Package 'lmmix'

Title: Linear Mixed Models with Correlated Residuals
Description: Fits Gaussian linear mixed models by explicitly optimizing the maximum likelihood or restricted maximum likelihood criterion. Random effects and correlated residual structures can be combined in the same model. Fixed-effect inference includes Satterthwaite and Kenward-Roger denominator degrees of freedom, type III tests, likelihood-ratio model comparisons, and estimated marginal means.
Authors: Aurélien Nicosia [aut, cre]
Maintainer: Aurélien Nicosia <[email protected]>
License: MIT + file LICENSE
Version: 0.4.0
Built: 2026-10-19 21:01:09 UTC
Source: https://github.com/AurelienNicosiaULaval/lmmix

Help Index


Augment data with fitted values and residuals

Description

Augment data with fitted values and residuals

Usage

## S3 method for class 'lmm'
augment(x, data = NULL, newdata = NULL, ...)

Arguments

x

An lmm object.

data

Optional data used for augmentation. By default, excluded rows are restored when the model used stats::na.exclude().

newdata

Optional new data. If supplied, it takes precedence over data.

...

Additional arguments passed to predict().

Value

A tibble with .fitted, .resid, and .std.resid columns.


Extract fixed effects

Description

Extract fixed effects

Usage

fixef(object, ...)

Arguments

object

A fitted model.

...

Additional arguments.


One-row model summary for an lmm model

Description

One-row model summary for an lmm model

Usage

## S3 method for class 'lmm'
glance(x, ...)

Arguments

x

An lmm object.

...

Additional arguments.

Value

A one-row tibble.


Fit a Gaussian linear mixed model

Description

lmm() explicitly evaluates a profiled ML or REML criterion for ⁠V = Z G Z' + R⁠. It can combine random effects with an independent, compound-symmetric, AR(1), full or fixed-band Toeplitz, or unstructured residual covariance. Missing values are handled according to na.action.

Usage

lmm(
  data,
  formula,
  random = NULL,
  repeated = NULL,
  structure = c("id", "cs", "ar1", "toep", "un"),
  method = c("REML", "ML"),
  ddf = c("satterthwaite", "residual", "kenward-roger"),
  weights = NULL,
  offset = NULL,
  contrasts = NULL,
  control = lmm_control(),
  na.action = stats::na.omit
)

Arguments

data

A data frame or tibble. Placing data first makes the function pipe-friendly.

formula

A two-sided fixed-effects formula.

random

Optional one-sided random-effects formula such as ~ 1 | subject, or a list of such formulas.

repeated

Optional one-sided repeated-measures formula such as ~ time | subject.

structure

Residual covariance structure: "id", "cs", "ar1", "toep", "toep(k)", or "un". The "toep" form estimates every available Toeplitz band. The "toep(k)" form estimates k bands, including the main diagonal, and fixes longer-lag covariances to zero.

method

Estimation method: restricted maximum likelihood ("REML") or maximum likelihood ("ML").

ddf

Denominator degrees-of-freedom method: "satterthwaite", "kenward-roger", or "residual".

weights

Optional known relative precision weights. The residual covariance is scaled on both sides by diag(1 / sqrt(weights)).

offset

Optional numeric offset added to the fixed-effect predictor. An offset() term in formula is also supported.

contrasts

Optional contrasts passed to stats::model.matrix().

control

An object returned by lmm_control().

na.action

Missing-value action: stats::na.omit(), stats::na.exclude(), or stats::na.fail().

Details

The random argument accepts a grouping formula or a list of independent grouping formulas. The repeated argument accepts one ordering variable and one grouping expression. Each repeated group may have at most one observation per ordering value. The likelihood factors independent connected covariance components separately. The fitted object retains the complete marginal covariance for model methods.

Value

An object of class lmm. The object stores fixed and random-effect estimates, covariance components, fitted values, residuals, optimization diagnostics, the analysis data, and the model matrices.

References

Harville, D. A. (1977). Maximum likelihood approaches to variance component estimation and to related problems. Journal of the American Statistical Association, 72(358), 320-338. doi:10.1080/01621459.1977.10480998

LaMotte, L. R. (2007). A direct derivation of the REML likelihood function. Statistical Papers, 48(2), 321-327. doi:10.1007/s00362-006-0335-6

Pinheiro, J. C., and Bates, D. M. (2000). Mixed-Effects Models in S and S-PLUS. Springer. doi:10.1007/b98882

