Fit a Multilevel Model Specification
mlm_fit.RdCenters requested predictors, builds an lme4 formula, and fits the specified mixed-effects or multilevel model.
Arguments
- spec
An
"mlm_spec"object created withmlm_spec.- REML
Logical; whether to use restricted maximum likelihood for Gaussian models. Use
REML = FALSEwhen comparing nested models that differ in fixed effects.- optimizer
Optimizer passed to lme4, such as
"bobyqa","Nelder_Mead", or"nloptwrap".- maxfun
Maximum number of function evaluations.
Value
A list containing the fitted model, formula, centered data, centering code, and model specification.
Details
For Gaussian models, mlm_fit() calls lme4::lmer(). For supported
generalized mixed models, it calls lme4::glmer() or
lme4::glmer.nb(). The returned fit element is the underlying
lme4 model object, so users can pass it to standard lme4 methods.
The function performs requested grand-mean and cluster-mean centering before fitting. Users should inspect convergence messages, singular fits, residual patterns, and whether the random-effects structure is supported by the data.
Examples
# \donttest{
if (requireNamespace("lme4", quietly = TRUE)) {
dat <- example_hsb(n_schools = 4, min_students = 5, max_students = 6)
spec <- mlm_spec(
outcome = "mathscore",
fixed = list(ses = list(center = "CWC")),
grouping = list(schoolid = "schoolid"),
random = list(schoolid = list(intercept = TRUE, slopes = character(),
correlation = TRUE)),
data = dat
)
fit <- mlm_fit(spec)
summary(fit$fit)
}
#> Linear mixed model fit by REML ['lmerMod']
#> Formula: mathscore ~ ses_CWC + (1 | schoolid)
#> Data: spec$data
#> Control: control
#>
#> REML criterion at convergence: 155.6
#>
#> Scaled residuals:
#> Min 1Q Median 3Q Max
#> -1.33488 -0.59912 -0.08057 0.34960 2.33011
#>
#> Random effects:
#> Groups Name Variance Std.Dev.
#> schoolid (Intercept) 30.61 5.532
#> Residual 93.78 9.684
#> Number of obs: 22, groups: schoolid, 4
#>
#> Fixed effects:
#> Estimate Std. Error t value
#> (Intercept) 72.780 3.455 21.065
#> ses_CWC 3.224 3.773 0.854
#>
#> Correlation of Fixed Effects:
#> (Intr)
#> ses_CWC 0.000
# }