Chapter 16: An Introduction to Mixed-Effects Models: Nested 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.

Chapter 16 takes up data that are nested: clients within trainees, students within classrooms, classrooms within treatment conditions. Clustering of this kind induces dependence among observations that share a higher-level unit, and the mixed-effects model handles it by estimating the variance of the cluster effect rather than an effect for each cluster. Section 16.4 reviews the ANOVA approach of Chapter 10 on the clinical trainee data, Section 16.5 shows that the mixed-effects analysis reproduces it exactly when nn is equal and then takes over where ANOVA cannot go (unequal nn), and Section 16.6 adds predictors measured at two different levels of the hierarchy: teaching skill, a property of the classroom (level 2), and cognitive ability, a property of the student (level 1). Section 16.7 closes with sample size planning.

These notes build on the prior chapters’ R Code and Instructions, where operational aspects of R and the use of many functions are discussed; here we skip what has already been covered there, including how the AMCP data sets are named (see Chapter 1). This chapter uses two of them: chapter_16_table_1 (the clinical trainee severity ratings, the equal-nn example, which is the Table 10.9 data of Chapter 10) and chapter_16_table_4 (the inductive reasoning study, the unequal-nn example).

HideShow
# Load all of the packages used.
library(dplyr)          # data manipulation
library(ggplot2)        # figures
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(broom)          # tidy output from lm/aov into data frames
library(broom.mixed)    # tidy output from lmer into data frames
library(lme4)           # fit mixed-effects models
library(lmerTest)       # p-values and denominator df for lmer fixed effects
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

16.4 — Review of the ANOVA Approach

The chapter opens with the hypothetical clinical trainee data of Table 10.9, repeated as Table 16.1. Three female and three male clinical psychology graduate trainees were randomly selected, each was randomly assigned four clients to interview, and each trainee assigned a severity rating to each client. Trainees are nested within gender: trainee is a random factor, gender a fixed one.

HideShow
data(chapter_16_table_1)
nest <- chapter_16_table_1 |>
  as_tibble() |>
  mutate(Gender = case_when(Gender == 1 ~ "Male",
                            Gender == 2 ~ "Female")) |>
  mutate(Gender  = factor(Gender, levels = c("Male", "Female")),
         Trainee = factor(Trainee))
nest
HideShow
# A tibble: 24 × 3
   Trainee Gender Severity
   <fct>   <fct>     <int>
 1 1       Male         49
 2 1       Male         40
 3 1       Male         31
 4 1       Male         40
 5 2       Male         42
 6 2       Male         48
 7 2       Male         52
 8 2       Male         58
 9 3       Male         42
10 3       Male         46
# ℹ 14 more rows
HideShow
#> The 24 severity ratings of Table 16.1 — matches book p. 935. Trainee is coded
#> 1 through 6 across both genders (book p. 939), so Trainee is already a unique
#> label for each of the six trainees and needs no further construction.

The book reports the ANOVA test first, so that the mixed-effects result can be compared against it. In base R the nested design is fit with an Error() stratum for trainee: gender is tested against the trainee-within-gender mean square, not against the within-trainee mean square.

HideShow
summary(aov(Severity ~ Gender + Error(Trainee), data = nest))
HideShow

Error: Trainee
          Df Sum Sq Mean Sq F value Pr(>F)  
Gender     1   1176    1176   9.966 0.0343 *
Residuals  4    472     118                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: Within
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals 18    820   45.56               
HideShow
#> F(1, 4) = 9.97, p = .0343 — matches book p. 939 and Table 16.3 (p. 943).
#> MS_B/A = 118 and MS_W = 45.5556 — matches book p. 945.

16.5 — Mixed-Effects Models Analysis for the Simple Nested Design

16.5.1 — Numerical Example: Equal nn

Before any inference, the book looks at the pattern of means (Table 16.2), because the whole logic of the analysis rests on treating the six trainee means as the scores that carry the gender comparison.

HideShow
nest |>
  group_by(Gender, Trainee) |>
  summarise(n = n(), Mean = mean(Severity), .groups = "drop")
HideShow
# A tibble: 6 × 4
  Gender Trainee     n  Mean
  <fct>  <fct>   <int> <dbl>
1 Male   1           4    40
2 Male   2           4    50
3 Male   3           4    48
4 Female 4           4    61
5 Female 5           4    54
6 Female 6           4    65
HideShow
#> Male trainees 40, 50, 48; female trainees 61, 54, 65 — matches Table 16.2
#> (book p. 941) and the text on book p. 940.

nest |>
  group_by(Gender) |>
  summarise(n = n(), Mean = mean(Severity))
HideShow
# A tibble: 2 × 3
  Gender     n  Mean
  <fct>  <int> <dbl>
1 Male      12    46
2 Female    12    60
HideShow
#> 46 for the 12 clients seen by males, 60 for the 12 seen by females —
#> matches book p. 940.

The book makes the point explicitly (p. 940) that with equal nn the mixed-effects pp value is exactly the pp value of a two-sample tt test on those six trainee means. That tt test is worth running, because it shows in one line what the mixed-effects machinery is doing: summarizing at the lowest level, then comparing at the higher one.

HideShow
trainee_means <- nest |>
  group_by(Gender, Trainee) |>
  summarise(Mean = mean(Severity), .groups = "drop")

# These are six independent trainee means, one per trainee, so the comparison is
# an unpaired, equal-variance two-sample test. (The formula method of t.test()
# does not accept a `paired` argument, so independence is stated here instead.)
t.test(
  Mean ~ Gender,
  data        = trainee_means,
  alternative = "two.sided",
  conf.level  = 0.95,
  var.equal   = TRUE
)
HideShow

    Two Sample t-test

data:  Mean by Gender
t = -3.1569, df = 4, p-value = 0.03429
alternative hypothesis: true difference in means between group Male and group Female is not equal to 0
95 percent confidence interval:
 -26.312733  -1.687267
sample estimates:
  mean in group Male mean in group Female 
                  46                   60 
HideShow
#> t = -3.157 on 4 df, p = .0343 — the same p value as the ANOVA above and as
#> the mixed-effects analysis below, exactly as the book states (p. 940).