Kenward, M. G., and Roger, J. H. (1997). Small sample inference for fixed effects from restricted maximum likelihood. Biometrics, 53(3), 983-997. doi:10.2307/2533558

Examples

fit <- lmm(
  data = nlme::Orthodont,
  formula = distance ~ age + Sex,
  random = ~ 1 | Subject
)
summary(fit)

Control numerical optimization for lmm()

Description

Control numerical optimization for lmm()

Usage

lmm_control(
  optimizer = c("auto", "nlminb", "optim"),
  optim_method = "BFGS",
  max_iter = 1000L,
  rel_tol = 1e-08,
  x_tol = 1e-08,
  initial = NULL,
  lower = -20,
  upper = 20,
  deriv_method = "Richardson",
  max_restarts = 3L,
  restart_scale = 0.25
)

Arguments

optimizer

Optimizer strategy: "auto", "nlminb", or "optim".

optim_method

Method passed to stats::optim() when optimizer = "optim".

max_iter

Maximum number of optimizer iterations.

rel_tol

Relative convergence tolerance.

x_tol

Parameter convergence tolerance for stats::nlminb().

initial

Optional numeric vector of unconstrained starting values.

lower, upper

Bounds for unconstrained covariance parameters.

deriv_method

Numerical differentiation method passed to numDeriv.

max_restarts

Maximum number of deterministic restart attempts after an unsuccessful initial fit.

restart_scale

Size of deterministic perturbations to starting values.

Value

An object of class lmm_control.


Standard methods for lmm fits

Description

Methods are provided for extracting likelihood quantities, fitted values, residuals, model matrices and formulas, as well as for prediction, type III testing and fixed-effect confidence intervals.

Usage

## S3 method for class 'lmm'
print(x, ...)

## S3 method for class 'lmm'
coef(object, ...)

## S3 method for class 'lmm'
vcov(object, adjusted = TRUE, ...)

## S3 method for class 'lmm'
logLik(object, ...)

## S3 method for class 'lmm'
AIC(object, ..., k = 2)

## S3 method for class 'lmm'
BIC(object, ...)

## S3 method for class 'lmm'
deviance(object, ...)

## S3 method for class 'lmm'
nobs(object, ...)

## S3 method for class 'lmm'
fitted(object, type = c("conditional", "marginal"), ...)

## S3 method for class 'lmm'
residuals(object, type = c("response", "pearson", "marginal"), ...)

## S3 method for class 'lmm'
plot(x, which = c("residuals", "qq", "fitted"), ...)

## S3 method for class 'lmm'
sigma(object, ...)

## S3 method for class 'lmm'
predict(
  object,
  newdata = NULL,
  re.form = NULL,
  allow.new.levels = FALSE,
  se.fit = FALSE,
  interval = c("none", "confidence", "prediction"),
  level = 0.95,
  na.action = stats::na.pass,
  ...
)

## S3 method for class 'lmm'
simulate(object, nsim = 1, seed = NULL, ...)

## S3 method for class 'lmm'
update(object, formula., ..., evaluate = TRUE)

## S3 method for class 'lmm'
model.matrix(object, data = NULL, ...)

## S3 method for class 'lmm'
model.frame(formula, ...)

## S3 method for class 'lmm'
formula(x, fixed.only = TRUE, ...)

## S3 method for class 'lmm'
terms(x, ...)

## S3 method for class 'lmm'
anova(
  object,
  ...,
  type = 3,
  refit = TRUE,
  test = c("chisq", "parametric.bootstrap"),
  nsim = 199L,
  seed = NULL
)

## S3 method for class 'lmm'
confint(object, parm = names(object$coefficients), level = 0.95, ...)

Arguments

x, object, formula

An lmm object. The formula name follows the argument name of the model.frame() generic.

...

Additional fitted lmm models for likelihood-ratio comparison, or arguments passed to the corresponding method.

adjusted

Whether vcov() returns the Kenward-Roger-adjusted covariance when available.

k

Penalty per parameter used by AIC().

type

For fitted(), either "conditional" or "marginal". For residuals(), one of "response", "pearson", or "marginal". For anova(), only type 3 is implemented.

which

Diagnostic plot to draw: standardized residuals against fitted values, a normal quantile-quantile plot, or observed against fitted values.

newdata

Optional data frame used for prediction.

re.form

NULL includes every empirical random-effect term, NA or ~ 0 excludes all random effects, and a random-effects formula or list of formulas selects a subset of fitted terms.

