R Code and Instructions
On this page
- What these notes cover
- 15.5 — Within-Subjects Designs
- 15.5.2 — Models for Longitudinal Data
- 15.5.3 — Review of the ANOVA Mixed-Model Approach
- 15.6 — Mixed-Effects Models
- 15.6.2 — An Example of Maximum Likelihood Estimation
- 15.6.4 — Numerical Example
- The ANOVA approach first (Table 15.2)
- The mixed-effects approach (Table 15.3)
- 15.6.6 — Graphical Representation of Longitudinal Data
- 15.6.7 — Graphical Representation of the Random Intercept Model
- 15.6.10 — Numerical Example
- 15.6.11 — Graphical Representation of a Model with Random Slope and Intercept
- 15.6.14 — Straight-Line Change Model
- Confidence intervals on the fixed effects
- 15.6.15 — Graphical Representation of a Growth Curve Model
- 15.7 — An Alternative Approach and Conceptualization
- The errors a cell-means model leaves behind (Tables 15.7 to 15.9)
- The unstructured model (Table 15.10)
- 15.7.1 — Additional Covariance Matrix Structures
- Compound symmetry (Table 15.11)
- A first-order autoregressive structure (Table 15.12)
- 15.7.3 — Overview of Broader Model Comparison
- In DMAR
- How to Cite This Page
- References
Examples follow the book’s section numbers.
What these notes cover
Chapter 15 introduces mixed-effects (multilevel) models for within-subjects data. Compared with the traditional univariate ANOVA of Chapter 11, the mixed-effects approach:
- Handles missing observations at any time point (no listwise deletion).
- Allows the variance-covariance structure of the within-subjects factor to be modeled rather than assumed (compound symmetry, unstructured, AR(1), and so on).
- Estimates fixed effects by restricted maximum likelihood (REML) and reports the random part of the model as variances and covariances rather than as per-person effects.
Every analysis below is worked first in base R or in the package a
reader is likeliest to already know — aov(),
lm(), anova(), lme4::lmer(),
nlme::gls() — with the corresponding DMAR
call shown alongside it, labelled.
The book’s results come from SAS PROC MIXED. Where R and PROC MIXED differ it is almost always in the denominator degrees of freedom, which the two programs determine by different rules; the parameter estimates, the variance components, and the statistics themselves agree, and those are the quantities confirmed against the book below.
Chapter 1 covers the R groundwork these notes take for granted:
installing packages from CRAN, loading them, and the way the book’s data
sets are named. This chapter draws on one of them —
chapter_15_table_1, the hypothetical McCarthy data of Table
15.1.
HideShow
# Load all of the packages used.
library(tidyverse) # data wrangling and plotting (dplyr, ggplot2, and friends)
library(DMAR) # design, measurement, and analysis
library(AMCP) # the textbook's data sets
library(broom.mixed) # tidy mixed-model output into data frames
library(lme4) # fit mixed-effects models
library(lmerTest) # degrees of freedom and p-values for lmer fixed effects
library(nlme) # mixed models with flexible covariance structures (gls/lme)
library(gt) # polished HTML tables
library(gtsummary) # publication-ready regression / comparison tables
library(modelsummary) # side-by-side model-comparison tables
library(sjPlot) # tab_model(): mixed-model tables, including the ICC15.5 — Within-Subjects Designs
15.5.2 — Models for Longitudinal Data
The data are McCarthy scores for 12 children, each measured at 30,
36, 42, and 48 months. The book stores them one column per time point
(Table 15.1), and chapter_15_table_1 in
AMCP carries that layout unchanged.
HideShow
# A tibble: 12 × 5
Months30 Months36 Months42 Months48 subject
<int> <int> <int> <int> <fct>
1 108 96 110 122 1
2 103 117 127 133 2
3 96 107 106 107 3
4 84 85 92 99 4
5 118 125 125 116 5
6 110 107 96 91 6
7 129 128 123 128 7
8 90 84 101 113 8
9 84 104 100 88 9
10 96 100 103 105 10
11 105 114 105 112 11
12 113 117 132 130 12 HideShow
[1] 109 120 104 90 121 101 127 97 94 101 109 123HideShow
Months30 Months36 Months42 Months48
103 107 110 112 HideShow
[1] 108The mixed-effects functions need one row per observation, so the next
step is the reshape. Time is carried two ways: Months, a
four-level factor for the cell-means (ANOVA) models, and
month_c, the number of months since the first wave, for the
growth models. Section 15.6.8 recodes month as 0, 6, 12, and 18 for
exactly this purpose (book p. 882): putting zero at the first wave makes
the growth-model intercept the population mean at 30 months. The level
labels are read out of the column names rather than assigned
positionally, so factor() is left to do nothing but fix the
order of the levels.
HideShow
mcc_long <- mcc_wide |>
pivot_longer(starts_with("Months"), names_to = "wave", values_to = "Score") |>
mutate(
months = as.integer(str_remove(wave, "Months")), # 30, 36, 42, 48
month_c = months - 30, # months since the first wave
Months = factor(months, levels = c(30, 36, 42, 48))
) |>
select(subject, Months, months, month_c, Score)
mcc_longHideShow
# A tibble: 48 × 5
subject Months months month_c Score
<fct> <fct> <int> <dbl> <int>
1 1 30 30 0 108
2 1 36 36 6 96
3 1 42 42 12 110
4 1 48 48 18 122
5 2 30 30 0 103
6 2 36 36 6 117
7 2 42 42 12 127
8 2 48 48 18 133
9 3 30 30 0 96
10 3 36 36 6 107
# ℹ 38 more rowsTwo pairs of children share the same marginal mean — subjects 1 and 11 at 109, and subjects 6 and 10 at 101. The book notes this on p. 878, where it explains why only ten distinct fitted trajectories appear in Figure 15.3.
HideShow
101 109
2 2 15.5.3 — Review of the ANOVA Mixed-Model Approach
Before any mixed-effects model, the book reviews the Chapter 11
analysis of these same data: the omnibus for the within-subjects factor is ,
which in base R is the within-subject stratum of aov() with
an Error(subject) term.
HideShow
Error: subject
Df Sum Sq Mean Sq F value Pr(>F)
Residuals 11 6624 602.2
Error: Within
Df Sum Sq Mean Sq F value Pr(>F)
Months 3 552 184.00 3.027 0.0432 *
Residuals 33 2006 60.79
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1HideShow
#> Months: SS 552, df 3, MS 184.00, F = 3.03, p = .0432 — matches book p. 863,
#> and the "timecat" line of Table 15.2, book p. 871
#> Residuals: SS 2006, df 33, MS 60.79 — the "Error" line of Table 15.2, p. 871
#> subject stratum: SS 6624, df 11, MS 602.18 — the "id" line of Table 15.2,
#> book p. 871The same omnibus test written as an APA-style table, with sums of squares, df, , , and partial . The table is built with gt, which formats properly in HTML.
HideShow
within_tbl <- summary(aov_fit)[["Error: Within"]][[1L]]
ss_res <- within_tbl["Residuals", "Sum Sq"] # error SS, for partial eta^2
tibble(
Source = rownames(within_tbl),
SS = within_tbl[["Sum Sq"]],
df = within_tbl[["Df"]],
MS = within_tbl[["Mean Sq"]],
Fstat = within_tbl[["F value"]],
p = within_tbl[["Pr(>F)"]]
) |>
mutate(
# Partial eta-squared: the effect's share of effect-plus-error variance.
peta = if_else(Source == "Residuals", NA_real_, SS / (SS + ss_res))
) |>
gt() |>
fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
fmt_number(columns = peta, decimals = 3) |>
fmt_number(columns = p, decimals = 4) |>
sub_missing(missing_text = "") |>
cols_label(Fstat = md("*F*"), p = md("*p*"),
peta = md("Partial η<sup>2</sup>")) |>
tab_header(title = md("**Within-subjects analysis of variance** for McCarthy score")) |>
cols_align(align = "center", columns = -Source)| Within-subjects analysis of variance for McCarthy score | ||||||
| Source | SS | df | MS | F | p | Partial η2 |
|---|---|---|---|---|---|---|
| Months | 552.00 | 3 | 184.00 | 3.03 | 0.0432 | 0.216 |
| Residuals | 2,006.00 | 33 | 60.79 | |||
15.6 — Mixed-Effects Models
15.6.2 — An Example of Maximum Likelihood Estimation
The chapter motivates maximum likelihood with four observed scores (3.0, 4.1, 4.3, 4.6) drawn from a normal distribution with known standard deviation 1. For any candidate mean , the likelihood of the sample is the product of the four normal densities. Graphing that product over a range of shows it peaks at the sample mean, which is the maximum likelihood estimate.
HideShow
obs <- c(3.0, 4.1, 4.3, 4.6) # the four observed scores, book p. 865
mu <- seq(2, 6, length.out = 400) # candidate values for the mean
# Likelihood is the product of the four normal densities (sigma = 1) at each mu.
lik <- vapply(mu, function(m) prod(dnorm(obs, mean = m, sd = 1)), numeric(1))
lik_df <- data.frame(mu = mu, likelihood = lik)
mle <- mean(obs) # the value of mu that maximizes the likelihood
mleHideShow
[1] 4HideShow
#> 4.0 — matches the maximum likelihood estimate on book p. 866
ggplot(lik_df, aes(mu, likelihood)) +
geom_line(color = "black", linewidth = 1) +
geom_vline(xintercept = mle, color = "#0C2340",
linetype = "dashed", linewidth = 0.7) +
annotate("text", x = mle + 0.3, y = max(lik_df$likelihood),
label = sprintf("hat(italic('μ')) == '%.1f'", mle), parse = TRUE,
color = "#0C2340", hjust = 0, vjust = 0.5, size = 3.3) +
labs(title = "Figure 15.1. Likelihood as a function of the mean",
x = expression("Candidate population mean"~italic("μ")),
y = "Likelihood")Figure 15.1. Likelihood of the sample data as a function of the population mean .
15.6.4 — Numerical Example
The ANOVA approach first (Table 15.2)
Table 15.2 is the PROC GLM analysis of these data, which treats
subjects as just another fixed classification. In base R that is an
ordinary two-factor lm() with no interaction, and
anova() gives the same partition.
HideShow
Analysis of Variance Table
Response: Score
Df Sum Sq Mean Sq F value Pr(>F)
subject 11 6624 602.18 9.9063 1.314e-07 ***
Months 3 552 184.00 3.0269 0.04322 *
Residuals 33 2006 60.79
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1HideShow
#> subject: SS 6624, df 11, MS 602.18, F = 9.91 — matches Table 15.2, book p. 871
#> Months: SS 552, df 3, MS 184.00, F = 3.03, p = .0432 — Table 15.2, p. 871
#> Residuals: SS 2006, df 33, MS 60.79 — Table 15.2, p. 871
# The overall "Model" line and the fit summary SAS prints above the source table.
summary(fit_glm)$r.squaredHideShow
[1] 0.7815291HideShow
[1] 7.796658The mixed-effects approach (Table 15.3)
A single random intercept for subject imposes a
compound-symmetry structure on the four repeated scores: every pair of
time points is assumed to have the same covariance. This is the
mixed-effects equivalent of the traditional univariate within-subjects
ANOVA just fit.
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Score ~ Months + (1 | subject)
Data: mcc_long
REML criterion at convergence: 340.8
Scaled residuals:
Min 1Q Median 3Q Max
-1.88627 -0.44709 -0.09063 0.53924 1.70501
Random effects:
Groups Name Variance Std.Dev.
subject (Intercept) 135.35 11.634
Residual 60.79 7.797
Number of obs: 48, groups: subject, 12
Fixed effects:
Estimate Std. Error df t value Pr(>|t|)
(Intercept) 103.000 4.043 18.117 25.477 1.22e-15 ***
Months36 4.000 3.183 33.000 1.257 0.21769
Months42 7.000 3.183 33.000 2.199 0.03498 *
Months48 9.000 3.183 33.000 2.828 0.00791 **
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Correlation of Fixed Effects:
(Intr) Mnth36 Mnth42
Months36 -0.394
Months42 -0.394 0.500
Months48 -0.394 0.500 0.500HideShow
Type III Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
Months 552 184 3 33 3.0269 0.04322 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1The fixed-effect estimates in Table 15.3 are expressed against the last time point, because PROC GLM and PROC MIXED fix the effect of the final level at zero. R’s default treatment contrasts use the first level instead, so to read the book’s , , straight off the output, make 48 months the reference level.
HideShow
Estimate Std. Error df t value Pr(>|t|)
(Intercept) 112 4.042858 18.1174 27.7031773 2.763710e-16
Months30 -9 3.182972 33.0000 -2.8275458 7.911329e-03
Months36 -5 3.182972 33.0000 -1.5708588 1.257555e-01
Months42 -2 3.182972 33.0000 -0.6283435 5.341039e-01The book stresses that how the random part is specified changes the test of the fixed part. Dropping the random intercept altogether treats the 48 scores as if they came from a between-subjects design.
HideShow
Analysis of Variance Table
Response: Score
Df Sum Sq Mean Sq F value Pr(>F)
Months 3 552 184.00 0.9381 0.4304
Residuals 44 8630 196.14 Confidence intervals on the variance components
confint() on the fitted lmer object gives
profile-likelihood intervals, on the standard-deviation scale.
HideShow
2.5 % 97.5 %
sd_(Intercept)|subject 7.3238254 18.257258
sigma 6.0237150 9.587055
(Intercept) 95.0042559 110.995745
Months36 -2.1358536 10.135854
Months42 0.8641464 13.135854
Months48 2.8641464 15.135854For intervals on the variances themselves, DMAR implements
the Burdick–Graybill modified-large-sample method, the
generalizability-theory standard, computed from the two mean squares of
the balanced ANOVA. It returns an interval for each component and for
the intraclass correlation, on the variance scale rather than the
standard-deviation scale of confint().
HideShow
classical <- summary(aov_fit)
between <- classical[[1L]][[1L]] # the subject stratum
within_s <- classical[[2L]][[1L]] # the within-subject stratum
variance_components_mls(
ms_between = between[["Mean Sq"]][1],
ms_within = within_s[["Mean Sq"]][nrow(within_s)],
df_between = between[["Df"]][1],
df_within = within_s[["Df"]][nrow(within_s)],
n = nlevels(mcc_long$Months), # observations per subject
conf_level = 0.95
)| term | value |
|---|---|
| sigma2_between | 135.348 |
| sigma2_between_ci_lower | 59.443 |
| sigma2_between_ci_upper | 418.430 |
| sigma2_within | 60.788 |
| sigma2_within_ci_lower | 39.547 |
| sigma2_within_ci_upper | 105.320 |
| icc | 0.690 |
| icc_ci_lower | 0.361 |
| icc_ci_upper | 0.914 |
Confidence level: 95%
The intraclass correlation
Because the compound-symmetry model treats the repeated scores as nested within subjects, the proportion of variance attributable to subjects is an intraclass correlation, and it is also the common correlation the model imposes on every pair of time points. By hand it is the between-subject share of total variance.
HideShow
[1] 0.6900734In DMAR, icc_lmer() reads the same quantity directly off
the fitted lmer object and reports a confidence interval
with it.
| term | value |
|---|---|
| icc | 0.690 |
| sigma2_between | 135.348 |
| sigma2_within | 60.788 |
| total_variance | 196.136 |
| ci_lower | 0.394 |
| ci_upper | 0.868 |
| n_clusters | 12 |
| average_cluster_size | 4 |
Confidence level: 95%
The point estimate is the same 0.690 three times over, but the two
DMAR calls report different 95% intervals for it (0.394 to
0.868 here, 0.361 to 0.914 from variance_components_mls()
above). That is not a contradiction: the two functions invert different
pivotal quantities — icc_lmer() the exact ratio of the two mean squares,
variance_components_mls() the Burdick–Graybill
modified-large-sample approximation. The book tabulates neither
interval, so neither can be checked against it; what can be checked is
the estimate, and that agrees.
sjPlot::tab_model() reports that ICC in a formatted
model table, next to the fixed effects, the random-effect variances, and
the sample sizes. The ICC row near the foot of the
table is the 0.69 computed by hand and by icc_lmer()
above.
| McCarthy score | |||
|---|---|---|---|
| Predictors | Estimates | CI | p |
| (Intercept) | 103.00 | 94.84 – 111.16 | <0.001 |
| Months [36] | 4.00 | -2.42 – 10.42 | 0.216 |
| Months [42] | 7.00 | 0.58 – 13.42 | 0.033 |
| Months [48] | 9.00 | 2.58 – 15.42 | 0.007 |
| Random Effects | |||
| σ2 | 60.79 | ||
| τ00 subject | 135.35 | ||
| ICC | 0.69 | ||
| N subject | 12 | ||
| Observations | 48 | ||
| Marginal R2 / Conditional R2 | 0.056 / 0.708 | ||
15.6.6 — Graphical Representation of Longitudinal Data
A trajectory plot of the raw data: one line per child, connecting that child’s four observed scores. There is a general tendency for scores to rise with age, but the trajectories are far from parallel, which is exactly the question the later models address — are those departures real individual differences, or merely error?
HideShow
ggplot(mcc_long, aes(months, Score, group = subject)) +
geom_line(color = "black", alpha = 0.50, linewidth = 0.5) +
geom_point(color = "black", alpha = 0.70, size = 1.4) +
scale_x_continuous(breaks = c(30, 36, 42, 48)) +
labs(title = "Figure 15.2. Observed individual trajectories of McCarthy scores",
x = "Age (months)", y = "McCarthy score")Figure 15.2. Observed individual trajectories of McCarthy scores.
15.6.7 — Graphical Representation of the Random Intercept Model
The random-intercept model treats the four occasions as a categorical fixed effect and lets each child differ only in a single random intercept. The fitted (BLUP) trajectories are therefore parallel: every child follows the same average pattern of change, shifted up or down. Only ten distinct lines appear, because the two pairs of children identified earlier share a marginal mean.
HideShow
30 36 42 48
103 107 110 112 HideShow
#> 103 107 110 112 — averaging the BLUP trajectories recovers the fixed-effect
#> trajectory, and those are the four values the book reports on p. 879 for the
#> model with the random intercept omitted (a single trajectory). They coincide
#> because the random intercepts average to zero, not because the book is
#> describing this model's per-child predictions.
ggplot(mcc_long, aes(months, fit_cs, group = subject)) +
geom_line(color = "black", alpha = 0.55, linewidth = 0.6) +
scale_x_continuous(breaks = c(30, 36, 42, 48)) +
labs(title = "Figure 15.3. Fitted trajectories, random-intercept model",
x = "Age (months)", y = "Model-implied McCarthy score")Figure 15.3. Fitted trajectory plot from the random-intercept model (parallel lines).
The increase is not quite linear, as the book points out: each line rises 4 points from 30 to 36 months, 3 points from 36 to 42, and 2 points from 42 to 48.
HideShow
36 42 48
4 3 2 The restricted model drops the fixed time effect, keeping only the random intercept. Under this null, scores do not change over time, so every child’s fitted trajectory is a flat line at that child’s predicted level. The omnibus test of the time effect is the comparison of these flat lines against the rising parallel lines of Figure 15.3. The heights are shrunken slightly toward the grand mean of 108, because they are best linear unbiased predictions (BLUPs) rather than the raw subject means — a point the book makes in its footnote to Figure 15.4.
HideShow
[1] 92.12394 124.75806HideShow
[1] 90 127HideShow
#> the BLUP levels run 92.1 to 124.8, inside the 90 to 127 range of the raw
#> subject means of Table 15.1 (book p. 863): shrinkage toward the grand mean
ggplot(mcc_long, aes(months, fit_restricted, group = subject)) +
geom_line(color = "black", alpha = 0.55, linewidth = 0.6) +
scale_x_continuous(breaks = c(30, 36, 42, 48)) +
labs(title = "Figure 15.4. Fitted trajectories, restricted random-intercept model",
x = "Age (months)", y = "Model-implied McCarthy score")Figure 15.4. Fitted trajectory plot from the restricted random-intercept model (flat lines).
15.6.10 — Numerical Example
The compound-symmetry model lets children differ only in their
intercept. Adding a random slope for month_c lets each
child also change at his or her own rate, and lets the intercept and
slope covary. The fixed effects stay the four-level categorical
Months (a cell-means specification), so this model and the
random-intercept model differ only in their random part — exactly the
comparison the book draws between Tables 15.3 and 15.4.
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Score ~ Months + (1 + month_c | subject)
Data: mcc_long
REML criterion at convergence: 336.4
Scaled residuals:
Min 1Q Median 3Q Max
-1.81430 -0.47911 -0.05763 0.57397 1.53582
Random effects:
Groups Name Variance Std.Dev. Corr
subject (Intercept) 168.0183 12.9622
month_c 0.3892 0.6239 -0.40
Residual 37.4365 6.1185
Number of obs: 48, groups: subject, 12
Fixed effects:
Estimate Std. Error df t value Pr(>|t|)
(Intercept) 103.000 4.138 12.289 24.893 6.89e-12 ***
Months36 4.000 2.722 31.803 1.470 0.1515
Months42 7.000 3.303 22.434 2.119 0.0454 *
Months48 9.000 4.092 11.859 2.199 0.0485 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Correlation of Fixed Effects:
(Intr) Mnth36 Mnth42
Months36 -0.421
Months42 -0.465 0.607
Months48 -0.471 0.595 0.749HideShow
Type III Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
Months 200.07 66.69 3 16.356 1.7814 0.1903summary() reports the random part as standard deviations
and a correlation. The book’s table reports variances and a covariance,
which VarCorr() gives in data-frame form.
HideShow
grp var1 var2 vcov sdcor
1 subject (Intercept) <NA> 168.0182777 12.9621865
2 subject month_c <NA> 0.3891905 0.6238514
3 subject (Intercept) month_c -3.2420907 -0.4009274
4 Residual <NA> <NA> 37.4365342 6.1185402The covariance is easier to read as a correlation, which is how the book interprets it.
HideShow
[1] -0.4009274Allowing individual slopes absorbs variability that the random-intercept model charged to the fixed time effect, which is why the drops from 3.03 to 1.78. The two tests use different denominator degrees of freedom: lmerTest’s Satterthwaite value is about 16 here, while PROC MIXED’s containment method reports 22, so the values differ slightly even though the of 1.78 is the same.
HideShow
[1] 16.35622The two random-effects models side by side, fit statistics at the foot, with modelsummary (each model in its own column):
HideShow
modelsummary(
list("Random intercept" = fit_cs, "Random intercept + slope" = fit_ris),
estimate = "{estimate}",
statistic = "({std.error})", # standard errors in parentheses, APA style
gof_map = c("nobs", "aic", "bic", "logLik"),
stars = TRUE,
output = "gt" # gt backend, to match the gtsummary table below
)| Random intercept | Random intercept + slope | |
|---|---|---|
| (Intercept) | 103.000 | 103.000 |
| (4.043) | (4.138) | |
| Months36 | 4.000 | 4.000 |
| (3.183) | (2.722) | |
| Months42 | 7.000 | 7.000 |
| (3.183) | (3.303) | |
| Months48 | 9.000 | 9.000 |
| (3.183) | (4.092) | |
| SD (Intercept subject) | 11.634 | 12.962 |
| SD (month_c subject) | 0.624 | |
| Cor (Intercept~month_c subject) | -0.401 | |
| SD (Observations) | 7.797 | 6.119 |
| Num.Obs. | 48 | 48 |
| AIC | 352.8 | 352.4 |
| BIC | 364.0 | 367.3 |
| + p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001 | ||
The same comparison as a gtsummary table, each model under its own spanning header:
| Characteristic |
Random intercept
|
Random intercept + slope
|
||||
|---|---|---|---|---|---|---|
| Beta | 95% CI | p-value | Beta | 95% CI | p-value | |
| (Intercept) | 103 | 95, 111 | <0.001 | 103 | 94, 112 | <0.001 |
| Months | ||||||
| 30 | — | — | — | — | ||
| 36 | 4.0 | -2.5, 10 | 0.2 | 4.0 | -1.5, 9.5 | 0.2 |
| 42 | 7.0 | 0.52, 13 | 0.035 | 7.0 | 0.16, 14 | 0.045 |
| 48 | 9.0 | 2.5, 15 | 0.008 | 9.0 | 0.07, 18 | 0.048 |
| Abbreviation: CI = Confidence Interval | ||||||
15.6.11 — Graphical Representation of a Model with Random Slope and Intercept
Adding a random slope for (centered) age lets each child change at his or her own rate, while the fixed effects remain the four-level categorical time. The fitted trajectories now fan out: they are no longer parallel, because the model allows individual differences in slope as well as intercept. The occasion means of the predictions are unchanged, so this model and the random-intercept model describe the same average change but differ in how individuals depart from it.
HideShow
30 36 42 48
103 107 110 112 HideShow
#> 103 107 110 112 — the same predicted occasion means the book gives for this
#> model on p. 887
ggplot(mcc_long, aes(months, fit_ris, group = subject)) +
geom_line(color = "black", alpha = 0.55, linewidth = 0.6) +
scale_x_continuous(breaks = c(30, 36, 42, 48)) +
labs(title = "Figure 15.5. Fitted trajectories, random intercept and slope model",
x = "Age (months)", y = "Model-implied McCarthy score")Figure 15.5. Fitted trajectory plot from the random intercept and slope model.
15.6.14 — Straight-Line Change Model
When time is treated as quantitative, a more parsimonious
model parameterizes change as a linear slope that may
vary across subjects. Each fixed effect (intercept, slope) is paired
with a corresponding random effect, the structure the book calls a
growth-curve model. Time is the centered month_c (0 at the
first wave), so the intercept is the population mean at 30 months and
the slope is points gained per month.
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Score ~ month_c + (month_c | subject)
Data: mcc_long
REML criterion at convergence: 349.1
Scaled residuals:
Min 1Q Median 3Q Max
-1.79184 -0.43847 0.00417 0.64189 1.68327
Random effects:
Groups Name Variance Std.Dev. Corr
subject (Intercept) 169.8529 13.0328
month_c 0.4038 0.6354 -0.41
Residual 34.8162 5.9005
Number of obs: 48, groups: subject, 12
Fixed effects:
Estimate Std. Error df t value Pr(>|t|)
(Intercept) 103.5000 4.0231 11.0001 25.726 3.54e-11 ***
month_c 0.5000 0.2231 10.9998 2.241 0.0466 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Correlation of Fixed Effects:
(Intr)
month_c -0.475HideShow
grp var1 var2 vcov sdcor
1 subject (Intercept) <NA> 169.8528972 13.0327625
2 subject month_c <NA> 0.4037638 0.6354241
3 subject (Intercept) month_c -3.3730646 -0.4073095
4 Residual <NA> <NA> 34.8161554 5.9005216HideShow
#> the vcov column, at the book's precision, is 169.85, 0.4038, -3.3731,
#> 34.8162 — the UN(1,1), UN(2,2), UN(2,1), and Residual estimates of
#> Table 15.6, book p. 894, which prints 169.85, 0.4037, -3.3731, and 34.8167.
#> The slope variance and the residual differ from SAS in the fourth decimal,
#> a convergence tolerance rather than a different model. The -0.41 correlation
#> that summary() prints is implied by these estimates; the book's table prints
#> the covariance instead.
anova(fit_growth)HideShow
Type III Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
month_c 174.9 174.9 1 11 5.0236 0.04659 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1Confidence intervals on the fixed effects
The book forms the 95% interval for the slope from the distribution on 11 df, whose critical value Appendix Table A.1 gives as 2.20, and reports 0.01 to 0.99.
HideShow
[1] 2.200985HideShow
lower upper
0.008999869 0.991000131 broom.mixed builds the same interval without the hand
arithmetic, because it takes the degrees of freedom from the fitted
model rather than assuming a normal approximation.
HideShow
# A tibble: 2 × 9
effect term estimate std.error statistic df p.value conf.low conf.high
<chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 fixed (Interc… 103. 4.02 25.7 11.0 3.54e-11 94.6 112.
2 fixed month_c 0.500 0.223 2.24 11.0 4.66e- 2 0.00900 0.991confint(..., method = "Wald") on a merMod
object uses the normal critical value of 1.96 rather than the
value of 2.20, so its interval is
slightly narrower than the book’s. The point estimate and standard error
are the same; only the multiplier differs.
HideShow
2.5 % 97.5 %
.sig01 NA NA
.sig02 NA NA
.sig03 NA NA
.sigma NA NA
(Intercept) 95.61486478 111.3851352
month_c 0.06276735 0.937232615.6.15 — Graphical Representation of a Growth Curve Model
The straight-line change model treats age as quantitative: a fixed intercept and slope, each paired with a random effect, so every child’s trajectory is an actual straight line. The thin lines are the individual fitted trajectories; the heavy line estimates the population-average trajectory from the fixed effects.
HideShow
# Fitted lines over a fine age grid (linear in age, so any grid recovers the line).
grid <- expand.grid(subject = levels(mcc_long$subject), months = seq(30, 48, by = 1))
grid$month_c <- grid$months - 30
grid$fitted <- predict(fit_growth, newdata = grid) # includes random effects
pop <- data.frame(months = seq(30, 48, by = 1))
pop$month_c <- pop$months - 30
pop$fitted <- predict(fit_growth, newdata = pop, re.form = NA) # population-average line
ggplot(grid, aes(months, fitted, group = subject)) +
geom_line(color = "black", alpha = 0.45, linewidth = 0.5) +
geom_line(data = pop, aes(months, fitted), inherit.aes = FALSE,
color = "#0C2340", linewidth = 1.4) +
scale_x_continuous(breaks = c(30, 36, 42, 48)) +
labs(title = "Figure 15.6. Fitted trajectories, straight-line change model",
x = "Age (months)", y = "Model-implied McCarthy score")Figure 15.6. Fitted trajectories from the straight-line change model. The heavy line estimates the population-average trajectory.
The straight-line change model estimates not just an average slope but a variance of slopes across children. Treating the random slope as normally distributed, the curve below is the estimated population distribution of growth rates: centered at the average slope (the fixed effect, dashed line) with a spread given by the estimated slope standard deviation. Its width is the model’s claim about how much children differ in their rate of change.
HideShow
mean sd
0.5000000 0.6354241 HideShow
#> mean 0.50 and sd 0.64: the slope variance of 0.4037 in Table 15.6 implies a
#> standard deviation of 0.64, as the book notes on p. 896
xx <- seq(slope_mean - 3.5 * slope_sd, slope_mean + 3.5 * slope_sd,
length.out = 400)
dens <- data.frame(slope = xx, density = dnorm(xx, slope_mean, slope_sd))
ggplot(dens, aes(slope, density)) +
geom_area(fill = "#0C2340", alpha = 0.20) +
geom_line(color = "black", linewidth = 0.9) +
geom_vline(xintercept = slope_mean, color = "#0C2340",
linetype = "dashed", linewidth = 0.7) +
annotate("text", x = slope_mean + slope_sd / 2, y = max(dens$density),
label = sprintf("Estimated mean = %.2f", slope_mean),
color = "#0C2340", hjust = 0, vjust = 0.5, size = 3.3) +
labs(title = "Figure 15.7. Estimated population distribution of slopes",
subtitle = "Rate of change in McCarthy score per month (straight-line change model)",
x = "Slope (McCarthy points per month)", y = "Density")Figure 15.7. Estimated population distribution of slopes from the straight-line change model.
15.7 — An Alternative Approach and Conceptualization
Instead of building the covariance from random effects, the book’s alternative is to model the residual covariance matrix directly.
The errors a cell-means model leaves behind (Tables 15.7 to 15.9)
The book motivates that move by looking at the errors left by a fixed
cell-means model, which in base R are just the residuals of
lm(Score ~ Months) laid back out one row per child.
HideShow
months
subject 30 36 42 48
1 5 -11 0 10
2 0 10 17 21
3 -7 0 -4 -5
4 -19 -22 -18 -13
5 15 18 15 4
6 7 0 -14 -21
7 26 21 13 16
8 -13 -23 -9 1
9 -19 -3 -10 -24
10 -7 -7 -7 -7
11 2 7 -5 0
12 10 10 22 18Those errors are correlated across occasions, which is the whole problem. Their covariance and correlation matrices are the book’s Tables 15.8 and 15.9, and because the cell-means model only removes column means, they are also the covariance and correlation matrices of the original scores.
HideShow
Months30 Months36 Months42 Months48
Months30 188.00 154.36 127.36 121.18
Months36 154.36 200.55 143.64 97.45
Months42 127.36 143.64 178.00 168.09
Months48 121.18 97.45 168.09 218.00HideShow
Months30 Months36 Months42 Months48
Months30 1.000 0.795 0.696 0.599
Months36 0.795 1.000 0.760 0.466
Months42 0.696 0.760 1.000 0.853
Months48 0.599 0.466 0.853 1.000The unstructured model (Table 15.10)
nlme::gls() models that residual covariance matrix
directly. An unstructured (UN) matrix frees every variance and every
covariance, so it is the most general and the most data-hungry; with
balanced data it reproduces the multivariate (Chapter 13) analysis.
HideShow
Denom. DF: 44
numDF F-value p-value
(Intercept) 1 934.2918 <.0001
Months 3 2.7379 0.0547HideShow
Marginal variance covariance matrix
[,1] [,2] [,3] [,4]
[1,] 188.00 154.36 127.36 121.18
[2,] 154.36 200.55 143.64 97.46
[3,] 127.36 143.64 178.00 168.09
[4,] 121.18 97.46 168.09 218.00
Standard Deviations: 13.711 14.162 13.342 14.765 HideShow
#> 188.00, 154.36, 200.55, 127.36, 143.64, 178.00, 121.18, 97.46, 168.09,
#> 218.00 — the ten UN(i,j) covariance parameter estimates of Table 15.10,
#> book p. 906. The unstructured fit simply recovers the sample covariance
#> matrix of Table 15.8; every cell agrees to within 0.001 of it, which is why
#> the UN(4,2) entry rounds to 97.46 here and to the 97.45 the book prints.15.7.1 — Additional Covariance Matrix Structures
Compound symmetry (Table 15.11)
Specifying compound symmetry directly, rather than through a random intercept, gives the same model by a different route — a point the book makes explicitly when it notes that the two produce identical information criteria.
HideShow
Rho
0.6900734 HideShow
[1] 196.1364HideShow
Denom. DF: 44
numDF F-value p-value
(Intercept) 1 929.7391 <.0001
Months 3 3.0269 0.0394HideShow
Marginal variance covariance matrix
[,1] [,2] [,3] [,4]
[1,] 196.14 135.35 135.35 135.35
[2,] 135.35 196.14 135.35 135.35
[3,] 135.35 135.35 196.14 135.35
[4,] 135.35 135.35 135.35 196.14
Standard Deviations: 14.005 14.005 14.005 14.005 A first-order autoregressive structure (Table 15.12)
Compound symmetry assumes every pair of time points correlates equally; in longitudinal data, closer occasions usually correlate more highly. A first-order autoregressive (AR1) structure captures that: adjacent occasions correlate , occasions two apart , and so on.
HideShow
Phi
0.8064014 HideShow
[1] 199.4432HideShow
[1] 0.8064014 0.6502833 0.5243894HideShow
Denom. DF: 44
numDF F-value p-value
(Intercept) 1 921.6425 <.0001
Months 3 1.8041 0.160415.7.3 — Overview of Broader Model Comparison
Several of these structures are non-nested (AR1 versus compound symmetry, for instance), so they cannot be ranked by a likelihood-ratio test. The book (Table 15.14) instead compares all five full models by information criteria, which penalize fit for the number of parameters.
The one thing to be careful about is which parameters get
counted. PROC MIXED counts only the covariance
parameters in its penalty, and uses the number of subjects for BIC and
the REML residual degrees of freedom for the finite-sample correction.
R’s AIC() and BIC() use different conventions,
so they return different numbers for the same fit. Spelling the book’s
conventions out reproduces Table 15.14 exactly.
HideShow
neg2logL <- function(fit) -2 * as.numeric(logLik(fit))
ic <- tibble(
Model = c("Random intercept", "Random intercept and slope",
"Unstructured", "Compound symmetry", "Autoregressive"),
# REML -2 log likelihood; all five models share the same fixed effects.
neg2logL = c(neg2logL(fit_cs), neg2logL(fit_ris),
neg2logL(fit_un), neg2logL(fit_cs_gls), neg2logL(fit_ar1)),
# Number of covariance parameters, which is what PROC MIXED penalizes.
q = c(2, 4, 10, 2, 2)
) |>
mutate(
AIC = neg2logL + 2 * q,
# Finite-sample correction uses the REML residual df, N - (number of fixed effects).
AICC = AIC + 2 * q * (q + 1) / ((nrow(mcc_long) - 4) - q - 1),
# BIC uses the number of subjects, not the number of observations.
BIC = neg2logL + log(nlevels(mcc_long$subject)) * q
)
ic |>
gt() |>
fmt_number(columns = neg2logL, decimals = 1) |>
fmt_number(columns = c(AIC, AICC, BIC), decimals = 1) |>
cols_label(neg2logL = md("−2 log *L*"), q = md("*q*")) |>
tab_header(title = md("**Information criteria** for the five full models")) |>
cols_align(align = "center", columns = -Model)| Information criteria for the five full models | |||||
| Model | −2 log L | q | AIC | AICC | BIC |
|---|---|---|---|---|---|
| Random intercept | 340.8 | 2 | 344.8 | 345.0 | 345.7 |
| Random intercept and slope | 336.4 | 4 | 344.4 | 345.4 | 346.3 |
| Unstructured | 325.1 | 10 | 345.1 | 351.8 | 350.0 |
| Compound symmetry | 340.8 | 2 | 344.8 | 345.0 | 345.7 |
| Autoregressive | 333.1 | 2 | 337.1 | 337.4 | 338.1 |
Two of the book’s observations fall straight out of the table. The random intercept and compound symmetry rows are identical, because they are two ways of writing the same model; and all three criteria pick the autoregressive model, which fits nearly as well as the unstructured one with eight fewer parameters.
In DMAR
compare_cov_structures() automates the family in one
call. It fits eight structures — independence (IND), compound symmetry
(CS) and its heterogeneous form (CSH), first-order autoregressive (AR1)
and its heterogeneous form (ARH1), Toeplitz (TOEP) and heterogeneous
Toeplitz (TOEPH), and unstructured (UN) — to the same fixed-effects
model, and returns each model’s log-likelihood, AIC, BIC, parameter
count, and a likelihood-ratio test against the most general (UN) model.
That last column is a significance test for the nested comparisons,
which the information criteria above do not provide. The comparison uses
ML, since the fixed-effects part is held constant across structures, so
its log-likelihoods are on a different scale from the REML values tabled
above.
| structure | log_lik | AIC | BIC | n_par | LRT_vs_UN_chisq | LRT_vs_UN_df | LRT_vs_UN_p | fit_error |
|---|---|---|---|---|---|---|---|---|
| IND | -192.712 | 395.424 | 404.780 | 5 | 45.776 | 9 | < 0.0001 | NA |
| CS | -178.357 | 368.714 | 379.942 | 6 | 17.066 | 8 | 0.0294 | NA |
| CSH | -177.969 | 373.938 | 390.779 | 9 | 16.290 | 5 | 0.0061 | NA |
| AR1 | -174.202 | 360.404 | 371.631 | 6 | 8.755 | 8 | 0.3633 | NA |
| ARH1 | -173.982 | 365.964 | 382.805 | 9 | 8.315 | 5 | 0.1397 | NA |
| TOEP | -171.858 | 359.716 | 374.686 | 8 | 4.067 | 6 | 0.6676 | NA |
| TOEPH | -171.640 | 365.281 | 385.864 | 11 | 3.632 | 3 | 0.3040 | NA |
| UN | -169.824 | 367.649 | 393.846 | 14 | NA | NA | NA | NA |
How to Cite This Page
The book. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.
This page. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Chapter 15: An Introduction to Mixed-Effects Models: Within-Subjects Designs (R code and instructions). Companion materials for Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). https://DesigningExperiments.com
These examples use DMAR 1.2.0. The printed book predates DMAR.
References
Arel-Bundock V (2026). modelsummary: Summary Tables and Plots for Statistical Models and Data: Beautiful, Customizable, and Publication-Ready. doi:10.32614/CRAN.package.modelsummary https://doi.org/10.32614/CRAN.package.modelsummary. R package version 2.6.0, https://CRAN.R-project.org/package=modelsummary.
Bates D, Maechler M, Bolker B, Walker S, Ly A, Jagan M (2026). lme4: Linear Mixed-Effects Models using ‘Eigen’ and S4. doi:10.32614/CRAN.package.lme4 https://doi.org/10.32614/CRAN.package.lme4. R package version 2.0-6, https://CRAN.R-project.org/package=lme4.
Bolker B, Robinson D (2026). broom.mixed: Tidying Methods for Mixed Models. doi:10.32614/CRAN.package.broom.mixed https://doi.org/10.32614/CRAN.package.broom.mixed. R package version 0.2.9.7, https://CRAN.R-project.org/package=broom.mixed.
Iannone R, Cheng J, Schloerke B, Haughton S, Hughes E, Lauer A, François R, Seo J, Brevoort K, Roy O (2026). gt: Easily Create Presentation-Ready Display Tables. doi:10.32614/CRAN.package.gt https://doi.org/10.32614/CRAN.package.gt. R package version 1.3.0, https://CRAN.R-project.org/package=gt.
Kelley K (2026). DMAR: Design, Measurement, and Analysis in R (DMAR). R package version 1.2.0, https://kenkelley.org.
Kuznetsova A, Bruun Brockhoff P, Haubo Bojesen Christensen R (2026). lmerTest: Tests in Linear Mixed Effects Models. doi:10.32614/CRAN.package.lmerTest https://doi.org/10.32614/CRAN.package.lmerTest. R package version 3.2-1, https://CRAN.R-project.org/package=lmerTest.
Lüdecke D (2025). sjPlot: Data Visualization for Statistics in Social Science. doi:10.32614/CRAN.package.sjPlot https://doi.org/10.32614/CRAN.package.sjPlot. R package version 2.9.0, https://CRAN.R-project.org/package=sjPlot.
Maxwell S, Delaney H, Kelley K (2026). AMCP: Data Sets to Accompany Designing Experiments and Analyzing Data: A Model Comparison Perspective (Maxwell, Delaney, and Kelley, 2027, 4th Edition). doi:10.32614/CRAN.package.AMCP https://doi.org/10.32614/CRAN.package.AMCP. R package version 2.0.0, https://CRAN.R-project.org/package=AMCP.
Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.
Pinheiro J, Bates D, R Core Team (2026). nlme: Linear and Nonlinear Mixed Effects Models. doi:10.32614/CRAN.package.nlme https://doi.org/10.32614/CRAN.package.nlme. R package version 3.1-171, https://CRAN.R-project.org/package=nlme.
R Core Team (2026). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria. doi:10.32614/R.manuals https://doi.org/10.32614/R.manuals. https://www.R-project.org/.
Sjoberg D, Larmarange J, Curry M, de la Rua E, Lavery J, Whiting K, Zabor E (2026). gtsummary: Presentation-Ready Data Summary and Analytic Result Tables. doi:10.32614/CRAN.package.gtsummary https://doi.org/10.32614/CRAN.package.gtsummary. R package version 2.5.1, https://CRAN.R-project.org/package=gtsummary.
Wickham H (2023). tidyverse: Easily Install and Load the ‘Tidyverse’. doi:10.32614/CRAN.package.tidyverse https://doi.org/10.32614/CRAN.package.tidyverse. R package version 2.0.0, https://CRAN.R-project.org/package=tidyverse.