Now the mixed-effects model itself: a fixed effect of gender and a random intercept for each trainee. This is the Equation 16.3 full model, and it is the analysis summarized in Table 16.3.

HideShow
fit_mix <- lmer(Severity ~ Gender + (1 | Trainee), data = nest)
summary(fit_mix)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Severity ~ Gender + (1 | Trainee)
   Data: nest

REML criterion at convergence: 155.2

Scaled residuals: 
    Min      1Q  Median      3Q     Max 
-1.8248 -0.4452 -0.1247  0.6843  1.4141 

Random effects:
 Groups   Name        Variance Std.Dev.
 Trainee  (Intercept) 18.11    4.256   
 Residual             45.56    6.749   
Number of obs: 24, groups:  Trainee, 6

Fixed effects:
             Estimate Std. Error     df t value Pr(>|t|)    
(Intercept)    46.000      3.136  4.000  14.669 0.000126 ***
GenderFemale   14.000      4.435  4.000   3.157 0.034286 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr)
GenderFemal -0.707
HideShow
#> Gender effect 14.0000 with SE 4.4347 on 4 df, t = 3.16, p = .0343 — matches
#> Table 16.3 (book p. 943). SAS codes female as the reference and so reports
#> this as -14.0000 with intercept 60 (the female mean); lmer codes male as the
#> reference, so its intercept is 46 (the male mean, book p. 940) and the sign
#> of the contrast is reversed. The SE, df, t, and p are identical.
#> Trainee variance 18.1111 and Residual 45.5556 — matches Table 16.3 (p. 943).
HideShow
anova(fit_mix, ddf = "Kenward-Roger")
HideShow
Type III Analysis of Variance Table with Kenward-Roger's method
       Sum Sq Mean Sq NumDF DenDF F value  Pr(>F)  
Gender 454.01  454.01     1     4  9.9661 0.03429 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F(1, 4) = 9.97, p = .0343 — matches Table 16.3 (book p. 943) and the ANOVA
#> above. With equal n the two approaches give identical tests of the fixed
#> effect, which is the point of the section (book p. 944).

The book derives the trainee variance by hand from the expected mean squares rather than taking it from the output. Equation 16.6 says σ̂β2=(MSB/A−MSW)/n\hat\sigma^2_\beta = (MS_{B/A} – MS_W)/n, which is worth reproducing because it shows where the estimate comes from.

HideShow
MS_BA <- 118
MS_W  <- 45.5556
n_per <- 4
(MS_BA - MS_W) / n_per
HideShow
[1] 18.1111
HideShow
#> 18.1111 — matches book p. 945 and the Trainee variance in Table 16.3.

The two variances are additive, so the total variance within gender and the proportion of it due to trainee follow directly.

HideShow
vc <- as.data.frame(VarCorr(fit_mix))
sigma2_trainee  <- vc$vcov[vc$grp == "Trainee"]
sigma2_residual <- vc$vcov[vc$grp == "Residual"]
c(trainee  = sigma2_trainee,
  residual = sigma2_residual,
  total    = sigma2_trainee + sigma2_residual,
  icc      = sigma2_trainee / (sigma2_trainee + sigma2_residual))
HideShow
   trainee   residual      total        icc 
18.1111141 45.5555546 63.6666687  0.2844678 
HideShow
#> Total 63.6667 and an intraclass correlation of .2845 — matches book p. 945,
#> where 18.1111 / 63.6667 is reported as 28% of the variance due to trainee
#> and the remaining 72% due to client.

The book also forms a confidence interval for the gender difference from the estimate and its standard error, using the critical tt on 4 degrees of freedom. Done by hand, that is

HideShow
est <- fixef(fit_mix)["GenderFemale"]
se  <- sqrt(vcov(fit_mix)["GenderFemale", "GenderFemale"])
est + c(-1, 1) * qt(0.975, df = 4) * se
HideShow
[1]  1.687266 26.312734
HideShow
#> 1.69 to 26.31 for female minus male. The book works the same interval in the
#> opposite direction, -26.33 to -1.67 (p. 943), using the rounded critical
#> value 2.78; carrying the critical value to full precision moves the endpoints
#> by about .02. The interval excludes zero and is very wide, because the design
#> rests on only six trainees.
The same intraclass correlation, with an interval, in DMAR

The ratio computed above is a point estimate with nothing attached to it. DMAR’s icc_lmer() reads the same quantity off the fitted model and adds the interval and the cluster bookkeeping that the bare ratio leaves out.

HideShow
icc_lmer(fit_mix, conf_level = 0.95)
term value
icc 0.284
sigma2_between 18.111
sigma2_within 45.556
total_variance 63.667
ci_lower 0.000
ci_upper 0.747
n_clusters 6
average_cluster_size 4

Confidence level: 95%

HideShow
#> icc = 0.284 with sigma2_between = 18.111, sigma2_within = 45.556, and
#> total_variance = 63.667 — the same partition as the hand calculation above
#> and as book p. 945. The ci_lower and ci_upper rows are the addition: the
#> interval runs from essentially zero to about .75, which is the honest summary
#> of what six clusters of four observations support.

sjPlot::tab_model() collects the fixed effects, the random-effect variances, and the same ICC in one formatted table.

HideShow
tab_model(fit_mix,
          show.icc    = TRUE,    # the intraclass correlation
          show.re.var = TRUE,    # random-effect variances
          dv.labels   = "Severity")
  Severity
Predictors Estimates CI p
(Intercept) 46.00 39.46 – 52.54 <0.001
Gender [Female] 14.00 4.75 – 23.25 0.005
Random Effects
σ2 45.56
τ00 Trainee 18.11
ICC 0.28
N Trainee 6
Observations 24
Marginal R2 / Conditional R2 0.445 / 0.603

16.5.2 — Numerical Example: Unequal nn

The second example is the inductive reasoning study of Table 16.4. Three classrooms were randomly assigned to a treatment designed to teach inductive reasoning and three to a control, and 29 children in all were measured. Alongside the outcome (Inductive) the data carry two covariates that differ in level: Cognition, a cognitive ability score measured on each student (level 1), and Skill, the teacher’s rated teaching skill, measured on each classroom (level 2). Both are used in Section 16.6.

