Chapter 15: An Introduction to Mixed-Effects Models: Within-Subjects Designs

R Code and Instructions

Scott E. Maxwell, Harold D. Delaney, and Ken Kelley

Code
Results
On this page

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 FF 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 ICC

15.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
data(chapter_15_table_1)
mcc_wide <- chapter_15_table_1 |>
  as_tibble() |>
  mutate(subject = factor(row_number()))
mcc_wide
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
#> the 12 x 4 block of scores matches Table 15.1, book p. 863

# The marginal means printed in the last column and the last row of Table 15.1.
rowMeans(chapter_15_table_1)
HideShow
 [1] 109 120 104  90 121 101 127  97  94 101 109 123
HideShow
#> 109 120 104 90 121 101 127 97 94 101 109 123 — the subject marginal means
#> of Table 15.1, book p. 863

colMeans(chapter_15_table_1)
HideShow
Months30 Months36 Months42 Months48 
     103      107      110      112 
HideShow
#> 103 107 110 112 — the occasion means of Table 15.1, book p. 863

mean(as.matrix(chapter_15_table_1))
HideShow
[1] 108
HideShow
#> 108 — the grand mean of Table 15.1, book p. 863

The 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_long
HideShow
# 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 rows

Two 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
rowMeans(chapter_15_table_1) |> table() |> (\(x) x[x > 1])()
HideShow

101 109 
  2   2 
HideShow
#> 101 and 109 each occur twice — the two tied pairs noted on book p. 878

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 FF for the within-subjects factor is 𝑀𝑆A/𝑀𝑆A×S\mathit{MS}_{A}/\mathit{MS}_{A \times S}, which in base R is the within-subject stratum of aov() with an Error(subject) term.

HideShow
aov_fit <- aov(Score ~ Months + Error(subject), data = mcc_long)
summary(aov_fit)
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 ' ' 1
HideShow
#> 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. 871

The same omnibus test written as an APA-style table, with sums of squares, df, FF, pp, and partial η2\eta^2. 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 &eta;<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 μ\mu, the likelihood of the sample is the product of the four normal densities. Graphing that product over a range of μ\mu 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
mle
HideShow
[1] 4
HideShow
#> 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 \(\mu\).

Figure 15.1. Likelihood of the sample data as a function of the population mean μ\mu.

HideShow
#> reproduces Figure 15.1, book p. 867

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
fit_glm <- lm(Score ~ subject + Months, data = mcc_long)
anova(fit_glm)
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 ' ' 1
HideShow
#> 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.squared
HideShow
[1] 0.7815291
HideShow
#> 0.781529 — the R-Square of Table 15.2, book p. 871

sigma(fit_glm)
HideShow
[1] 7.796658
HideShow
#> 7.796658 — the Root MSE of Table 15.2, book p. 871

The 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
fit_cs <- lmer(Score ~ Months + (1 | subject), data = mcc_long)
summary(fit_cs)
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.500
HideShow
anova(fit_cs)
HideShow
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 ' ' 1
HideShow
#> subject variance 135.35, residual variance 60.79 — the two "Covariance
#> Parameter Estimates" of Table 15.3, book p. 874
#> Months: F = 3.03 on 3 and 33 df, p = .0432 — the "Type 3 Tests of Fixed
#> Effects" line of Table 15.3, book p. 874 (and identical to the ANOVA above)

The 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 −9-9, −5-5, −2-2 straight off the output, make 48 months the reference level.

HideShow
mcc_ref48 <- mcc_long |> mutate(Months = relevel(Months, ref = "48"))
summary(lmer(Score ~ Months + (1 | subject), data = mcc_ref48))$coefficients
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-01
HideShow
#> Intercept 112.00 (SE 4.0429, t = 27.70); contrasts -9, -5, -2, each with
#> SE 3.1830 and t of -2.83, -1.57, -0.63 — match Table 15.3, book p. 874.
#> (The denominator df differ: lmerTest reports Satterthwaite values, PROC
#> MIXED the containment values of 11 and 33.)

The 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
anova(lm(Score ~ Months, data = mcc_long))
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               
HideShow
#> F = 0.94 — matches the value the book reports on p. 875 for the model with
#> the random effect omitted. Its residual variance, 196.14, is the total
#> variance the compound-symmetry model splits into 135.35 + 60.7879, the sum
#> the book computes on p. 910.
Confidence intervals on the variance components

