These methods compute the marginal covariance matrix \(V = Var(y)\) for fitted linear and linear mixed models of the form $$y = X \beta + Z u + \epsilon,$$ where \(u\) and \(\epsilon\) are random effects and residual errors.

The returned matrix represents the implied covariance structure of the response vector, combining contributions from both random effects and residuals.

cov_matrix(fit, ...)

# S3 method for class 'lmerMod'
cov_matrix(fit, ...)

# S3 method for class 'lme'
cov_matrix(fit, ...)

# S3 method for class 'gls'
cov_matrix(fit, ...)

# S3 method for class 'lm'
cov_matrix(fit, ...)

Arguments

fit

A fitted model object. Supported classes: lmerMod (from lme4), lme and gls (from nlme).

...

Additional arguments (currently ignored).

Value

A sparse matrix (class "dgCMatrix") representing the marginal covariance matrix \(V\).

Methods

cov_matrix.lmerMod

For lmerMod models from the lme4 package. Computes \(V = Z D Z' + \sigma^2 I\).

cov_matrix.lme

For lme models from the nlme package. Computes block-diagonal covariance with group-specific structures.

cov_matrix.gls

For gls models from the nlme package. Includes optional correlation structures.

Examples

if (require(nlme) && require(Matrix)) {
  ## gls example
  fit_gls <- gls(distance ~ age, data = Orthodont)
  V_gls <- cov_matrix(fit_gls)
  print(V_gls)

  ## lme example
  fit_lme <- lme(distance ~ age, random = ~ 1 | Subject, data = Orthodont)
  V_lme <- cov_matrix(fit_lme)
  print(V_lme)
}
#> Loading required package: nlme
#> 
#> Attaching package: ‘nlme’
#> The following object is masked from ‘package:lme4’:
#> 
#>     lmList
#> Error in cov_matrix(fit_gls): could not find function "cov_matrix"

if (require(lme4) && require(Matrix)) {
  ## lmerMod example
  fit_lmer <- lme4::lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
  V_lmer <- cov_matrix(fit_lmer)
  print(V_lmer)
}
#> Error in cov_matrix(fit_lmer): could not find function "cov_matrix"