Rooms are coded 1, 2, 3 within each condition, so “Room 1” in the control condition is a different classroom from “Room 1” in the treatment condition; there are six classrooms in all (book p. 946). The nesting therefore has to be made explicit, by pasting condition and room together into a single grouping factor with six distinct labels. We also grand-mean-center cognitive ability here, because every analysis from Section 16.6.3 onward uses the centered score.

HideShow
data(chapter_16_table_4)
three <- chapter_16_table_4 |>
  as_tibble() |>
  mutate(Condition = case_when(Condition == 0 ~ "Control",
                               Condition == 1 ~ "Treatment")) |>
  mutate(
    Condition = factor(Condition, levels = c("Control", "Treatment")),
    Room      = factor(Room),
    # Six classrooms, six labels: "Control 1" is not "Treatment 1". This is the
    # grouping lmer would build internally from 1 | Condition:Room; writing it
    # out as its own column also lets the classical tools below read the nesting.
    Classroom = factor(paste(Condition, Room, sep = " ")),
    # Grand-mean-centered cognitive ability (book p. 961).
    CogCent   = Cognition - mean(Cognition)
  )
three
HideShow
# A tibble: 29 × 8
   Observation Room  Condition Cognition Skill Inductive Classroom CogCent
         <int> <fct> <fct>         <int> <int>     <int> <fct>       <dbl>
 1           1 1     Control          46     4        21 Control 1  -3.72 
 2           2 1     Control          52     4        26 Control 1   2.28 
 3           3 1     Control          60     4        33 Control 1  10.3  
 4           4 1     Control          44     4        22 Control 1  -5.72 
 5           5 2     Control          46     6        18 Control 2  -3.72 
 6           6 2     Control          48     6        25 Control 2  -1.72 
 7           7 2     Control          50     6        26 Control 2   0.276
 8           8 2     Control          54     6        24 Control 2   4.28 
 9           9 2     Control          50     6        21 Control 2   0.276
10          10 2     Control          48     6        25 Control 2  -1.72 
# ℹ 19 more rows
HideShow
#> The 29 rows of Table 16.4 — matches book p. 948.

mean(three$Cognition)
HideShow
[1] 49.72414
HideShow
#> 49.72 — matches book p. 961, the grand mean subtracted to form "cogcent".

The book establishes a context with the means of all three variables, by condition and by classroom (Table 16.5).

HideShow
three |>
  group_by(Condition) |>
  summarise(n = n(), Inductive = mean(Inductive),
            Cognition = mean(Cognition), Skill = mean(Skill))
HideShow
# A tibble: 2 × 5
  Condition     n Inductive Cognition Skill
  <fct>     <int>     <dbl>     <dbl> <dbl>
1 Control      15      27.3      50.3  6.47
2 Treatment    14      36.5      49.1  6.93
HideShow
#> Control 27.33 on 15 students, treatment 36.50 on 14 — matches Table 16.5
#> (book p. 949) and the text on book p. 947.

three |>
  group_by(Condition, Room) |>
  summarise(n = n(), Inductive = mean(Inductive),
            Cognition = mean(Cognition), Skill = mean(Skill),
            .groups = "drop")
HideShow
# A tibble: 6 × 6
  Condition Room      n Inductive Cognition Skill
  <fct>     <fct> <int>     <dbl>     <dbl> <dbl>
1 Control   1         4      25.5      50.5     4
2 Control   2         6      23.2      49.3     6
3 Control   3         5      33.8      51.2     9
4 Treatment 1         3      29        46       5
5 Treatment 2         5      39.8      51.2     8
6 Treatment 3         6      37.5      49       7
HideShow
#> Classroom means 25.50, 23.17, 33.80 (control) and 29.00, 39.80, 37.50
#> (treatment), on 4, 6, 5, 3, 5, and 6 students — matches Table 16.5
#> (book p. 949). The unequal classroom sizes are the reason the book turns to
#> the mixed-effects model: the ANOVA approach "is unable to handle unequal
#> sample sizes" (book p. 948).

The model is the same one as in Section 16.5.1 — a fixed condition effect and a random intercept for classrooms nested in condition — fit now to unbalanced data.

HideShow
fit_three <- lmer(Inductive ~ Condition + (1 | Classroom), data = three)
summary(fit_three)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Inductive ~ Condition + (1 | Classroom)
   Data: three

REML criterion at convergence: 171

Scaled residuals: 
     Min       1Q   Median       3Q      Max 
-1.39742 -0.74219  0.04089  0.67433  1.93550 

Random effects:
 Groups    Name        Variance Std.Dev.
 Classroom (Intercept) 26.63    5.160   
 Residual              20.26    4.501   
Number of obs: 29, groups:  Classroom, 6

Fixed effects:
                   Estimate Std. Error     df t value Pr(>|t|)   
(Intercept)          27.478      3.203  3.840   8.579  0.00121 **
ConditionTreatment    8.148      4.548  3.899   1.792  0.14955   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr)
CndtnTrtmnt -0.704
HideShow
#> Condition effect 8.1485 with SE 4.5484 — matches Table 16.6 (book p. 950),
#> which prints the standard error as 4.5483.
#> Classroom variance 26.627 and Residual 20.255 — matches Table 16.6 (p. 950).
#> lmer codes control as the reference, so its intercept 27.478 is the control
#> mean; SAS codes the treatment side as the reference and reports the intercept
#> as 35.6261 with COND 0 at -8.1485. The two agree: 27.478 + 8.148 = 35.626.

The book’s FF test uses containment degrees of freedom, which here equal 4: six classrooms less one, less the condition factor. The squared Wald tt referred to 4 denominator degrees of freedom reproduces Table 16.6 exactly.

HideShow
est <- fixef(fit_three)["ConditionTreatment"]
se  <- sqrt(vcov(fit_three)["ConditionTreatment", "ConditionTreatment"])
t_obs <- est / se
c(F_value = unname(t_obs^2), p_value = unname(2 * pt(-abs(t_obs), df = 4)))
HideShow
  F_value   p_value 
3.2095410 0.1476891 
HideShow
#> F(1, 4) = 3.21, p = .1477 — matches Table 16.6 (book p. 950). The data do not
#> allow us to reject the null hypothesis of no treatment effect.

lmerTest can choose the denominator degrees of freedom for us. Its default Satterthwaite method and the Kenward-Roger method both land essentially on the containment value here, though neither is forced to be an integer.