confint() on the fitted lmer object gives profile-likelihood intervals, on the standard-deviation scale.

HideShow
confint(fit_cs, method = "profile", signames = FALSE)
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.135854

For 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%

HideShow
#> sigma2_between 135.348 and sigma2_within 60.788 agree with the 135.35 and
#> 60.7879 of Table 15.3, book p. 874; the intervals around them are DMAR's
#> addition, not something the book's table reports.
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
varcomps  <- VarCorr(fit_cs) |> as.data.frame()
v_between <- varcomps$vcov[varcomps$grp == "subject"]
v_within  <- varcomps$vcov[varcomps$grp == "Residual"]
v_between / (v_between + v_within)
HideShow
[1] 0.6900734
HideShow
#> 0.6901 — the common correlation the compound-symmetry model reports in the
#> estimated correlation matrix of Table 15.11, book p. 909

In DMAR, icc_lmer() reads the same quantity directly off the fitted lmer object and reports a confidence interval with it.

HideShow
icc_lmer(fit_cs, conf_level = 0.95)
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%

HideShow
#> icc 0.690 with sigma2_between 135.348 and sigma2_within 60.788 — the same
#> three numbers computed by hand just above. Its total_variance of 196.136 is
#> the 196.14 the book computes on p. 910.

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 FF 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.

HideShow
tab_model(fit_cs,
          show.icc    = TRUE,    # the intraclass correlation
          show.re.var = TRUE,    # random-effect variances
          dv.labels   = "McCarthy score")
  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.

Figure 15.2. Observed individual trajectories of McCarthy scores.

HideShow
#> reproduces Figure 15.2, book p. 877. Subject 7 is the trajectory that starts
#> near 130 (129, 128, 123, 128), and subjects 4 and 9 are the two that start
#> at 84 — the children the book uses to orient the reader on p. 876.

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
mcc_long$fit_cs <- predict(fit_cs)   # BLUPs: include the random intercept

tapply(mcc_long$fit_cs, mcc_long$Months, 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).

Figure 15.3. Fitted trajectory plot from the random-intercept model (parallel lines).

HideShow
#> reproduces Figure 15.3, book p. 879

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
diff(tapply(mcc_long$fit_cs, mcc_long$Months, mean))
HideShow
36 42 48 
 4  3  2 
HideShow
#> 4, 3, 2 — the changes between adjacent occasions described on book p. 878

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
fit_cs_restricted <- lmer(Score ~ 1 + (1 | subject), data = mcc_long)
mcc_long$fit_restricted <- predict(fit_cs_restricted)  # one flat BLUP level per child

range(mcc_long$fit_restricted)
HideShow
[1]  92.12394 124.75806
HideShow
range(rowMeans(chapter_15_table_1))
HideShow
[1]  90 127
HideShow
#> 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).

Figure 15.4. Fitted trajectory plot from the restricted random-intercept model (flat lines).

HideShow
#> reproduces Figure 15.4, book p. 880

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
fit_ris <- lmer(Score ~ Months + (1 + month_c | subject), data = mcc_long)
summary(fit_ris)
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.749
HideShow
anova(fit_ris)
HideShow
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.1903
HideShow
#> intercept variance 168.0183, slope variance 0.3892, residual 37.4365 —
#> the book's 168.02, 0.3892, and 37.4364, Table 15.4, book p. 886
#> Months: F = 1.78, no longer significant at .05 — matches the F of Table 15.4,
#> book p. 886

summary() 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
vc_ris <- as.data.frame(VarCorr(fit_ris))
vc_ris
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.1185402
HideShow
#> the vcov column, at the book's precision, is 168.02, 0.3892, -3.2421,
#> 37.4365 — the four covariance parameters UN(1,1), UN(2,2), UN(2,1), and
#> Residual of Table 15.4, book p. 886, which prints 168.02, 0.3892, -3.2421,
#> and 37.4364

The covariance is easier to read as a correlation, which is how the book interprets it.

HideShow
vc_ris$vcov[3] / sqrt(vc_ris$vcov[1] * vc_ris$vcov[2])
HideShow
[1] -0.4009274
HideShow
#> -0.40 — the correlation between initial status and rate of change that the
#> book computes from Table 15.4 on p. 886

Allowing individual slopes absorbs variability that the random-intercept model charged to the fixed time effect, which is why the FF 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 pp values differ slightly even though the FF of 1.78 is the same.