allow.new.levels

Whether conditional predictions may include new grouping levels. Their random contribution is zero when allowed.

se.fit

Whether predict() returns standard errors for the expected response. These standard errors use the fixed-effect covariance and condition on any empirical random effects included through re.form.

interval

Prediction interval type. "confidence" describes the expected response. "prediction" additionally includes the fitted residual variance but not uncertainty in empirical random effects.

level

Confidence level for fixed-effect and covariance intervals.

na.action

Missing-value action retained for prediction-method compatibility.

nsim

Number of simulations for a parametric-bootstrap comparison.

seed

Optional integer seed for a reproducible parametric bootstrap.

formula.

Optional formula update accepted by update().

evaluate

Whether update() evaluates the updated call.

data

Optional data frame used to construct a fixed-effects model matrix.

fixed.only

Whether formula() returns only the fixed formula. If FALSE, it returns fixed, random, and repeated formulas in a list.

refit

Whether REML models that differ in fixed effects are refitted with ML before comparison.

test

Reference test for likelihood-ratio model comparisons. The default "chisq" uses the usual asymptotic chi-squared reference. The "parametric.bootstrap" option simulates under each smaller model and is appropriate when covariance parameters can lie on a boundary.

parm

Parameters requested from confint(), supplied by name or fixed effect position. Use "beta_" for every fixed effect and "theta_" for every covariance parameter.

Details

Conditional fitted values and predictions include empirical random effects. Marginal values use fixed effects only. In prediction from new data, known grouping levels use their fitted random effect. New levels are rejected by default and receive a random contribution of zero only when explicitly allowed.

ranef() always returns a named list with one tibble per random-effect term, including for models with a single term. It returns an empty list for marginal models. sigma() is defined as sqrt(mean(diag(R))); it is a descriptive residual scale when residual variances differ across observations.

Value

The return value follows the corresponding base R generic.

References

Self, S. G., and Liang, K.-Y. (1987). Asymptotic properties of maximum likelihood estimators and likelihood ratio tests under nonstandard conditions. Journal of the American Statistical Association, 82(398), 605-610. doi:10.1080/01621459.1987.10478472

Davison, A. C., and Hinkley, D. V. (1997). Bootstrap Methods and Their Application. Cambridge University Press. doi:10.1017/CBO9780511802843


Estimated marginal means for an lmm model

Description

Marginal means use equal weights over nuisance-factor levels. Numeric covariates not listed in specs are held at their observed means. Multiplicity adjustment applies to pairwise p-values. Simultaneous Bonferroni confidence intervals are used automatically when p-values are adjusted, unless conf_adjust = "none" is requested.

Usage

lsmeans(
  object,
  specs,
  pairwise = FALSE,
  at = list(),
  level = 0.95,
  adjust = "none",
  conf_adjust = c("auto", "none", "bonferroni"),
  ...
)

Arguments

object

An lmm object.

specs

Variables defining the marginal means, supplied as a character vector or one-sided formula. Use pairwise ~ factor to request differences.

pairwise

Whether to return pairwise differences as well as means.

at

Named list overriding reference-grid values.

level

Confidence level.

adjust

Multiplicity adjustment passed to stats::p.adjust().

conf_adjust

Confidence-interval adjustment. "auto" uses Bonferroni intervals when adjust is not "none"; the alternatives are "none" and "bonferroni".

...

Reserved for future extensions.

Value

A tibble, or a list with lsmeans and contrasts tibbles when pairwise comparisons are requested.


Multi-site repeated-measures experiment

Description

An unbalanced experiment with three drugs in three centers and three repeated measurement times. This is the multilocation repeated-measures example described by Milliken and Johnson (2009, Section 28.3).

Usage

multicentre

Format

A data frame with 153 rows and 5 variables:

Center

Center identifier with levels R, S, and T.

Drug

Drug identifier with levels 1, 2, and 3.

Subject

Subject identifier within each center and drug.

Time

Repeated-measurement occasion with levels 1, 2, and 3.

Y

Continuous response, including 28 missing values.

Source

Milliken, G. A., and Johnson, D. E. (2009). Analysis of Messy Data, Volume 1: Designed Experiments (2nd ed.), Section 28.3. Chapman and Hall/CRC. doi:10.1201/EBK1584883340


Extract random effects

Description

Extract random effects

Usage

ranef(object, ...)

Arguments

object

A fitted model.

...

Additional arguments.


Support for emmeans