HideShow
anova(fit_three, ddf = "Kenward-Roger")
HideShow
Type III Analysis of Variance Table with Kenward-Roger's method
          Sum Sq Mean Sq NumDF  DenDF F value Pr(>F)
Condition 64.915  64.915     1 3.9882  3.2049 0.1481
HideShow
#> F = 3.20 on 1 and 3.99 denominator df, p = .148. Kenward-Roger also adjusts
#> the standard error, so its F differs from the book's 3.21 in the third digit;
#> the conclusion is the same.

The book then forms the confidence interval for the treatment effect from the same standard error and the critical tt on 4 degrees of freedom.

HideShow
est + c(-1, 1) * qt(0.975, df = 4) * se
HideShow
[1] -4.479798 20.776749
HideShow
#> -4.48 to 20.78, the book's -4.50 to 20.79 (p. 950) up to its rounding of the
#> critical value to 2.78. The treatment could be as beneficial as about 21
#> points or as detrimental as about 4.5; the interval contains zero, and it is
#> this wide because there are only six classrooms.
Profile-likelihood intervals on the variance components

In Section 16.5.1 the design was balanced, so the analytic modified-large-sample interval on the variance components applied (DMAR’s variance_components_mls(), used on these data in the Chapter 10 notes). That formula assumes a single common cell size nn, so it does not apply here: the classrooms hold different numbers of students, which is the whole reason the book analyzes these data with the mixed model. The lme4-native analog, valid for unequal nn, is a REML profile-likelihood interval taken from the fitted model.

HideShow
# Profile intervals come back on the standard-deviation scale; square them for
# variances. The .sig01 row is the Classroom SD, .sigma the residual SD.
ci_sd  <- confint(fit_three, parm = c(".sig01", ".sigma"), method = "profile")
ci_var <- ci_sd^2
rownames(ci_var) <- c("Classroom variance", "Residual variance")
ci_var
HideShow
                       2.5 %   97.5 %
Classroom variance  2.538059 78.90358
Residual variance  11.964581 38.65127
HideShow
#> The point estimates 26.627 and 20.255 (Table 16.6, book p. 950) fall inside
#> these 95% intervals. The classroom-variance interval is very wide, because
#> six classrooms carry little information about a variance.
Is the classroom clustering needed? A likelihood-ratio test

The book does not test the random classroom effect, but the question is a natural one, so we work it here as companion material. The comparison is the mixed model against an ordinary regression with no clustering at all, both fit by maximum likelihood so the likelihoods are comparable. Because the classroom variance sits on the boundary of its parameter space — it cannot be negative — the usual χ2(1)\chi^2(1) tail probability is halved.

HideShow
fit_no_room <- lm(Inductive ~ Condition, data = three)
fit_room    <- lmer(Inductive ~ Condition + (1 | Classroom), data = three,
                    REML = FALSE)

lr      <- as.numeric(2 * (logLik(fit_room) - logLik(fit_no_room)))
p_value <- pchisq(lr, df = 1, lower.tail = FALSE) / 2
tibble(LR_statistic = lr, p_value = p_value)
HideShow
# A tibble: 1 × 2
  LR_statistic p_value
         <dbl>   <dbl>
1         6.62 0.00503

lmerTest::ranova() performs the same single-term deletion directly from the REML fit. Its likelihood ratio is computed on the REML scale and its pp value is not halved, so the two numbers differ; both say the same thing.

HideShow
ranova(fit_three)
HideShow
ANOVA-like table for random-effects: Single term deletions

Model:
Inductive ~ Condition + (1 | Classroom)
                npar  logLik    AIC    LRT Df Pr(>Chisq)   
<none>             4 -85.522 179.04                        
(1 | Classroom)    3 -90.024 186.05 9.0041  1   0.002694 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Both routes say the classrooms differ from one another beyond chance, which is consistent with the sizable classroom variance (26.627) in Table 16.6 and confirms that the clustering should be modeled rather than ignored.

Where the variability sits: a descriptive nested decomposition

Classical ANOVA is not the basis for inference here — the book is explicit that it does not apply with unequal nn (p. 948) — but the nested sums of squares still describe where the variability sits. With Room a factor, aov() reads the nesting correctly: condition on 1 degree of freedom and rooms-within-condition on 4. (Had Room been left numeric it would have entered as a single regression slope on 1 degree of freedom, which is wrong.) We lay it out with gt, and report no FF or pp, because under unequal nn those would not be the tests the book uses.

HideShow
fit_aov <- aov(Inductive ~ Condition + Condition:Room, data = three)
broom::tidy(fit_aov) |>
  mutate(term = recode(term, "Condition:Room" = "Room (within Condition)")) |>
  transmute(Source = term, SS = sumsq, df = df, MS = meansq) |>
  gt() |>
  fmt_number(columns = c(SS, MS), decimals = 2) |>
  tab_header(
    title    = md("**Table 1**. Nested decomposition of inductive reasoning (descriptive)"),
    subtitle = md("Rooms are nested within condition; *n* is unequal, so inference uses the mixed model above.")) |>
  cols_align(align = "center", columns = -Source)
Table 1. Nested decomposition of inductive reasoning (descriptive)
Rooms are nested within condition; n is unequal, so inference uses the mixed model above.
Source SS df MS
Condition 608.48 1 608.48
Room (within Condition) 555.90 4 138.97
Residuals 464.93 23 20.21

16.6 — Mixed-Effects Models for Complex Nested Designs

Section 16.6 extends the unconditional model in two directions, using the two covariates that differ in level. Teaching skill is a property of the classroom (level 2), so it enters the between-classroom part of the model; cognitive ability is a property of the student (level 1), so it enters the within-classroom part and can carry its own random slope. The book treats them in turn.

16.6.2 — Models with Additional Level 2 Variables

Because teaching skill is constant within a classroom, it enters as an additional fixed effect and the random part is unchanged: adding a predictor at the highest level of the hierarchy changes the fixed effects but not the random-effects specification (book p. 955).

HideShow
fit_skill <- lmer(Inductive ~ Condition + Skill + (1 | Classroom), data = three)
summary(fit_skill)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Inductive ~ Condition + Skill + (1 | Classroom)
   Data: three