HideShow
anova(fit_ris)[["DenDF"]]
HideShow
[1] 16.35622
HideShow
#> 16.36, against the 22 of Table 15.4 (book p. 886): the same F, a different
#> rule for the denominator df

The 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:

HideShow
t_ri  <- tbl_regression(fit_cs,  intercept = TRUE)
t_ris <- tbl_regression(fit_ris, intercept = TRUE)
tbl_merge(list(t_ri, t_ris),
          tab_spanner = c("**Random intercept**", "**Random intercept + slope**"))
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
mcc_long$fit_ris <- predict(fit_ris)   # BLUPs: intercept and slope

tapply(mcc_long$fit_ris, mcc_long$Months, mean)
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.

Figure 15.5. Fitted trajectory plot from the random intercept and slope model.

HideShow
#> reproduces Figure 15.5, book p. 888

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
fit_growth <- lmer(Score ~ month_c + (month_c | subject), data = mcc_long)
summary(fit_growth)
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.475
HideShow
#> fixed effects: intercept 103.50 (SE 4.0231, t = 25.73) and slope 0.5000
#> (SE 0.2231, t = 2.24, p = .0466), both on 11 df — match the "Solution for
#> Fixed Effects" of Table 15.6, book p. 894

as.data.frame(VarCorr(fit_growth))
HideShow
       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.9005216
HideShow
#> 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 ' ' 1
HideShow
#> F = 5.02 on 1 and 11 df, p = .0466 — the "Type 3 Tests of Fixed Effects"
#> line of Table 15.6, book p. 894, and the linear-trend contrast of
#> Table 15.5, book p. 891

Confidence intervals on the fixed effects

The book forms the 95% interval for the slope from the tt distribution on 11 df, whose critical value Appendix Table A.1 gives as 2.20, and reports 0.01 to 0.99.

HideShow
qt(0.975, df = 11)
HideShow
[1] 2.200985
HideShow
#> 2.201 — the critical value of 2.20 the book reads from Table A.1, p. 894

b  <- fixef(fit_growth)["month_c"]
se <- sqrt(vcov(fit_growth)["month_c", "month_c"])
b + c(lower = -1, upper = 1) * qt(0.975, df = 11) * se
HideShow
      lower       upper 
0.008999869 0.991000131 
HideShow
#> 0.009 to 0.991, the 0.01 to 0.99 interval reported on book p. 894

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
generics::tidy(fit_growth, effects = "fixed", conf.int = TRUE, conf.method = "Wald")
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.991
HideShow
#> conf.low 0.009 and conf.high 0.991 for month_c — the same bounds as the hand
#> computation above, and the 0.01 to 0.99 of book p. 894

confint(..., method = "Wald") on a merMod object uses the normal critical value of 1.96 rather than the tt 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
confint(fit_growth, method = "Wald")
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.9372326
HideShow
#> month_c: 0.063 to 0.937 — narrower than the book's 0.01 to 0.99 because the
#> multiplier is 1.96 rather than 2.20

15.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.

Figure 15.6. Fitted trajectories from the straight-line change model. The heavy line estimates the population-average trajectory.

HideShow
#> reproduces Figure 15.6, book p. 895. The population-average line runs from
#> 103.50 at 30 months to 112.50 at 48 months, a gain of 0.50 points per month.

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
slope_mean <- as.numeric(fixef(fit_growth)["month_c"])
vc_growth  <- as.data.frame(VarCorr(fit_growth))
slope_sd   <- vc_growth$sdcor[vc_growth$grp  == "subject" &
                              vc_growth$var1 == "month_c" &
                              is.na(vc_growth$var2)]
c(mean = slope_mean, sd = slope_sd)
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.

Figure 15.7. Estimated population distribution of slopes from the straight-line change model.

HideShow
#> reproduces Figure 15.7, book p. 896

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
errors_wide <- matrix(residuals(lm(Score ~ Months, data = mcc_long)),
                      nrow = 12, byrow = TRUE,
                      dimnames = list(subject = 1:12, months = c(30, 36, 42, 48)))
round(errors_wide)
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  18
HideShow
#> matches Table 15.7, book p. 903 (subject 1: 5, -11, 0, 10)

