12 Mixed-Effects Models
12.1 Prerequisites
Answer the following questions to see if you can bypass this chapter. You can find the answers at the end of the chapter in Section 12.20.
- What is the primary limitation of repeated-measures ANOVA for analyzing data with multiple sources of random variation (e.g., participants and items)?
- What happens to the standard errors when you fit an ordinary linear regression to clustered (non-independent) observations?
- In a mixed-effects model, what do random effects represent, and when should you declare a factor as random rather than fixed?
12.2 Learning objectives
By the end of this chapter you should be able to:
- Distinguish fixed, random, nested, and crossed effects.
- Fit linear and generalized linear mixed models with
lme4::lmer()andlme4::glmer()and read their output. - Specify random intercepts (
(1 | group)), random slopes ((x | group)), and uncorrelated random effects ((1 + x || group)). - Explain why p-values and degrees of freedom are contested in mixed models, and use
lmerTest,pbkrtest, orparametric bootstrapto obtain approximate tests. - Diagnose convergence warnings and take appropriate action: rescaling, simplifying random effects, switching optimizer.
- Compute and interpret the intraclass correlation coefficient (ICC).
- Recognize crossed random effects (e.g., subjects and items) and write the corresponding
lmer()formula.
12.3 Orientation
Clustered and repeated-measures data are the norm in biomedicine. Patients are nested in hospitals, and observations are nested within subjects. A study may also have multiple pathology slides per patient or multiple time points per individual. Ignoring the clustering leads to incorrect standard errors, which are usually too small. The reason is that non-independence inflates the effective sample size used by the inference. On the other hand, a model that treats every cluster level as a separate parameter (one intercept per subject) wastes degrees of freedom and does not generalize to new subjects.
Mixed-effects models sit between these two extremes. They treat between-cluster variation as a random component drawn from a distribution, and the variance of that distribution is estimated from the data. This produces correctly calibrated standard errors and generalizable inference. It also produces ‘partial pooling’ of cluster-specific estimates toward the overall mean. The lme4 package by Douglas Bates is the standard implementation in R.
We begin with the decisions that belong to the statistician, and with the reasons ordinary regression fails on clustered data. We then present fixed and random effects, the lmer() syntax, REML and ML, and the contested question of p-values. Lastly, we shall consider BLUPs, the ICC, convergence warnings, GLMMs, a worked example, and collaboration with an LLM.
12.4 The statistician’s contribution
Mixed models are not harder to fit than ordinary linear models, since lmer(y ~ x + (1 | subject), data = d) is trivial syntax. They are harder to specify, interpret, and defend.
Fixed or random? A factor is fixed when its levels are the only ones of interest. Treatment vs. control is an example: nobody cares about a hypothetical ‘treatment B’ that was not in the trial. A factor is random when the observed levels are a sample from a population and the inferential target is that population. Subjects, hospitals, sites, and items in a psycholinguistic experiment are typical. The same variable can be either, depending on the question. With many levels and sparse per-level data, random tends to be the more honest choice. With few levels and ample data per level, fixed may be cleaner.
Which random effects to include. Barr et al. (2013) made the case for ‘maximal’ random effects, meaning random slopes for every fixed effect that varies within cluster. On the minus side, the cost is convergence; on the plus side, the benefit is honest standard errors. Matuschek et al. (2017) argue for parsimony when maximal models do not converge. The right answer depends on the data. With 8 subjects and 1000 trials each, a random slope per subject is feasible. With 50 subjects and 4 trials each, it probably is not.
ICC interpretation. The intraclass correlation \(\rho = \sigma^2_\text{between} / (\sigma^2_\text{between} + \sigma^2_\text{within})\) measures the proportion of total variance attributable to the cluster level. An ICC of 0.05 means that clusters explain 5% of the variance, and an ICC of 0.5 means half. The implications for analysis differ. At low ICC, ignoring clustering may not disastrously bias inference, although it should still be modeled. At high ICC, ignoring it definitely does. We would much rather know the ICC of a design before submitting for peer review than learn it during review.
Convergence warnings are not optional. A non-converging mixed model has not been fit, and reporting its coefficients is reporting numerical noise. The right responses (rescaling predictors, simplifying random effects, switching optimizer) should all be documented and reproducible. Ignoring the warning and reporting anyway is a serious methodological failure.
12.5 Why ordinary regression fails on clustered data
To illustrate, consider repeated measurements on each of \(n\) subjects, with \(K\) trials per subject and \(nK\) observations in total. A naive lm(y ~ x, data = d) treats all \(nK\) observations as independent.
Two problems result:
Standard errors too small. The effective sample size is roughly \(nK / (1 + (K-1) \rho)\), not \(nK\), where \(\rho\) is the ICC. For \(K = 10\) and \(\rho = 0.5\), the effective sample size is \(n \cdot 10 / 5.5 \approx 1.8 n\), not \(10 n\). Ignoring this inflates the Type-I error from the nominal 5% to 20 to 30% in many designs.
Misallocated variance. A subject-specific intercept that is not modeled as a random effect leaks into the residual error term. This inflates \(\hat\sigma\) and reduces the apparent precision of within-subject effects.
Two alternatives are sometimes proposed. Aggregating to subject means throws away within-subject variability, often halving statistical power. A separate analysis per subject does not generalize to new subjects.
Mixed models address both problems at once. They model between-cluster variation explicitly, so that it is neither ignored nor aggregated away.
12.6 Fixed vs. random effects
A fixed effect estimates a parameter at the levels we observed. The treatment in a clinical trial is fixed. Only those treatments are of interest, and a replication of the trial would use the same arms.
A random effect treats the observed levels as a sample from a distribution, and that distribution’s parameters are estimated from the data. Subjects in a longitudinal study are random. That is, this study’s 100 subjects are not the inferential target; the population they were sampled from is.
A practical heuristic is as follows. Suppose the experiment would be replicated with new units (subjects, items, sites), and those new units would not be the same physical entities as the old ones. Then that factor is random.
In symbols, a random intercepts model is
\[ y_{ij} = \alpha + \mathbf{x}_{ij}^T \boldsymbol\beta + u_j + \varepsilon_{ij}, \quad u_j \sim N(0, \sigma_u^2), \quad \varepsilon_{ij} \sim N(0, \sigma^2). \]
The fixed effects (\(\alpha\), \(\boldsymbol\beta\)) and the two variance components (\(\sigma_u^2\), \(\sigma^2\)) are estimated. The cluster-specific deviations \(u_j\) are predicted (BLUPs, Best Linear Unbiased Predictors). They are not estimated, and they are pulled toward zero by an amount that depends on how much data each cluster has. This is partial pooling: clusters with little data borrow strength from clusters with more data.
12.7 lmer() syntax
library(lme4)
# random intercept by subject
lmer(y ~ x + (1 | subject), data = d)
# random intercept and random slope on x
lmer(y ~ x + (1 + x | subject), data = d)
lmer(y ~ x + (x | subject), data = d) # equivalent
# uncorrelated random intercept and slope
lmer(y ~ x + (1 + x || subject), data = d)
lmer(y ~ x + (1 | subject) + (0 + x | subject), data = d) # equivalent
# nested random effects: clinics within regions
lmer(y ~ x + (1 | region/clinic), data = d)
lmer(y ~ x + (1 | region) + (1 | region:clinic), data = d) # equivalent
# crossed random effects: subjects and items
lmer(y ~ x + (1 | subject) + (1 | item), data = d)In the | separator, the random effects formula is on the left and the grouping factor is on the right. The double bar || removes the correlation between random intercept and slope.
The choice of random-effects structure is consequential. Random slopes for fixed effects that vary within cluster are sometimes essential for honest inference (Barr et al., 2013). Unfortunately, they are also computationally hard, and a model with many random slopes may not converge.
12.8 REML vs. ML
lmer() defaults to REML (restricted maximum likelihood) estimation. REML corrects the downward bias of ML estimates of variance components, and in balanced designs its estimates are unbiased. For comparing nested models that differ in fixed effects, we refit with ML (REML = FALSE):
m1 <- lmer(y ~ x1 + (1 | g), data = d, REML = FALSE)
m2 <- lmer(y ~ x1 + x2 + (1 | g), data = d, REML = FALSE)
anova(m1, m2)anova() automatically refits REML fits with ML before comparing them (its default is refit = TRUE). For comparing models that differ only in random effects, REML is correct. In that case we pass refit = FALSE to keep the REML fits.
12.9 p-values and degrees of freedom
summary(lmer_fit) does not show p-values for fixed effects, because the appropriate reference distribution is not exactly known. The denominator degrees of freedom for the t-statistic depend on the random-effects structure, the data, and the test in subtle ways. But how are we to obtain a p-value at all? There are three approaches.
lmerTest::lmer() wraps
lmer()and adds Satterthwaite-approximated degrees of freedom and p-values:library(lmerTest) fit <- lmer(y ~ x + (1 | subject), data = d) summary(fit) # now includes p-valuesThis is a reasonable default for moderate sample sizes.
pbkrtest::KRmodcomp() uses the Kenward-Roger approximation. It is generally more accurate for small samples but more expensive.
Likelihood ratio tests via parametric bootstrap.
pbkrtest::PBmodcomp()is the gold standard for small-sample inference, but it is slow.
For variance components, likelihood-ratio tests have a boundary issue. The null hypothesis \(\sigma^2 = 0\) places the parameter on the boundary of the parameter space, and the chi-square reference distribution is then wrong. It should be a 50:50 mixture with a point mass at 0. The standard fix is to halve the reported p-value.
12.10 Predicted random effects (BLUPs)
ranef(fit) returns the cluster-specific deviations from the fixed-effect estimates. These are useful for the following purposes:
- Plotting cluster-specific fits.
- Identifying outlier clusters (extreme BLUPs).
- Reporting between-cluster variation.
library(lme4)
fit <- lmer(Reaction ~ Days + (Days | Subject),
data = sleepstudy)
re <- ranef(fit)$Subject # data frame of intercept and slope BLUPs
head(re)BLUPs are shrunk toward zero relative to the cluster-specific OLS estimates. The shrinkage is greater for clusters with less data, and it is deliberate. That is, it stabilizes estimates for sparsely-sampled clusters by borrowing information from the population.
12.11 ICC: how much clustering is there?
For a random-intercept model, the intraclass correlation is
\[ \rho = \frac{\sigma^2_u}{\sigma^2_u + \sigma^2}. \]
vc <- as.data.frame(VarCorr(fit))
icc <- vc$vcov[1] / sum(vc$vcov)
iccAlternatively, performance::icc(fit) offers a tidier interface. The ICC quantifies how much of the total variance is between-cluster vs. within-cluster:
- ICC = 0: clusters do not differ; ordinary regression would be fine (rare).
- ICC = 0.05 to 0.2: typical of randomized trials with modest cluster effects.
- ICC = 0.3 to 0.6: typical of biological measurements with strong subject differences.
- ICC = 0.9: nearly all variance is between clusters; you may have very few independent observations.
Reporting the ICC alongside the fixed-effect estimates makes the strength of clustering transparent to the reader.
12.12 Convergence warnings
lmer warnings are common with realistic data and complex random-effects structures. Common messages include the following:
- ‘Model failed to converge with max|grad| …’
- ‘Model is nearly unidentifiable: large eigenvalue ratio’
- ‘singular fit: see ?isSingular’
The first two indicate that the optimizer may have stopped before finding a clearly-defined optimum. The third indicates that the optimum lies on the boundary of the parameter space, with one or more variance components at (or near) zero. Reporting the model output without addressing the warning is unsafe.
The standard remedies, roughly in order, are as follows.
- Rescale predictors. Continuous predictors with wildly different units inflate the condition number. We center and scale them with
scale(). - Simplify random effects. We drop random slopes for predictors that vary little within cluster, or use
||to remove correlations between random effects. - Switch optimizer.
control = lmerControl(optimizer = "bobyqa")often succeeds where the default fails. - Increase iteration limit.
optCtrl = list(maxfun = 1e5). - Use the singular-fit check.
isSingular(fit)indicates that one or more variance components have collapsed to (near) zero. The corresponding random effect should probably be removed.
If none of these work, the data may not be rich enough to support the model we specified. We then simplify the random-effects structure, starting with the slopes that have the smallest estimated variance, until we have a converged, interpretable model. We should document what we tried.
12.13 GLMMs with glmer()
glmer() extends mixed models to non-normal outcomes:
glmer(y ~ x + (1 | subject),
family = binomial, data = d) # logistic GLMM
glmer(count ~ x + (1 | subject),
family = poisson, data = d) # Poisson GLMMThe computational cost is substantially higher than for lmer, since the random-effects integration has no closed form for non-normal outcomes. The default Laplace approximation works well for moderate ICC and reasonable cluster size. For small clusters or high ICC, we increase nAGQ (adaptive Gauss-Hermite quadrature points), and nAGQ = 7 is often a good compromise.
Convergence problems are even more common in GLMMs than in LMMs. The same remedies apply. In addition, binary GLMMs with sparse data often have boundary issues, in which one or more random effects have estimated variance near zero. This is a flag for re-thinking the model.
For overdispersed counts, MASS::glmmPQL() or glmmTMB::glmmTMB() provide more flexible alternatives. The latter is faster and supports a richer family of distributions (negative binomial, beta-binomial, zero-inflated, hurdle).
12.14 Worked example: sleep deprivation study
library(lme4)
library(lmerTest)
data(sleepstudy)
# subjects measured over 10 days; reaction time as response
fit <- lmer(Reaction ~ Days + (Days | Subject),
data = sleepstudy)
summary(fit)
# fixed effect: average reaction time increases by ~10ms/day
# random effects: subjects vary in baseline RT and in slope on Days
# ICC of the intercept
performance::icc(fit)
# subject-specific predicted slopes
ranef(fit)$SubjectThe fixed effects table shows the population-average effect of sleep deprivation. The random-effects variance components show how much subjects vary in baseline reaction time and in their day-by-day slopes. We note that the correlation between the two random effects is often substantial in data of this kind. It indicates whether subjects with high baselines also tend to have steep slopes.
12.15 Collaborating with an LLM on mixed models
Large language models handle the syntax of lmer reasonably well. They handle the conceptual judgments much less reliably.
Prompt 1: writing the formula. We describe the data structure (subjects nested within sites; items crossed with subjects; etc.) and ask: ‘write the lmer formula for the correct random-effects structure.’
What to watch for. Confusion between nested and crossed random effects is the most common LLM error. For ‘subjects within sites’, the formula is (1 | site/subject) if subject IDs are reused across sites. It is (1 | site) + (1 | subject) if subject IDs are unique. For ‘subjects answering items’, subjects and items are crossed, so the formula is (1 | subject) + (1 | item).
Verification. We ask the LLM to expand its proposed formula into the explicit form (e.g., (1 | site/subject) expands to (1 | site) + (1 | site:subject)). If the expansion is correct, the formula is correct.
Prompt 2: handling convergence warnings. We paste the warning message and ask: ‘what is happening, and what should I try?’
What to watch for. We expect the standard suite of remedies. Suppose the LLM suggests ‘use lmerTest’. That is not a fix for convergence; it is only a way to get p-values once the model converges. If it suggests ‘just use the model anyway’, we push back, since a non-converging model is not a fit.
Verification. We apply each suggested remedy in turn and track which one resolves the warning. Often the answer is to rescale predictors and to drop a random slope. Rarely is it any single one of the more exotic options.
Prompt 3: interpreting random-effect variance. We paste the summary(fit) output and ask: ‘how should I interpret the random-effects variance components?’
What to watch for. The variance components are reported as standard deviations and variances. The interpretation is on the response scale (or, for GLMMs, on the link scale). We make sure the LLM does not confuse the random-effect variance (\(\sigma^2_u\)) with the residual variance (\(\sigma^2\)) or with the fixed-effect coefficients.
Verification. The ICC is a sanity check. We compute it from the variance components and confirm that it falls in a plausible range for the design.
12.16 Principle in use
Three habits define defensible mixed-model practice:
- Specify random effects deliberately. We identify which factors are sampled (random) and which are fixed. We include random slopes for within-cluster fixed effects when the data support them, and drop them when convergence demands it.
- Report the ICC. The strength of clustering is part of the result. Readers need to know whether a design is tightly clustered, with little independent information, or loosely clustered.
- Take convergence warnings seriously. A non-converging mixed model has not been fit. We document what was done to address the warning, since ignoring it is not a defensible choice.
12.17 Exercises
- Using
lme4::sleepstudy, fitlmer(Reaction ~ Days + (Days | Subject)). Extract the fixed effects, the variance components, and the BLUPs. Plot the subject-specific fitted lines on top of the data. - Compare the fixed-effect slope from exercise 1 to the slope from
lm(Reaction ~ Days)ignoring subject. Explain why they differ. - Simulate data from a random-intercept logistic GLMM with a known ICC. Fit the model with
glmer()and check whether the fitted ICC is close to the truth. - Refit the sleepstudy model with uncorrelated random intercepts and slopes (
||). Compare AIC. Does the correlation matter? - Take the sleepstudy data and induce a non-convergence warning by including a random slope for a constructed covariate that has no within-subject variation. Apply the standard remedies in order and document which one resolves the warning.
12.18 Further reading
- (Bates et al., 2015), the authoritative JSS paper on
lme4. - (Brown, 2021), recent applied LMM introduction in R.
- (McCulloch et al., 2008), the standard textbook on GLMs and GLMMs.
- (Bolker, n.d.), Ben Bolker’s GLMM FAQ; indispensable for diagnosing convergence and specification issues.
- (Barr et al., 2013), the influential ‘keep it maximal’ paper.
- (Matuschek et al., 2017), the more cautious response on parsimony.
12.19 Practice test
The following multiple-choice questions exercise the chapter’s content. Attempt each question before expanding the answer.
12.19.1 Question 1
What is the primary limitation of repeated-measures ANOVA when analyzing data where participants respond to multiple trials?
- They require balanced data designs
- They cannot model both participant-level and item-level variability simultaneously
- They are computationally too expensive
- They require normally distributed data
B. Repeated-measures ANOVA handles a single random-factor structure. Mixed-effects models generalize to multiple crossed or nested random factors.
12.19.2 Question 2
What happens when observations are not independent in standard regression analysis?
- The model will automatically correct for this violation
- The results will be exactly the same as with independent observations
- The independence assumption is violated, leading to incorrect standard errors
- The model will fail to converge
C. Non-independence inflates the effective sample size used by the analysis, which produces incorrectly narrow standard errors.
12.19.3 Question 3
In the context of mixed-effects models, what are ‘random effects’?
- Effects that are randomly selected by the researcher
- Statistical noise that should be eliminated
- Effects that model random variation in grouping factors (like participants)
- Unpredictable variables that cannot be modeled
C. Random effects allow inference to generalize to the population of groups from which the observed levels were drawn.
12.19.4 Question 4
lmer returns a ‘singular fit’ warning. The most likely interpretation is:
- A clear bug in
lme4; report it.
- A clear bug in
- One or more variance components have collapsed to near zero, indicating a random effect that the data cannot support.
- The fixed effects are not identifiable.
- Ignore it; singular fits are still valid.
B. Drop the corresponding random effect (or simplify the structure) and refit. A singular fit is not a model that can be reported as-is.
12.19.5 Question 5
Your design has 20 clusters of size 30, with ICC = 0.3. Approximately how does the effective sample size compare to the nominal sample size of 600?
- The same, 600.
- About 62 (effective).
- About 300 (effective).
- About 20 (effective).
B. Design effect = \(1 + 29 \cdot 0.3 = 9.7\). Effective \(n = 600 / 9.7 \approx 62\). This reduction is the standard motivation for mixed models. That is, the naive sample size greatly overstates the information content of clustered data.
12.20 Prerequisites answers
- Repeated-measures ANOVA cannot simultaneously model multiple crossed or nested sources of random variation (e.g., participants and items). It assumes a single random-factor structure and balanced data, both of which are commonly violated in modern designs.
- Non-independence leaves the point estimates approximately unbiased but produces incorrect standard errors, typically too small. As a result, confidence intervals are too narrow and p-values too optimistic. The inflation factor is roughly \(\sqrt{1 + (K - 1) \rho}\) for clusters of size \(K\) with ICC \(\rho\). For a typical longitudinal study with ICC = 0.5 and 10 visits per subject, the naive standard errors are about \(\sqrt{5.5} \approx 2.3\) times too small.
- Random effects model variation in grouping factors whose levels are a sample from a larger population of interest (e.g., subjects, clinics, items). Declare a factor random when you wish to generalize inference to the population of levels, not just the specific levels observed. Declare it fixed when the observed levels are themselves the inferential target. The same variable can be either, depending on the question.