REML criterion at convergence: 164.5

Scaled residuals: 
     Min       1Q   Median       3Q      Max 
-1.40177 -0.69562 -0.06924  0.51685  2.01182 

Random effects:
 Groups    Name        Variance Std.Dev.
 Classroom (Intercept)  6.572   2.564   
 Residual              20.274   4.503   
Number of obs: 29, groups:  Classroom, 6

Fixed effects:
                   Estimate Std. Error      df t value Pr(>|t|)  
(Intercept)         12.6834     5.5039  3.1807   2.304   0.0996 .
ConditionTreatment   7.5686     2.7163  2.8876   2.786   0.0717 .
Skill                2.3092     0.8086  3.1249   2.856   0.0617 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) CndtnT
CndtnTrtmnt -0.127       
Skill       -0.939 -0.119
HideShow
#> Skill slope 2.3092 with SE 0.8086 and Condition 7.5686 with SE 2.7163 —
#> matches Table 16.7 (book p. 956), where they are 2.3092 (0.8085) and 7.5687
#> (2.7161). The book reads the skill slope as "approximately 2.31" on p. 955:
#> a one-point rise in rated teaching skill goes with a 2.31-point rise in a
#> classroom's mean inductive reasoning score.
#> Classroom variance 6.572 and Residual 20.274, against Table 16.7's 6.5704 and
#> 20.2747 (p. 956): agreement to about three significant digits, the remainder
#> REML convergence tolerance rather than a difference of model.

The book’s tests again use containment degrees of freedom: 3 for condition (one fewer than before, because a classroom-level predictor has been added) and 23 for skill. Those reproduce Table 16.7’s pp values exactly.

HideShow
containment_test <- function(fit, term, df) {
  est <- fixef(fit)[term]
  se  <- sqrt(vcov(fit)[term, term])
  t   <- est / se
  c(estimate = unname(est), se = unname(se),
    F_value = unname(t^2), p_value = unname(2 * pt(-abs(t), df = df)))
}
rbind(
  Condition = containment_test(fit_skill, "ConditionTreatment", df = 3),
  Skill     = containment_test(fit_skill, "Skill",              df = 23)
)
HideShow
          estimate        se  F_value     p_value
Condition 7.568622 2.7162537 7.764134 0.068622920
Skill     2.309244 0.8085643 8.156624 0.008938874
HideShow
#> Condition F(1, 3) = 7.76, p = .0686 and Skill F(1, 23) = 8.16, p = .0089 —
#> matches Table 16.7 (book p. 956), which prints the condition F as 7.77.

Two quantities the book draws from this output are worth reproducing. The first is the confidence interval for the condition effect, which is narrower than it was without teaching skill in the model.

HideShow
est_c <- fixef(fit_skill)["ConditionTreatment"]
se_c  <- sqrt(vcov(fit_skill)["ConditionTreatment", "ConditionTreatment"])
est_c + c(-1, 1) * qt(0.975, df = 3) * se_c
HideShow
[1] -1.075709 16.212954
HideShow
#> -1.07 to 16.21 — matches book p. 955. Compare the -4.50 to 20.79 of the model
#> without teaching skill (p. 950): the interval is substantially narrower,
#> though it still contains zero.

The second is the squared semipartial correlation for teaching skill — the share of the between-classroom variance it accounts for.

HideShow
v_without <- as.data.frame(VarCorr(fit_three))$vcov[1]   # 26.627 (Table 16.6)
v_with    <- as.data.frame(VarCorr(fit_skill))$vcov[1]   #  6.572 (Table 16.7: 6.5704)
(v_without - v_with) / v_without
HideShow
[1] 0.753184
HideShow
#> .75 — matches book p. 957: teaching skill accounts for about 75% of the
#> between-classroom variance in inductive reasoning. The denominator is
#> variance between classrooms, not between students, and the effective sample
#> size behind it is only six classrooms, so the book is careful not to read
#> this as a causal share.

Notice also that the residual variance barely moved: 20.255 without teaching skill, 20.274 with it (book p. 957). A level-2 covariate soaks up between-classroom variance and leaves the within-classroom variance alone, because the level-1 equation is unchanged.

Tidy fixed effects, and the two models side by side

broom.mixed::tidy() puts the fixed effects of a mixed model into a data frame, which is convenient when the next step is a table or a plot rather than reading the console.

HideShow
broom.mixed::tidy(fit_skill, effects = "fixed", conf.int = TRUE, conf.level = 0.95)
HideShow
# A tibble: 3 × 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  (Interce…    12.7      5.50       2.30  3.18  0.0996   -4.28      29.6 
2 fixed  Conditio…     7.57     2.72       2.79  2.89  0.0717   -1.27      16.4 
3 fixed  Skill         2.31     0.809      2.86  3.12  0.0617   -0.207      4.83

modelsummary puts each model in its own column with fit statistics at the foot.

HideShow
modelsummary(
  list("Condition only" = fit_three, "Condition + Skill" = fit_skill),
  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
)
Condition only Condition + Skill
(Intercept) 27.478 12.683
(3.203) (5.504)
ConditionTreatment 8.148 7.569
(4.548) (2.716)
Skill 2.309
(0.809)
SD (Intercept Classroom) 5.160 2.564
SD (Observations) 4.501 4.503
Num.Obs. 29 29
AIC 179.0 174.5
BIC 184.5 181.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_base  <- tbl_regression(fit_three, intercept = TRUE)
t_skill <- tbl_regression(fit_skill, intercept = TRUE)
tbl_merge(list(t_base, t_skill),
          tab_spanner = c("**Condition only**", "**Condition + Skill**"))
Characteristic
Condition only
Condition + Skill
Beta 95% CI p-value Beta 95% CI p-value
(Intercept) 27 18, 37 0.001 13 -4.3, 30 0.10
Condition





    Control — —
— —
    Treatment 8.1 -4.6, 21 0.15 7.6 -1.3, 16 0.072
Skill


2.3 -0.21, 4.8 0.062
Abbreviation: CI = Confidence Interval

sjPlot::tab_model() shows both models with the random-effect variances and the ICC in one view; the fall in the classroom variance from the first column to the second is the 75% reduction computed above.