Description

These methods allow emmeans::emmeans() to recover the fixed-effects reference grid and use model-specific Satterthwaite degrees of freedom.

Usage

## S3 method for class 'lmm'
recover_data(object, frame = object$model_frame, ...)

## S3 method for class 'lmm'
emm_basis(object, trms, xlev, grid, ...)

Arguments

object

An lmm object.

frame

Model frame.

...

Additional arguments passed by emmeans.

trms, xlev, grid

Arguments supplied by emmeans.

Value

An emmeans data-recovery object.

A basis list used by emmeans.


Repeated-measures growth example from the SAS MIXED documentation

Description

Growth measurements for 11 girls and 16 boys at ages 8, 10, 12, and 14. SAS uses these Potthoff and Roy data in Example 79.2 of the SAS/STAT 14.3 documentation for the MIXED procedure.

Usage

sas_growth

Format

A data frame with 108 rows and 4 variables:

Person

Person identifier with 27 levels.

Gender

Gender factor with levels F and M.

Age

Age in years.

y

Continuous growth response.

Source

SAS Institute Inc. (2017). SAS/STAT 14.3 User's Guide, Example 79.2, Repeated Measures. https://support.sas.com/documentation/onlinedoc/stat/


Line-source irrigation example from the SAS MIXED documentation

Description

Winter-wheat yields for three cultivars in three blocks. Each plot contains twelve subplots arranged on two sides of a line-source sprinkler. SAS uses these data in Example 79.6 of the SAS/STAT 14.3 documentation to combine three random-intercept terms with a four-band Toeplitz residual covariance.

Usage

sas_line_source

Format

A data frame with 108 rows and 6 variables:

Block

Block identifier with three levels.

Cult

Winter-wheat cultivar with three levels.

Sbplt

Ordered subplot position from 1 to 12.

Irrig

Irrigation level with six levels.

Dir

Side of the sprinkler with levels North and South.

Y

Continuous yield response.

Source

SAS Institute Inc. (2017). SAS/STAT 14.3 User's Guide, Example 79.6, Line-Source Sprinkler Irrigation. https://support.sas.com/documentation/onlinedoc/stat/


Random-coefficients example from the SAS MIXED documentation

Description

Pharmaceutical stability measurements for three batches at six shelf ages. SAS uses these simulated data in Example 79.5 of the SAS/STAT 14.3 documentation for the MIXED procedure.

Usage

sas_random_coefficients

Format

A data frame with 108 rows and 4 variables:

Batch

Batch identifier with three levels.

Month

Shelf age in months.

Replicate

Replicate identifier within a batch and month.

Y

Assay response, including 24 missing values.

Source

SAS Institute Inc. (2017). SAS/STAT 14.3 User's Guide, Example 79.5, Random Coefficients. https://support.sas.com/documentation/onlinedoc/stat/


Split-plot example from the SAS MIXED procedure documentation

Description

A balanced split-plot experiment with four blocks, three whole-plot levels, and two subplot levels. SAS uses this data set in Example 79.1 of the SAS/STAT 14.3 documentation for the MIXED procedure.

Usage

sas_split_plot

Format

A data frame with 24 rows and 4 variables:

Block

Block identifier with four levels.

A

Whole-plot treatment factor with three levels.

B

Subplot treatment factor with two levels.

Y

Continuous response.

Source

SAS Institute Inc. (2017). SAS/STAT 14.3 User's Guide, Example 79.1, Split-Plot Design. https://support.sas.com/documentation/onlinedoc/stat/


Summarize an lmm fit

Description

Summarize an lmm fit

Usage

## S3 method for class 'lmm'
summary(object, level = 0.95, ...)

Arguments

object

An lmm object.

level

Confidence level for fixed effects.

...

Additional arguments.

Value

An object of class summary.lmm.


Tidy an lmm model

Description

Tidy an lmm model

Usage

## S3 method for class 'lmm'
tidy(
  x,
  effects = c("fixed", "ran_pars", "all"),
  conf.int = FALSE,
  conf.level = 0.95,
  ...
)

Arguments

x

An lmm object.

effects

Effects to return: fixed effects, covariance parameters, or both.

conf.int

Whether to include confidence limits for fixed effects.

conf.level

Confidence level.

...

Additional arguments.

Value

A tibble.


Extract covariance components

Description

Extract covariance components

Usage

VarCorr(object, ...)

Arguments

object

A fitted model.

...

Additional arguments.