Those 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
round(cov(chapter_15_table_1), 2)
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.00
HideShow
#> 188.00, 200.55, 178.00, 218.00 on the diagonal and 154.36, 127.36, 121.18,
#> 143.64, 97.45, 168.09 off it — matches Table 15.8, book p. 903

round(cor(chapter_15_table_1), 3)
HideShow
         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.000
HideShow
#> 0.795, 0.696, 0.599, 0.760, 0.466, 0.853 — matches Table 15.9, book p. 904

The 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
fit_un <- gls(Score ~ Months,
              data        = mcc_long,
              correlation = corSymm(form = ~ as.integer(Months) | subject),
              weights     = varIdent(form = ~ 1 | Months))
anova(fit_un)
HideShow
Denom. DF: 44 
            numDF  F-value p-value
(Intercept)     1 934.2918  <.0001
Months          3   2.7379  0.0547
HideShow
#> Months: F = 2.74 — matches the default PROC MIXED test of Table 15.10,
#> book p. 906. gls() uses residual (N - p = 44) denominator df, so its p value
#> differs from the book's; the F statistic is the quantity to compare.

round(getVarCov(fit_un), 2)
HideShow
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
fit_cs_gls <- gls(Score ~ Months, data = mcc_long,
                  correlation = corCompSymm(form = ~ as.integer(Months) | subject))
coef(fit_cs_gls$modelStruct$corStruct, unconstrained = FALSE)   # the common correlation
HideShow
      Rho 
0.6900734 
HideShow
sigma(fit_cs_gls)^2                                             # the common variance
HideShow
[1] 196.1364
HideShow
anova(fit_cs_gls)
HideShow
Denom. DF: 44 
            numDF  F-value p-value
(Intercept)     1 929.7391  <.0001
Months          3   3.0269  0.0394
HideShow
#> correlation 0.6901 — the common off-diagonal correlation of Table 15.11,
#> book p. 909; F = 3.03, as in Table 15.11
#> variance 196.14 — the sum 135.35 + 60.7879 the book computes on p. 910

round(getVarCov(fit_cs_gls), 2)
HideShow
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 
HideShow
#> 196.14 on the diagonal and 135.35 everywhere off it — the covariance form of
#> the compound-symmetry model the book describes on book p. 910

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 ρ\rho, occasions two apart ρ2\rho^2, and so on.

HideShow
fit_ar1 <- gls(Score ~ Months, data = mcc_long,
               correlation = corAR1(form = ~ as.integer(Months) | subject))
rho <- coef(fit_ar1$modelStruct$corStruct, unconstrained = FALSE)
rho
HideShow
      Phi 
0.8064014 
HideShow
#> 0.8064 — matches the AR(1) estimate of Table 15.12, book p. 911

sigma(fit_ar1)^2
HideShow
[1] 199.4432
HideShow
#> 199.4432, against the 199.45 printed in Table 15.12 (book p. 911). The two
#> estimates differ by 0.007, about 0.003% — a difference between the two
#> programs' convergence tolerances, not between the models.

rho^(1:3)
HideShow
[1] 0.8064014 0.6502833 0.5243894
HideShow
#> 0.8064, 0.6503, 0.5244 — the lag-one, lag-two, and lag-three correlations
#> of the estimated correlation matrix in Table 15.12, book p. 911, which the
#> text rounds to .81, .65, and .52

anova(fit_ar1)
HideShow
Denom. DF: 44 
            numDF  F-value p-value
(Intercept)     1 921.6425  <.0001
Months          3   1.8041  0.1604
HideShow
#> Months: F = 1.80 — matches Table 15.12, book p. 911. As with the
#> unstructured fit, gls() reports a residual-df p value that differs from
#> PROC MIXED's.

15.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("&minus;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
HideShow
#> AIC 344.8, 344.4, 345.1, 344.8, 337.1; AICC 345.0, 345.4, 351.8, 345.0,
#> 337.4; BIC 345.7, 346.3, 350.0, 345.7, 338.1 — all fifteen values match
#> Table 15.14, book p. 914

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.

HideShow
compare_cov_structures(mcc_long, outcome = "Score",
                       subject = "subject", time = "Months")
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
HideShow
#> CS vs UN: LRT = 17.07 on 8 df, p = .029. The richer UN model fits
#> significantly better than CS, but AR1 fits nearly as well as UN
#> (LRT vs UN p = .36) with eight fewer parameters — the same conclusion the
#> book draws from Table 15.14, book p. 914.

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

Scroll to Top