HideShow
tab_model(fit_three, fit_skill,
          show.icc    = TRUE,
          show.re.var = TRUE,
          dv.labels   = c("Condition only", "Condition + Skill"))
  Condition only Condition + Skill
Predictors Estimates CI p Estimates CI p
(Intercept) 27.48 20.88 – 34.07 <0.001 12.68 1.32 – 24.04 0.030
Condition [Treatment] 8.15 -1.22 – 17.52 0.085 7.57 1.96 – 13.17 0.010
Skill 2.31 0.64 – 3.98 0.009
Random Effects
σ2 20.26 20.27
τ00 26.63 Classroom 6.57 Classroom
ICC 0.57 0.24
N 6 Classroom 6 Classroom
Observations 29 29
Marginal R2 / Conditional R2 0.268 / 0.684 0.555 / 0.664

One caution about all three tables: each package applies its own default degrees of freedom to the fixed effects, and none of them is the book’s containment dfdf. Their pp values therefore differ from one another and from Table 16.6 and Table 16.7. The containment tests computed above are the ones to compare with the book; read these tables for the estimates, the standard errors, and the variance components.

16.6.3 — Models with Additional Level 1 Variables

Cognitive ability is a student characteristic, so it enters the level-1 equation (Equation 16.12), and each classroom is now characterized two ways: by the intercept and by the slope of the within-classroom regression of inductive reasoning on cognitive ability. The book builds the argument from the data before fitting anything, and the three figures below follow it step by step.

Figure 16.1. Inductive reasoning and cognitive ability in one classroom

The book starts inside a single classroom — the first classroom in the control condition, four students — to make concrete what a level-1 regression line is.

HideShow
control_1 <- three |> filter(Classroom == "Control 1")

ggplot(control_1, aes(Cognition, Inductive)) +
  geom_point(size = 2.6) +
  geom_smooth(method = "lm", se = FALSE, color = "#0C2340", linewidth = 1) +
  labs(title = "Figure 16.1. Control classroom 1",
       x = "Cognitive ability", y = "Inductive reasoning")
Figure 16.1. Scatterplot of inductive reasoning and cognitive ability scores for students in the first classroom of the control condition.

Figure 16.1. Scatterplot of inductive reasoning and cognitive ability scores for students in the first classroom of the control condition.

HideShow
coef(lm(Inductive ~ Cognition, data = control_1))
HideShow
(Intercept)   Cognition 
-11.9677419   0.7419355 
HideShow
#> Slope 0.74 and intercept -11.97 for these 4 students — matches book p. 959.
Figure 16.2. Within-classroom regression lines, all six classrooms

The same line is then fit inside each of the six classrooms. The within-classroom slopes need not resemble one another, and they need not resemble the slope that would be obtained by ignoring classrooms altogether: this is the between- versus within-cluster distinction at the heart of the chapter.

HideShow
ggplot(three, aes(Cognition, Inductive, color = Classroom)) +
  geom_point(size = 2.3) +
  geom_smooth(method = "lm", se = FALSE, linewidth = 0.9) +
  labs(title = "Figure 16.2. Within-classroom regression on cognitive ability",
       x = "Cognitive ability", y = "Inductive reasoning", color = NULL)
Figure 16.2. Regression lines relating inductive reasoning and cognitive ability scores within each of six classrooms.

Figure 16.2. Regression lines relating inductive reasoning and cognitive ability scores within each of six classrooms.

Table 16.8 gives the numerical slope and intercept for each classroom.

HideShow
three |>
  group_by(Condition, Room) |>
  summarise(Slope     = coef(lm(Inductive ~ Cognition))[2],
            Intercept = coef(lm(Inductive ~ Cognition))[1],
            .groups   = "drop")
HideShow
# A tibble: 6 × 4
  Condition Room  Slope Intercept
  <fct>     <fct> <dbl>     <dbl>
1 Control   1     0.742    -12.0 
2 Control   2     0.446      1.14
3 Control   3     0.562      5.00
4 Treatment 1     0.125     23.3 
5 Treatment 2     1.03     -13.2 
6 Treatment 3     0.548     10.6 
HideShow
#> Slopes 0.74, 0.45, 0.56 (control) and 0.12, 1.03, 0.55 (treatment);
#> intercepts -11.97, 1.14, 5.00 and 23.25, -13.19, 10.64 — matches Table 16.8
#> (book p. 960).
Figure 16.3. The same lines after centering cognitive ability

An intercept is the fitted value when the predictor is zero, and a cognitive ability score of zero is off the scale, so the intercepts of Table 16.8 are not interpretable. Subtracting the grand mean of 49.72 fixes that: the intercept becomes the classroom’s fitted inductive reasoning score for a student of average cognitive ability. Centering leaves the slopes untouched and moves the intercepts (book p. 961).

HideShow
ggplot(three, aes(CogCent, Inductive, color = Classroom)) +
  geom_point(size = 2.3) +
  geom_smooth(method = "lm", se = FALSE, linewidth = 0.9) +
  labs(title = "Figure 16.3. Within-classroom regression on centered cognitive ability",
       x = "Cognitive ability (centered at the grand mean, 49.72)",
       y = "Inductive reasoning", color = NULL)
Figure 16.3. Regression lines relating inductive reasoning and centered cognitive ability scores within each of six classrooms.

Figure 16.3. Regression lines relating inductive reasoning and centered cognitive ability scores within each of six classrooms.

HideShow
three |>
  group_by(Condition, Room) |>
  summarise(Slope     = coef(lm(Inductive ~ CogCent))[2],
            Intercept = coef(lm(Inductive ~ CogCent))[1],
            .groups   = "drop")
HideShow
# A tibble: 6 × 4
  Condition Room  Slope Intercept
  <fct>     <fct> <dbl>     <dbl>
1 Control   1     0.742      24.9
2 Control   2     0.446      23.3
3 Control   3     0.563      33.0
4 Treatment 1     0.125      29.5
5 Treatment 2     1.03       38.3
6 Treatment 3     0.548      37.9
HideShow
#> Slopes unchanged at 0.74, 0.45, 0.56, 0.12, 1.03, 0.55; intercepts now
#> 24.92, 23.34, 32.97, 29.47, 38.27, 37.90 — matches Table 16.9 (book p. 962).
#> Centering has produced a clearer separation between the control and treatment
#> intercepts than Table 16.8 showed.

Substituting the book’s two level-2 equations — 16.13 for the intercept and 16.14 for the slope (book p. 963) — into the level-1 equation gives the single-equation full model of Equation 16.15 (book p. 964). It lets each classroom have its own intercept and its own slope on centered cognitive ability, allows the two to covary, and adds a condition-by-cognition interaction to the fixed part. In lmer notation that is Inductive ~ Condition * CogCent + (CogCent | Classroom).

HideShow
fit_cog <- lmer(Inductive ~ Condition * CogCent + (CogCent | Classroom),
                data = three)
summary(fit_cog)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Inductive ~ Condition * CogCent + (CogCent | Classroom)
   Data: three

REML criterion at convergence: 157.5

Scaled residuals: 
     Min       1Q   Median       3Q      Max 
-1.50204 -0.61776  0.02134  0.67690  1.67423 

Random effects:
 Groups    Name        Variance  Std.Dev. Corr 
 Classroom (Intercept) 18.524896 4.30406       
           CogCent      0.004772 0.06908  1.00 
 Residual              11.738104 3.42609       
Number of obs: 29, groups:  Classroom, 6

Fixed effects:
                           Estimate Std. Error       df t value Pr(>|t|)    
(Intercept)                27.03544    2.64430  3.76183  10.224 0.000702 ***
ConditionTreatment          9.06664    3.75887  3.82427   2.412 0.076333 .  
CogCent                     0.66722    0.21293 12.98348   3.133 0.007931 ** 
ConditionTreatment:CogCent -0.02521    0.30052 12.53846  -0.084 0.934479    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) CndtnT CogCnt
CndtnTrtmnt -0.703              
CogCent      0.127 -0.090       
CndtnTrt:CC -0.090  0.191 -0.709
optimizer (nloptwrap) convergence code: 0 (OK)
boundary (singular) fit: see help('isSingular')

Two things to read here. First, the residual variance has fallen from 20.255 in the unconditional model to about 11.74. The book reports 11.80 (Table 16.10, book p. 966, discussed p. 969) against 20.26 and 20.27 for the two earlier models: cognitive ability explains a large share of the within-classroom variance, the part teaching skill left untouched. Second, lme4 reports a singular fit. The three classroom covariance parameters below show where this fit reached a boundary.

HideShow
isSingular(fit_cog)
HideShow
[1] TRUE
HideShow
as.data.frame(VarCorr(fit_cog))
HideShow
        grp        var1    var2         vcov     sdcor
1 Classroom (Intercept)    <NA> 18.524896203 4.3040558
2 Classroom     CogCent    <NA>  0.004772074 0.0690802
3 Classroom (Intercept) CogCent  0.297325019 1.0000000
4  Residual        <NA>    <NA> 11.738103906 3.4260916

In two treatment classrooms, the slopes in Table 16.9 are 0.12 and 1.03 points of predicted inductive reasoning per point of cognitive ability. These fitted slopes vary with the students sampled, and the slope variance in Table 16.10 estimates how much the underlying slopes vary among classrooms within the same condition after accounting for that sampling variation. With 29 students in six classrooms, SAS estimated the slope variance at its lower bound of zero (p. 969) and reported an intercept–slope covariance of 0.7246. In R, lme4 requires the two variances and their covariance to form a valid covariance matrix and reaches its boundary with a slope variance of 0.00477 and an intercept–slope correlation of +1.

Both fits give a residual variance near 11.8, a fitted treatment advantage of about 9 points at average cognitive ability, and little evidence that the average slope differs by treatment condition.

The book warns (p. 967) that the cogcent row of the solution is a simple effect, not a main effect: with treatment contrasts it is the slope in the reference condition. Table 16.10’s Type 3 test of cognitive ability is instead the slope averaged over conditions, which in R comes from sum-to-zero contrasts on condition.

HideShow
three_sum <- three
contrasts(three_sum$Condition) <- contr.sum(2)
fit_cog_sum <- lmer(Inductive ~ Condition * CogCent + (CogCent | Classroom),
                    data = three_sum)
rbind(
  Condition           = containment_test(fit_cog_sum, "Condition1",         df = 4),
  CogCent             = containment_test(fit_cog_sum, "CogCent",            df = 4),
  `Condition:CogCent` = containment_test(fit_cog_sum, "Condition1:CogCent", df = 4)
)
HideShow
                     estimate        se      F_value    p_value
Condition         -4.53325266 1.8795752  5.817018265 0.07340763
CogCent            0.65459905 0.1502679 18.976593569 0.01209798
Condition:CogCent  0.01261834 0.1502679  0.007051341 0.93711315
HideShow
#> F(1, 4) = 5.82, 18.98, and 0.01 against Table 16.10's 5.18, 19.63, and 0.10
#> (book p. 966). Same three conclusions — condition not quite significant,
#> cognitive ability significant, no interaction — with the last digits moved by
#> the boundary described above, not by a different model. Only the F and p
#> columns are comparable here: under sum-to-zero coding the Condition estimate
#> is the control group's deviation from the grand mean, which is half the
#> treatment-minus-control effect with the sign reversed.

Dropping the uninformative random slope gives a non-singular fit that carries the same message and is easier to defend from six classrooms.

HideShow
fit_cog_ri <- lmer(Inductive ~ Condition * CogCent + (1 | Classroom), data = three)
as.data.frame(VarCorr(fit_cog_ri))
HideShow
        grp        var1 var2     vcov    sdcor
1 Classroom (Intercept) <NA> 18.08857 4.253066
2  Residual        <NA> <NA> 11.81926 3.437915
HideShow
anova(fit_cog_ri, ddf = "Kenward-Roger")
HideShow
Type III Analysis of Variance Table with Kenward-Roger's method
                   Sum Sq Mean Sq NumDF   DenDF F value    Pr(>F)    
Condition          71.372  71.372     1  3.9583  6.0386 0.0705527 .  
CogCent           237.222 237.222     1 21.6364 20.0708 0.0001935 ***
Condition:CogCent   0.002   0.002     1 21.6364  0.0002 0.9901447    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Residual 11.82, essentially the 11.8050 of Table 16.10 (book p. 966). The
#> cognitive-ability and interaction tests carry far more denominator df here
#> than in Table 16.10: with no random slope, cognitive ability becomes an
#> ordinary within-classroom effect, whereas the book's retained-but-zero slope
#> holds those tests to 4 df.

The headline comparison the book draws (p. 967) is what including cognitive ability does to the condition test.

HideShow
containment_test(fit_cog, "ConditionTreatment", df = 4)
HideShow
  estimate         se    F_value    p_value 
9.06663504 3.75886729 5.81806116 0.07339044 
HideShow
#> p = .073 here against the .1477 of the unconditional model (Table 16.6,
#> book p. 950). The book's Table 16.10 gives .0852 for the same comparison
#> (p. 967). Either way, including a level-1 covariate that predicts the outcome
#> has sharpened the test of the treatment effect, which is the book's point.
HideShow
est_g <- fixef(fit_cog)["ConditionTreatment"]
se_g  <- sqrt(vcov(fit_cog)["ConditionTreatment", "ConditionTreatment"])
est_g + c(-1, 1) * qt(0.975, df = 4) * se_g
HideShow
[1] -1.369654 19.502924
HideShow
#> -1.37 to 19.50. The book's interval from Table 16.10 is -1.99 to 19.97
#> (p. 968), built from its estimate 8.99 and SE 3.9487. Both are narrower than
#> the -4.50 to 20.79 of the model without covariates, and both still contain
#> zero: with six classrooms the treatment effect remains poorly pinned down.
HideShow
tab_model(fit_cog_ri,
          show.icc    = TRUE,
          show.re.var = TRUE,
          dv.labels   = "Inductive (with cognitive ability, level 1)")
  Inductive (with cognitive ability, level 1)
Predictors Estimates CI p
(Intercept) 27.07 21.66 – 32.49 <0.001
Condition [Treatment] 9.15 1.45 – 16.84 0.022
CogCent 0.67 0.24 – 1.10 0.004
Condition [Treatment] ×
CogCent
-0.00 -0.61 – 0.61 0.990
Random Effects
σ2 11.82
τ00 Classroom 18.09
ICC 0.60
N Classroom 6
Observations 29
Marginal R2 / Conditional R2 0.481 / 0.795

16.7 — Power Analysis and Sample Size Planning

The book gives three routes for planning a study that will be analyzed with a mixed-effects model for nested data. The first assumes an idealized equal-nn design and uses the Chapter 10 power machinery; because maximum likelihood does not map onto least squares in general, the resulting NN is a lower bound — a principled best case. The second builds an exemplary data set in which each cell’s supposed population mean is repeated according to its planned cell size, fits the model with the error variance fixed at its supposed value, converts the test statistic into a noncentrality parameter, and iterates over sample sizes. The third is an a priori Monte Carlo simulation, which is the most flexible of the three: it accommodates unequal cell sizes and differential rates of missing data, and it can target power and precision at once.

Clustering and the design effect

The book does not work the design effect in this chapter, but it is the quickest way to see what the clustering above costs, so we add it here. When clusters are the unit of assignment and individuals are the unit of analysis, the effective sample size is the nominal one divided by

DE=1+(m−1)ρI, \text{DE} \;=\; 1 + (m – 1)\,\rho_I,

where mm is the cluster size and ρI\rho_I the intraclass correlation. The inductive reasoning data supply both ingredients from the unconditional model of Section 16.5.2.

HideShow
vc_three <- as.data.frame(VarCorr(fit_three))
rho_I    <- vc_three$vcov[1] / sum(vc_three$vcov)
m_bar    <- mean(table(three$Classroom))
c(icc = rho_I, mean_cluster_size = m_bar,
  design_effect = 1 + (m_bar - 1) * rho_I)
HideShow
              icc mean_cluster_size     design_effect 
        0.5679603         4.8333333         3.1771810 

With an ICC near .57, even classrooms this small cost a factor of about three. A study of 29 children clustered this way carries roughly the information of nine independent ones, which is the arithmetic behind the stubbornly wide intervals throughout the chapter.

DMAR’s design_effect() does the same arithmetic and adds what the one-line formula cannot: Kish’s correction for unequal cluster sizes, the effective nn, and the cluster bookkeeping.

HideShow
design_effect(cluster_sizes = as.vector(table(three$Classroom)), icc = rho_I)
term value
design_effect 3.311
deft 1.820
effective_n 8.759
N 29
n_clusters_total 6
n_clusters_with_data 6
n_clusters_empty 0
n_clusters_singletons 0
n_clusters_informative 6
m_bar 4.833
m_kish 5.069
icc 0.568

The m_bar row is the simple mean cluster size used above; m_kish is the variance-weighted size that the unequal classroom sizes call for, and the design effect reported is the one built from it. The effective_n row translates the whole thing back into a number of independent observations.

The same ICC drives sample size planning. DMAR’s cluster-randomized AIPE family plans for a target confidence-interval width on the treatment effect rather than for power — the ss_aipe_crd_* functions — and a Fisher-transform planner handles the companion question of planning to estimate an ICC precisely in the first place.

HideShow
# Clusters needed for a standardized treatment effect estimated to within a
# full-width of 0.5, with 20 individuals per cluster and an ICC of .05.
ss_aipe_crd_n_clusters_fixed_width(
  width          = 0.5,
  cluster_size   = 20,
  pr_treat       = 0.5,
  true_icc       = 0.05,
  true_total_var = 1,
  conf_level     = 0.95
)
term value
necessary_n_clusters 27
width 0.500
expected_width 0.495

Confidence level: 95%

HideShow
# Clusters needed to estimate an ICC of .10 to within a full-width of .10,
# with 20 observations per cluster.
ss_aipe_icc(
  true_icc   = 0.10,
  n_raters   = 20,
  width      = 0.10,
  conf_level = 0.95,
  type       = "ICC(1,1)"
)
term value
necessary_N 58
expected_width 0.100
true_icc 0.100
n_raters 20
width 0.100
conf_level 0.950

Confidence level: 95%

Both planners make the chapter’s recurring lesson quantitative: with clustered data it is the number of clusters, far more than the number of individuals inside them, that buys precision.

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 16: An Introduction to Mixed-Effects Models: Nested 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