Chapter 10: Designs with Random or Nested Factors

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 10 works out what changes when a factor’s levels are a random sample from a population of levels rather than the particular levels of interest. The chapter’s organizing device is the expected mean square: once the expected value of each mean square is known, the correct denominator for each FF test follows, and the familiar habit of dividing everything by MSWMS_W is revealed as a source of positive bias for the fixed factor in a mixed design. Section 10.3 develops this for completely crossed designs, where the fixed factor is tested against the fixed-by-random interaction. Section 10.4 develops the parallel case for nested designs, where no interaction with the nested factor exists and the fixed effect is instead tested against the pooled variability among the clusters. Both sections close with measures of association strength: ω̂2\widehat\omega^2 for the fixed factor and the intraclass correlation ρI\rho_I for the random ones, each built from variance components recovered from the mean squares.

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_10_table_5 (the ACT training example, a crossed mixed design) and chapter_10_table_9 (the clinical trainee example, a nested design).

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(emmeans)        # estimated marginal means and simultaneous confidence intervals
library(lme4)           # fit mixed-effects models
library(lmerTest)       # p-values 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

10.3 — Designs with Random Factors

10.3.3 — Two-Factor Case

10.3.3.1 — Expected Mean Squares

Table 10.1 makes the problem concrete before any test statistic is computed. Part I of the table gives the population mean ratings of 18 clinical trainees under three therapy modes, arranged so that in the population there is no main effect of either factor: every trainee has an average effectiveness of 4 and every therapy mode has a mean of 4. Part II then takes the three trainees g, k, and r as the sampled “levels” of the random factor. No error component is involved at all; these are population cell means.

HideShow
# Table 10.1, part II: population mean ratings for three therapy modes with
# trainees g, k, and r as the sampled levels of the random factor. The labels
# are written out level by level, so the correspondence is visible rather than
# order-dependent, and factor() is used only to fix the display order.
table_10_1 <- data.frame(
  Therapy = rep(c("Psychodynamic", "Behavioral", "Rogerian"), each = 3),
  Trainee = rep(c("g", "k", "r"), times = 3),
  Mean    = c(4, 2, 3,
              7, 6, 4,
              1, 4, 5)
)
table_10_1$Therapy <- factor(table_10_1$Therapy,
  levels = c("Psychodynamic", "Behavioral", "Rogerian"))

# Marginal means for the fixed factor (therapy mode).
round(tapply(table_10_1$Mean, table_10_1$Therapy, mean), 2)
HideShow
Psychodynamic    Behavioral      Rogerian 
         3.00          5.67          3.33 
HideShow
#> 3.00, 5.67, 3.33 — matches Table 10.1, part II, book p. 536

# Marginal means for the three sampled trainees, and the grand mean.
tapply(table_10_1$Mean, table_10_1$Trainee, mean)
HideShow
g k r 
4 4 4 
HideShow
#> all 4 — matches book p. 536
mean(table_10_1$Mean)
HideShow
[1] 4
HideShow
#> 4 — matches book p. 536

The trainee marginal means are still identical, but the therapy-mode means are not: this particular sample of three trainees makes the behavioral approach look most effective and the psychodynamic approach worst, when in the full population of 18 trainees there is no therapy-mode effect whatsoever. The apparent effect is entirely an artifact of the interaction between the random and the fixed factor, and it is why Table 10.3 shows the expected mean square for the fixed factor AA in a mixed design as σε2+nσαβ2+bnθα2\sigma^2_\varepsilon + n\sigma^2_{\alpha\beta} + bn\theta^2_\alpha rather than σε2+bnθα2\sigma^2_\varepsilon + bn\theta^2_\alpha.

To see what that extra component does to a test statistic, we can add client-level error to the Part II population means and run both candidate FF tests. This simulation is a companion illustration rather than a book computation: the book deliberately bypasses the error component in Table 10.1.

HideShow
# A companion illustration: client ratings around the Table 10.1 population
# means, five clients per trainee-by-mode cell.
set.seed(113)

n_per_cell <- 5
sim_data <- data.frame(
  Therapy    = rep(table_10_1$Therapy, each = n_per_cell),
  Trainee    = rep(table_10_1$Trainee, each = n_per_cell),
  TargetMean = rep(table_10_1$Mean,    each = n_per_cell)
)
sim_data$Rating <- sim_data$TargetMean +
  rnorm(nrow(sim_data), mean = 0, sd = 1.2)

# The crossed model supplies every mean square we need.
sim_model <- aov(Rating ~ Therapy * Trainee, data = sim_data)
sim_table <- as.data.frame(summary(sim_model)[[1]])
sim_table
HideShow
                Df     Sum Sq   Mean Sq    F value       Pr(>F)
Therapy          2  91.937226 45.968613 27.7933266 5.017248e-08
Trainee          2   0.659002  0.329501  0.1992213 8.202657e-01
Therapy:Trainee  4 109.923542 27.480886 16.6153639 8.439692e-08
Residuals       36  59.541993  1.653944         NA           NA
HideShow
ms_therapy_sim     <- sim_table[1, "Mean Sq"]
ms_trainee_sim     <- sim_table[2, "Mean Sq"]
ms_interaction_sim <- sim_table[3, "Mean Sq"]
ms_within_sim      <- sim_table[4, "Mean Sq"]

df_therapy_sim     <- sim_table[1, "Df"]
df_trainee_sim     <- sim_table[2, "Df"]
df_interaction_sim <- sim_table[3, "Df"]
df_within_sim      <- sim_table[4, "Df"]

# The habitual test: MS_A / MS_W, which ignores that the trainees are a sample.
f_incorrect <- ms_therapy_sim / ms_within_sim
p_incorrect <- pf(f_incorrect, df_therapy_sim, df_within_sim, lower.tail = FALSE)

# The mixed-model test: MS_A / MS_AB.
f_correct <- ms_therapy_sim / ms_interaction_sim
p_correct <- pf(f_correct, df_therapy_sim, df_interaction_sim, lower.tail = FALSE)

cat(sprintf("Therapy tested against MS_W  : F(%d, %d) = %.3f, p = %.5f\n",
            df_therapy_sim, df_within_sim, f_incorrect, p_incorrect),
    sprintf("Therapy tested against MS_AB : F(%d, %d) = %.3f, p = %.5f\n",
            df_therapy_sim, df_interaction_sim, f_correct, p_correct),
    sep = "")
HideShow
Therapy tested against MS_W  : F(2, 36) = 27.793, p = 0.00000
Therapy tested against MS_AB : F(2, 4) = 1.673, p = 0.29654

Tested against MSWMS_W, the therapy effect comes out at F=27.79F = 27.79 with p<.0001p < .0001 — a confident conclusion that one therapy is better than another, drawn from a population in which no therapy-mode effect exists. Tested against MSABMS_{AB}, the same data give F=1.67F = 1.67, p=0.297p = 0.297, and the null hypothesis is retained. That is the positive bias of the preceding paragraphs: the within-cell error term is too small because it carries no interaction component, so the ratio is inflated by variability that belongs to these three particular trainees rather than to the therapies.

10.3.3.3 — Selection of Error Terms

Table 10.4 states the choice of denominator for every effect in the three two-factor crossed designs. For the mixed design (factor AA fixed, factor BB random), the error term for AA is MSABMS_{AB}, while BB and ABAB are both tested against MSWMS_W. Applying that table to the simulated trainee data is a matter of pairing each numerator with the right denominator and the right degrees of freedom.

HideShow
# Table 10.4, mixed design: A against MS_AB; B and AB against MS_W.
f_trainee_sim   <- ms_trainee_sim / ms_within_sim
p_trainee_sim   <- pf(f_trainee_sim, df_trainee_sim, df_within_sim,
                      lower.tail = FALSE)

f_interact_sim  <- ms_interaction_sim / ms_within_sim
p_interact_sim  <- pf(f_interact_sim, df_interaction_sim, df_within_sim,
                      lower.tail = FALSE)

data.frame(
  Effect      = c("Therapy (A, fixed)", "Trainee (B, random)", "Interaction (AB)"),
  Denominator = c("MS_AB", "MS_within", "MS_within"),
  df_num      = c(df_therapy_sim, df_trainee_sim, df_interaction_sim),
  df_denom    = c(df_interaction_sim, df_within_sim, df_within_sim),
  F_value     = round(c(f_correct, f_trainee_sim, f_interact_sim), 3),
  p_value     = round(c(p_correct, p_trainee_sim, p_interact_sim), 4)
)
HideShow
               Effect Denominator df_num df_denom F_value p_value
1  Therapy (A, fixed)       MS_AB      2        4   1.673  0.2965
2 Trainee (B, random)   MS_within      2       36   0.199  0.8203
3    Interaction (AB)   MS_within      4       36  16.615  0.0000

The three rows tell a story a fixed-effects analysis would have missed. The therapy effect is not significant once it must exceed the inconsistency among trainees. There is no main effect of trainee: on average the three were equally effective. The interaction is large, which is the whole point — effectiveness depends on the pairing of therapist with method, and that is exactly the component inflating the naive test of therapy mode.

10.3.4 — Numerical Example

An educational products firm compares a computer-based ACT study program with a packet of printed materials. Four high schools are sampled at random, ten junior volunteers at each school are split evenly between the two programs, and the posttest is a simulated ACT. Study program is factor AA (fixed; a1a_1 is the computer-based program, a2a_2 the paper-and-pencil program) and school is factor BB (random). The data are Table 10.5.

HideShow
data(chapter_10_table_5)
str(chapter_10_table_5)
HideShow
'data.frame':   40 obs. of  3 variables:
 $ A  : int  1 1 1 1 1 1 1 1 1 1 ...
 $ B  : int  1 1 1 1 1 2 2 2 2 2 ...
 $ ACT: int  28 26 26 23 17 26 26 25 21 17 ...
HideShow
# Spell out the correspondence between the numeric codes and the program names,
# then use factor() only to fix the level order (a1 first, as in the book).
chapter_10_table_5 <- chapter_10_table_5 |>
  mutate(Program = case_when(
    A == 1 ~ "Computer",
    A == 2 ~ "Paper-and-Pencil"
  )) |>
  mutate(Program = factor(Program,
                          levels = c("Computer", "Paper-and-Pencil")),
         School  = factor(B))

# Cell means and within-cell variances, part I of Table 10.5.
chapter_10_table_5 |>
  group_by(Program, School) |>
  summarise(mean = mean(ACT), variance = var(ACT), n = n(), .groups = "drop")
HideShow
# A tibble: 8 × 5
  Program          School  mean variance     n
  <fct>            <fct>  <dbl>    <dbl> <int>
1 Computer         1         24     18.5     5
2 Computer         2         23     15.5     5
3 Computer         3         19     25       5
4 Computer         4         18     12       5
5 Paper-and-Pencil 1         26     18.5     5
6 Paper-and-Pencil 2         29     14.5     5
7 Paper-and-Pencil 3         25     26       5
8 Paper-and-Pencil 4         28     14.5     5
HideShow
#> cell means 24, 23, 19, 18 and 26, 29, 25, 28 — matches Table 10.5, book p. 543
#> cell variances 18.5, 15.5, 25.0, 12.0 and 18.5, 14.5, 26.0, 14.5 — book p. 543

# Marginal means.
tapply(chapter_10_table_5$ACT, chapter_10_table_5$Program, mean)
HideShow
        Computer Paper-and-Pencil 
              21               27 
HideShow
#> 21 and 27 — matches book p. 543
tapply(chapter_10_table_5$ACT, chapter_10_table_5$School, mean)
HideShow
 1  2  3  4 
25 26 22 23 
HideShow
#> 25, 26, 22, 23 — matches book p. 543
mean(chapter_10_table_5$ACT)
HideShow
[1] 24
HideShow
#> 24 — matches book p. 543

The sums of squares, degrees of freedom, and mean squares are computed exactly as in a fixed-effects two-way design; only the denominators of the FF tests change. The crossed aov() fit supplies all of them.

HideShow
model_act <- aov(ACT ~ Program * School, data = chapter_10_table_5)
res_act   <- as.data.frame(summary(model_act)[[1]])
res_act
HideShow
               Df Sum Sq   Mean Sq   F value       Pr(>F)
Program         1    360 360.00000 19.930796 9.352074e-05
School          3    100  33.33333  1.845444 1.588054e-01
Program:School  3     80  26.66667  1.476355 2.395151e-01
Residuals      32    578  18.06250        NA           NA
HideShow
#> SS 360, 100, 80, 578 and MS 360.000, 33.333, 26.667, 18.063 — matches
#> Table 10.5, part III, book p. 543

ms_program     <- res_act[1, "Mean Sq"]
ms_school      <- res_act[2, "Mean Sq"]
ms_interaction <- res_act[3, "Mean Sq"]
ms_within      <- res_act[4, "Mean Sq"]

df_program     <- res_act[1, "Df"]
df_school      <- res_act[2, "Df"]
df_interaction <- res_act[3, "Df"]
df_within      <- res_act[4, "Df"]

The novel feature of the source table is the test of the fixed factor, whose denominator is MSABMS_{AB} rather than MSWMS_W.

HideShow
f_mixed <- ms_program / ms_interaction
p_mixed <- pf(f_mixed, df_program, df_interaction, lower.tail = FALSE)
c(F = f_mixed, p = p_mixed)
HideShow
          F           p 
13.50000000  0.03489698 
HideShow
#> F_A = 360 / 26.667 = 13.500 on (1, 3) df, p = .035 — matches book p. 542

# The critical value the observed F is compared against.
qf(0.95, df_program, df_interaction)
HideShow
[1] 10.12796
HideShow
#> 10.128, which book p. 542 quotes to one decimal as 10.1

For contrast, the same numerator divided by MSWMS_W gives the liberal test the book reports in Section 10.3.5.

HideShow
f_fixed <- ms_program / ms_within
p_fixed <- pf(f_fixed, df_program, df_within, lower.tail = FALSE)
c(F = f_fixed, p = p_fixed)
HideShow
           F            p 
1.993080e+01 9.352074e-05 
HideShow
#> F_obs(1, 32) = 19.931, p = .00009 — matches book p. 542

The full source table of Table 10.5, in APA style with gt. The FF and pp columns use the Table 10.4 denominators: MSABMS_{AB} for the fixed program effect, MSWMS_W for the random school factor and for the interaction. Partial η2\eta^2 for each effect is its share of effect-plus-within variance, which is the book’s Rpartial2R^2_{partial} of Equation 10.14.

HideShow
ss_within_act <- res_act[4, "Sum Sq"]

act_source <- data.frame(
  Source = c("A (Program, fixed)", "B (School, random)", "AB", "Within"),
  SS     = res_act[, "Sum Sq"],
  df     = res_act[, "Df"],
  MS     = res_act[, "Mean Sq"],
  Fstat  = c(f_mixed,
             ms_school / ms_within,
             ms_interaction / ms_within,
             NA_real_),
  p      = c(p_mixed,
             pf(ms_school / ms_within, df_school, df_within, lower.tail = FALSE),
             pf(ms_interaction / ms_within, df_interaction, df_within,
                lower.tail = FALSE),
             NA_real_),
  Denom  = c("AB", "Within", "Within", ""),
  row.names = NULL
)
act_source$peta <- ifelse(act_source$Source == "Within", NA_real_,
                          act_source$SS / (act_source$SS + ss_within_act))

act_source |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 3) |>
  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("**Table 10.5**. Analysis of Variance for ACT Score")) |>
  cols_align(align = "center", columns = -Source)
Table 10.5. Analysis of Variance for ACT Score
Source SS df MS F p Denom Partial η2
A (Program, fixed) 360.000 1 360.000 13.500 0.0349 AB 0.384
B (School, random) 100.000 3 33.333 1.845 0.1588 Within 0.147
AB 80.000 3 26.667 1.476 0.2395 Within 0.122
Within 578.000 32 18.063


HideShow
#> F = 13.500, 1.845, 1.476 with p = .035, .159, .240 — matches Table 10.5,
#> part III, book p. 543

The two analyses of the same data differ in what they license. The fixed-effects test is restricted to these 40 students at these four schools; the mixed-model test speaks to the population of American high schools, and pays for that reach with denominator degrees of freedom that fall from 32 to 3. The school, not the student, becomes the unit of analysis for the fixed effect, and pp moves from .00009 to .035.

The Program-by-School cell means

Why the price is worth paying is easiest to see in the cell means. The two programs do not differ by a constant across schools — the gap is 2 points at School 1 and 10 at School 4 — and that non-parallelism is the MSABMS_{AB} that the mixed-model test must overcome. The dashed navy lines are the two program marginal means, 21 and 27.

HideShow
act_cell_means <- chapter_10_table_5 |>
  group_by(Program, School) |>
  summarise(Mean = mean(ACT), .groups = "drop")

act_program_means <- chapter_10_table_5 |>
  group_by(Program) |>
  summarise(Mean = mean(ACT), .groups = "drop")

ggplot(act_cell_means, aes(x = School, y = Mean,
                           group = Program, colour = Program)) +
  geom_hline(data = act_program_means, aes(yintercept = Mean),
             inherit.aes = FALSE,
             linetype = "dashed", colour = "#0C2340") +
  geom_line() +
  geom_point(size = 2.5) +
  labs(x = "School (random factor)",
       y = "Mean simulated ACT score",
       colour = "Study program")
Mean simulated ACT score for each study program at each of the four randomly sampled schools, with the two program marginal means as dashed reference lines.

Mean simulated ACT score for each study program at each of the four randomly sampled schools, with the two program marginal means as dashed reference lines.

The same source table in DMAR

The bookkeeping above — build the crossed ANOVA table, then divide MSAMS_A by MSABMS_{AB} by hand and look up the right degrees of freedom — is what DMAR’s mixed_anova() packages. What the function adds is that the fixed-versus-random decision becomes an explicit argument rather than an unwritten convention, and the denominator actually used is reported in a column of the output, so the table carries its own audit trail.

HideShow
mixed_anova(
  data     = chapter_10_table_5,
  outcome  = "ACT",
  factor_A = "Program", A_type = "fixed",
  factor_B = "School",  B_type = "random"
)
effect ss df ms denominator F_value p_value
A 360 1 360.000 MS_AB 13.500 0.0349
B 100 3 33.333 MS_within 1.845 0.1588
A:B 80 3 26.667 MS_within 1.476 0.2395
HideShow
#> A: F = 13.500 on (1, 3) df, p = .0349 against MS_AB — matches book p. 542
#> B: F = 1.845, p = .1588 and A:B: F = 1.476, p = .2395 against MS_within —
#>    matches Table 10.5, book p. 543

Every number agrees with the hand computation and with the book’s source table, which is the point of showing both: the base-R route makes the choice of denominator visible, and the DMAR call records it.

10.3.5 — Alternative Tests and Design Considerations with Random Factors

If one is willing to treat the interaction as absent — the book’s example is a preliminary test of ABAB returning p>.2p > .2, which is the case here — the αβ\alpha\beta term can be dropped and the interaction and within-cell sources pooled into a single residual.

HideShow
ss_interaction <- res_act[3, "Sum Sq"]
ss_within      <- res_act[4, "Sum Sq"]

df_pooled <- df_interaction + df_within
ms_pooled <- (ss_interaction + ss_within) / df_pooled
ms_pooled
HideShow
[1] 18.8
HideShow
#> MS_residual = (578 + 80) / (32 + 3) = 658 / 35 = 18.80 — matches book p. 544

f_pooled <- ms_program / ms_pooled
p_pooled <- pf(f_pooled, df_program, df_pooled, lower.tail = FALSE)
c(F = f_pooled, p = p_pooled)
HideShow
           F            p 
1.914894e+01 1.038738e-04 
HideShow
#> F(1, 35) = 19.149, p = .0001 — matches book p. 544

If instead one concluded there was no evidence for either a BB effect or an ABAB interaction, the analysis could be rerun as a one-factor design, pooling BB, ABAB, and within.

HideShow
ss_school  <- res_act[2, "Sum Sq"]
df_pooled2 <- df_school + df_interaction + df_within
ms_pooled2 <- (ss_school + ss_interaction + ss_within) / df_pooled2

f_pooled2 <- ms_program / ms_pooled2
p_pooled2 <- pf(f_pooled2, df_program, df_pooled2, lower.tail = FALSE)
c(F = f_pooled2, p = p_pooled2)
HideShow
           F            p 
18.047493404  0.000134292 
HideShow
#> F(1, 38) = 18.047, p = .0001 — matches book p. 544

The four tests of the same fixed effect, side by side.

HideShow
data.frame(
  Test_logic  = c("Mixed model", "Pooled AB and within",
                  "Pooled B, AB and within", "Fixed effects"),
  Denominator = c("MS_AB", "MS_residual", "MS_residual (one-factor)", "MS_within"),
  MS_denom    = round(c(ms_interaction, ms_pooled, ms_pooled2, ms_within), 3),
  df_denom    = c(df_interaction, df_pooled, df_pooled2, df_within),
  F_value     = round(c(f_mixed, f_pooled, f_pooled2, f_fixed), 3),
  p_value     = signif(c(p_mixed, p_pooled, p_pooled2, p_fixed), 4)
)
HideShow
               Test_logic              Denominator MS_denom df_denom F_value
1             Mixed model                    MS_AB   26.667        3  13.500
2    Pooled AB and within              MS_residual   18.800       35  19.149
3 Pooled B, AB and within MS_residual (one-factor)   19.947       38  18.047
4           Fixed effects                MS_within   18.063       32  19.931
    p_value
1 3.490e-02
2 1.039e-04
3 1.343e-04
4 9.352e-05

The legitimacy of the last three rows hinges on the preliminary test having reached the right conclusion. As the book argues, an ABAB interaction that went undetected is still an ABAB interaction, so continuing to use MSABMS_{AB} regardless of how the interaction test turns out is the more conservative course.

10.3.6 — Follow-Up Tests and Confidence Intervals

Confidence intervals follow the same rule as the omnibus tests: whatever mean square served as the denominator of the test of an effect replaces MSWMS_W in the interval. For the two-level fixed factor that means MSABMS_{AB} and its 3 degrees of freedom.

HideShow
program_means <- tapply(chapter_10_table_5$ACT, chapter_10_table_5$Program, mean)
mean_diff <- program_means[["Computer"]] - program_means[["Paper-and-Pencil"]]
mean_diff
HideShow
[1] -6
HideShow
#> -6 = 21 - 27 — matches book p. 545

n_program <- as.vector(table(chapter_10_table_5$Program))   # 20 students each
f_crit    <- qf(0.95, df_program, df_interaction)
se_diff   <- sqrt(ms_interaction * sum(1 / n_program))
moe       <- sqrt(f_crit) * se_diff

c(lower = mean_diff - moe, upper = mean_diff + moe)
HideShow
      lower       upper 
-11.1969131  -0.8030869 
HideShow
#> -11.197, -0.803 — matches book p. 545, where rounding the critical value to
#> F(.05; 1, 3) = 10.1 rather than 10.128 gives -11.190 and -0.810

The interval excludes zero, consistent with the mixed-model test, but it is wide: the deficit from the computer-based program could be just over 11 points or less than a single point.

When a factor has more than two levels, simultaneous intervals are appropriate. The school effect was not significant, but the book illustrates a Tukey interval on the difference between Schools 2 and 3 using MSWMS_W, since MSWMS_W is the denominator for the random factor.

HideShow
school_means <- tapply(chapter_10_table_5$ACT, chapter_10_table_5$School, mean)
diff_23 <- school_means[["2"]] - school_means[["3"]]

n_school <- as.vector(table(chapter_10_table_5$School))     # 10 students each
q_crit   <- qtukey(0.95, nmeans = nlevels(chapter_10_table_5$School),
                   df = df_within)
q_crit
HideShow
[1] 3.831616
HideShow
#> 3.8316, which book p. 545 quotes as 3.832
moe_23   <- (q_crit / sqrt(2)) * sqrt(ms_within * (1 / n_school[2] + 1 / n_school[3]))

c(estimate = diff_23, lower = diff_23 - moe_23, upper = diff_23 + moe_23)
HideShow
 estimate     lower     upper 
 4.000000 -1.149569  9.149569 
HideShow
#> 4, with limits -1.150 and 9.150 — matches book p. 545

The mainstream route to the same interval is emmeans, which forms the estimated marginal means from the fitted model and applies the Tukey adjustment for the family of four school means.

HideShow
emm_school <- emmeans(model_act, specs = ~ School)
confint(contrast(emm_school, method = "pairwise", adjust = "tukey"),
        level = 0.95)
HideShow
 contrast          estimate  SE df lower.CL upper.CL
 School1 - School2       -1 1.9 32    -6.15     4.15
 School1 - School3        3 1.9 32    -2.15     8.15
 School1 - School4        2 1.9 32    -3.15     7.15
 School2 - School3        4 1.9 32    -1.15     9.15
 School2 - School4        3 1.9 32    -2.15     8.15
 School3 - School4       -1 1.9 32    -6.15     4.15

Results are averaged over the levels of: Program 
Confidence level used: 0.95 
Conf-level adjustment: tukey method for comparing a family of 4 estimates 
HideShow
#> School2 - School3: estimate 4, limits -1.150 and 9.150 — matches book p. 545

The School2 - School3 row reproduces the hand computation to three decimals, which is the useful thing to know: emmeans is doing the arithmetic of the preceding chunk, not something different, and it supplies the remaining five pairwise intervals at the same simultaneous confidence level.

10.3.7 — Measures of Association Strength

10.3.7.2 — Numerical Example

The sample measures are ratios of sums of squares, exactly as in earlier chapters: R2=SSeffect/SSTotalR^2 = SS_{effect}/SS_{Total} (Equation 10.13) and Rpartial2=SSeffect/(SSW+SSeffect)R^2_{partial} = SS_{effect}/(SS_W + SS_{effect}) (Equation 10.14).

HideShow
ss_total_act <- sum(res_act[, "Sum Sq"])
ss_total_act
HideShow
[1] 1118
HideShow
#> 360 + 100 + 80 + 578 = 1118 — matches book p. 548

ss_effects <- setNames(res_act[1:3, "Sum Sq"], c("A", "B", "AB"))
round(ss_effects / ss_total_act, 3)
HideShow
    A     B    AB 
0.322 0.089 0.072 
HideShow
#> R^2 = .322, .089, .072 — matches Table 10.6, book p. 548
round(ss_effects / (ss_effects + ss_within_act), 3)
HideShow
    A     B    AB 
0.384 0.147 0.122 
HideShow
#> R^2_partial = .384, .147, .122 — matches Table 10.6, book p. 548

The population estimates need variance components, which Equation 10.21 recovers from the mean squares. Because the program factor is fixed, its component is a sum of squared effect parameters, ∑α̂j2/a\sum\hat\alpha_j^2/a, rather than a variance.

HideShow
a <- nlevels(chapter_10_table_5$Program)   # 2 programs
b <- nlevels(chapter_10_table_5$School)    # 4 schools
n <- 5                                     # 5 students per cell

# Equation 10.21.
theta_program <- ((a - 1) / (a * b * n)) * (ms_program - ms_interaction)
var_school    <- (ms_school - ms_within) / (a * n)
var_interact  <- (ms_interaction - ms_within) / n
var_error     <- ms_within

round(c(sum_alpha_sq_over_a = theta_program, sigma2_beta = var_school,
        sigma2_alphabeta = var_interact, sigma2_epsilon = var_error), 4)
HideShow
sum_alpha_sq_over_a         sigma2_beta    sigma2_alphabeta      sigma2_epsilon 
             8.3333              1.5271              1.7208             18.0625 
HideShow
#> 8.333, 1.527, 1.721, and 18.0625 (which the book prints as 18.063) —
#> matches book p. 548

Equation 10.20 then gives the overall measures and Equation 10.22 the partial ones. The fixed factor’s measure is written ω̂2\widehat\omega^2; the random factors’ are intraclass correlations ρ̂I\widehat\rho_I.

HideShow
total_pop_var <- theta_program + var_school + var_interact + var_error
total_pop_var
HideShow
[1] 29.64375
HideShow
#> 29.644 — matches book p. 548

omega_sq_A <- theta_program / total_pop_var
rho_I_B    <- var_school    / total_pop_var
rho_I_AB   <- var_interact  / total_pop_var

# Equation 10.22: each component relative to itself plus error alone.
omega_sq_A_partial <- theta_program / (theta_program + var_error)
rho_I_B_partial    <- var_school    / (var_school    + var_error)
rho_I_AB_partial   <- var_interact  / (var_interact  + var_error)

round(c(omega_sq_A = omega_sq_A, rho_I_B = rho_I_B, rho_I_AB = rho_I_AB), 3)
HideShow
omega_sq_A    rho_I_B   rho_I_AB 
     0.281      0.052      0.058 
HideShow
#> .281, .052, .058 — matches book p. 548
round(c(omega_sq_A_partial = omega_sq_A_partial,
        rho_I_B_partial = rho_I_B_partial,
        rho_I_AB_partial = rho_I_AB_partial), 3)
HideShow
omega_sq_A_partial    rho_I_B_partial   rho_I_AB_partial 
             0.316              0.078              0.087 
HideShow
#> .316, .078, .087 — matches Table 10.6, book p. 548

All twelve entries of Table 10.6 in one table.

HideShow
data.frame(
  Effect     = c("A (Program, fixed)", "B (School, random)", "AB"),
  R2         = ss_effects / ss_total_act,
  R2_partial = ss_effects / (ss_effects + ss_within_act),
  Overall    = c(omega_sq_A, rho_I_B, rho_I_AB),
  Partial    = c(omega_sq_A_partial, rho_I_B_partial, rho_I_AB_partial),
  row.names  = NULL
) |>
  gt() |>
  fmt_number(columns = c(R2, R2_partial, Overall, Partial), decimals = 3) |>
  cols_label(R2 = md("*R*<sup>2</sup>"),
             R2_partial = md("*R*<sup>2</sup><sub>partial</sub>"),
             Overall = "Overall", Partial = "Partial") |>
  tab_spanner(label = "Sample values", columns = c(R2, R2_partial)) |>
  tab_spanner(label = "Population estimates", columns = c(Overall, Partial)) |>
  tab_header(title = md(paste("**Table 10.6**. Estimates of Association Strength",
                              "Measures for ACT Training Program Example"))) |>
  cols_align(align = "center", columns = -Effect)
Table 10.6. Estimates of Association Strength Measures for ACT Training Program Example
Effect
Sample values
Population estimates
R2 R2partial Overall Partial
A (Program, fixed) 0.322 0.384 0.281 0.316
B (School, random) 0.089 0.147 0.052 0.078
AB 0.072 0.122 0.058 0.087
HideShow
#> every entry matches Table 10.6, book p. 548

The overall ω̂2=.281\widehat\omega^2 = .281 counts school-to-school variability and the program-by-school interaction as part of the variance the program has to explain. The partial ω̂partial2=.316\widehat\omega^2_{partial} = .316 treats the school factor as extrinsic — appropriate if the question concerns students within one particular school, or a population for whom the school effect is not relevant — and so divides only by the program component plus within-cell error.

The same variance components from a fitted mixed model

The components above came from the method of moments: set each observed mean square equal to its expectation and solve. A random-effects model estimates them directly by restricted maximum likelihood, and VarCorr() reports them. The comparison is instructive precisely because the two routes do not agree everywhere.

HideShow
fit_mixed <- lmer(ACT ~ Program + (1 | School) + (1 | Program:School),
                  data = chapter_10_table_5)
print(VarCorr(fit_mixed), comp = "Variance")
HideShow
 Groups         Name        Variance
 Program:School (Intercept)  1.72082
 School         (Intercept)  0.66668
 Residual                   18.06250

The interaction component, 1.721, and the residual, 18.063, reproduce the moment-method values exactly. The school component does not: REML returns 0.667 where Equation 10.21 gives 1.527. The difference is not an error in either computation but a difference in the model being fitted. Table 10.3 gives the mixed-design expectation of MSBMS_B as σε2+anσβ2\sigma^2_\varepsilon + an\sigma^2_\beta, which is what Equation 10.21 inverts. Fitting (1 | School) and (1 | Program:School) as two separate random terms implies instead that MSBMS_B also carries an interaction component, σε2+nσαβ2+anσβ2\sigma^2_\varepsilon + n\sigma^2_{\alpha\beta} + an\sigma^2_\beta, and subtracting that extra term accounts for the whole discrepancy:

HideShow
(ms_school - ms_within - n * var_interact) / (a * n)
HideShow
[1] 0.6666667
HideShow
#> 0.667 — the REML estimate of the School variance, recovered by hand

So the two answers differ by nσ̂αβ2/(an)=1.721/2=0.861n\widehat\sigma^2_{\alpha\beta}/(an) = 1.721/2 = 0.861, and the choice between them is the choice between the restricted and unrestricted formulations of the mixed model. The book’s Equation 10.21 and the intraclass correlations above use the restricted form, and those are the values Table 10.6 reports.

10.3.8 — Using Statistical Computer Programs to Analyze Designs with Random Factors

The chapter shows how SPSS and SAS are told which error term to use for which effect: VS on a MANOVA DESIGN statement, a /TEST method vs method*school line added to UNIANOVA syntax, or test H = method E = method*school; in SAS’s PROC GLM. R’s counterpart in base R is the Error() term inside aov(), which splits the analysis into error strata and tests each effect within its own stratum.

HideShow
mixed_model_auto <- aov(ACT ~ Program + Error(School / Program),
                        data = chapter_10_table_5)
summary(mixed_model_auto)
HideShow

Error: School
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  3    100   33.33               

Error: School:Program
          Df Sum Sq Mean Sq F value Pr(>F)  
Program    1    360   360.0    13.5 0.0349 *
Residuals  3     80    26.7                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: Within
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals 32    578   18.06               
HideShow
#> Program: F = 13.5, p = .0349 in the School:Program stratum — matches book
#> p. 542; the strata carry MS_B = 33.33, MS_AB = 26.7, MS_W = 18.06 of
#> Table 10.5, book p. 543

The Error: School:Program stratum holds the test of the fixed factor, with the interaction mean square as its residual, so the reported FF and pp are the mixed-model values rather than the naive ones. The Error: Within stratum holds the within-cell variance.

The contemporary route is a linear mixed-effects model. lmer() estimates the variance components by REML, which does not require the balance that the method of moments assumes, and lmerTest supplies the FF test for the fixed effect with Satterthwaite degrees of freedom. The term (1 | School) makes the baseline ACT score vary randomly across schools, and (1 | Program:School) lets the program’s effect vary by school.

HideShow
lmm_model <- lmer(ACT ~ Program + (1 | School) + (1 | Program:School),
                  data = chapter_10_table_5)
anova(lmm_model)
HideShow
Type III Analysis of Variance Table with Satterthwaite's method
        Sum Sq Mean Sq NumDF DenDF F value Pr(>F)  
Program 243.84  243.84     1     3    13.5 0.0349 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 13.5 on (1, 3) df, p = .0349 — matches book p. 542

The Satterthwaite denominator degrees of freedom come out at exactly 3 here because the design is balanced; with unequal cell sizes or missing observations the same approximation returns a non-integer value, which is where it earns its keep. Note that lmer() reports a SumSqSum\ Sq for the fixed effect that is not the book’s SSA=360SS_A = 360: the likelihood- based fit works on a different scale, and it is the FF ratio and its degrees of freedom that are comparable to Table 10.5.

sjPlot::tab_model() collects the fitted model in one place: the fixed-effect estimate for program, the random-effect variances, the intraclass correlation, and the sample sizes. These random-effect variances are the REML ones, so the school variance is the 0.667 discussed above rather than the 1.527 of Table 10.6, and the reported ICC is computed from the REML partition rather than from Equation 10.20.

HideShow
tab_model(lmm_model,
          show.icc    = TRUE,    # intraclass correlation(s)
          show.re.var = TRUE,    # random-effect variances
          dv.labels   = "ACT score")
  ACT score
Predictors Estimates CI p
(Intercept) 21.00 18.51 – 23.49 <0.001
Program
[Paper-and-Pencil]
6.00 2.68 – 9.32 0.001
Random Effects
σ2 18.06
τ00 Program:School 1.72
τ00 School 0.67
ICC 0.12
N School 4
N Program 2
Observations 40
Marginal R2 / Conditional R2 0.311 / 0.391

To make the generalizability penalty concrete, the mixed model can be placed side by side with the fixed-effects OLS fit that ignores the random schools. With modelsummary, each model is a column and the fit statistics sit at the foot.

HideShow
fit_ols_act <- lm(ACT ~ Program, data = chapter_10_table_5)

modelsummary(
  list("Fixed-effects (OLS)" = fit_ols_act, "Mixed (random School)" = lmm_model),
  estimate  = "{estimate}",
  statistic = "({std.error})",   # standard errors in parentheses, APA style
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  output    = "gt"
)
Fixed-effects (OLS) Mixed (random School)
(Intercept) 21.000 21.000
(0.999) (1.225)
ProgramPaper-and-Pencil 6.000 6.000
(1.412) (1.633)
SD (Intercept ProgramSchool) 1.312
SD (Intercept School) 0.817
SD (Observations) 4.250
Num.Obs. 40 40
AIC 237.2 236.8
BIC 242.3 245.2
Log.Lik. -115.594

The same two fits as a gtsummary table, each under its own spanning header. The program coefficient is identical in the two models, because the design is balanced; what differs is the standard error and the reference distribution the fixed effect is judged against.

HideShow
t_ols <- tbl_regression(fit_ols_act, intercept = TRUE)
t_mix <- tbl_regression(lmm_model,   intercept = TRUE)
tbl_merge(list(t_ols, t_mix),
          tab_spanner = c("**Fixed-effects (OLS)**", "**Mixed (random School)**"))
Characteristic
Fixed-effects (OLS)
Mixed (random School)
Beta 95% CI p-value Beta 95% CI p-value
(Intercept) 21 19, 23 <0.001 21 18, 24 <0.001
Program





    Computer — —
— —
    Paper-and-Pencil 6.0 3.1, 8.9 <0.001 6.0 0.80, 11 0.035
Abbreviation: CI = Confidence Interval

10.3.9 — Determining Power in Designs with Random Factors

Power for a random effect is based on a central FF distribution rather than a noncentral one, which is why software written for fixed-effects power analysis does not apply. Under the alternative, the test statistic is distributed as a multiple of a central FF, and the multiplier is the ratio of expected mean squares (Equation 10.23). For a one-way random-effects design that ratio is 1+nfrand21 + nf^2_{rand} (Equation 10.24), with frand=σα/σεf_{rand} = \sigma_\alpha/\sigma_\varepsilon, so Equation 10.25 gives

power=Pr⁡[F≥Fcrit1+nfrand2].\text{power} = \Pr\left[F \geq \frac{F_{crit}}{1 + n f^2_{rand}}\right].

The book computes this with SPSS syntax over a table of scenarios: three levels of a random factor, α=.05\alpha = .05, frand=.40f_{rand} = .40, and nn running from 20 to 80. The same table in R is three vectorized lines.

HideShow
power_random <- function(a, n, f_rand, alpha = 0.05) {
  ems_ratio <- 1 + n * f_rand^2
  f_crit    <- qf(1 - alpha, a - 1, a * n - a)
  power     <- 1 - pf(f_crit / ems_ratio, a - 1, a * n - a)
  data.frame(a = a, n = n, f_rand = f_rand, alpha = alpha,
             EMSratio = round(ems_ratio, 2),
             F_crit = round(f_crit, 2),
             power = round(power, 2))
}

power_random(a = 3, n = c(20, 40, 60, 80), f_rand = 0.40)
HideShow
  a  n f_rand alpha EMSratio F_crit power
1 3 20    0.4  0.05      4.2   3.16  0.48
2 3 40    0.4  0.05      7.4   3.07  0.66
3 3 60    0.4  0.05     10.6   3.05  0.75
4 3 80    0.4  0.05     13.8   3.03  0.80
HideShow
#> EMSratio 4.20, 7.40, 10.60, 13.80; F_crit 3.16, 3.07, 3.05, 3.03;
#> power .48, .66, .75, .80 — matches book p. 551

Reaching power of .80 takes 240 subjects in total even though frand=.40f_{rand} = .40 is a large effect, for the two reasons the text gives: with only three levels sampled, the variance among the selected population means is usually smaller than the population variance, and power depends on how many levels of the random factor are used and not only on the total NN. Redistributing the same 240 subjects over more levels shows the second point directly.

HideShow
power_random(a = c(3, 8), n = c(80, 30), f_rand = 0.40)
HideShow
  a  n f_rand alpha EMSratio F_crit power
1 3 80    0.4  0.05     13.8   3.03  0.80
2 8 30    0.4  0.05      5.8   2.05  0.93
HideShow
#> 3 groups of 80 gives power .80; 8 groups of 30 gives .93 — matches book p. 551

# And the same power of .80 from far fewer subjects, by using 7 groups of 20.
power_random(a = 7, n = 20, f_rand = 0.40)
HideShow
  a  n f_rand alpha EMSratio F_crit power
1 7 20    0.4  0.05      4.2   2.17   0.8
HideShow
#> power .80 with 140 subjects in total — matches book p. 551

The effect size itself can be estimated from pilot data. Equation 10.26 estimates frand2f^2_{rand} as (MSA−MSW)/(n⋅MSW)(MS_A – MS_W)/(n \cdot MS_W). The book’s illustration is a three-group pilot study with means of 40, 45, and 50, 20 subjects per group, and MSW=100MS_W = 100.

HideShow
pilot_means <- c(40, 45, 50)
n_pilot     <- 20
ms_w_pilot  <- 100

# MS_A = sum(n * alpha_hat^2) / (a - 1), with alpha_hat the deviations from the
# grand mean.
alpha_hat  <- pilot_means - mean(pilot_means)
ms_a_pilot <- sum(n_pilot * alpha_hat^2) / (length(pilot_means) - 1)
ms_a_pilot
HideShow
[1] 500
HideShow
#> MS_A = 20(25 + 0 + 25) / 2 = 500 — matches book p. 551

f2_rand <- (ms_a_pilot - ms_w_pilot) / (n_pilot * ms_w_pilot)
c(f2_rand = f2_rand, f_rand = sqrt(f2_rand))
HideShow
  f2_rand    f_rand 
0.2000000 0.4472136 
HideShow
#> f^2_rand = 400 / 2000 = .2, so f_rand = .4472 — matches book p. 551

# How many per group a three-group study would then need for power of .80.
power_random(a = 3, n = 64, f_rand = sqrt(f2_rand))
HideShow
  a  n    f_rand alpha EMSratio F_crit power
1 3 64 0.4472136  0.05     13.8   3.04   0.8
HideShow
#> power .80 at 64 subjects per group — matches book p. 551
Planning the number of levels in DMAR

The computations above answer a power question: given a number of levels and a number of observations per level, how often will the test reject? A planning question the chapter’s emphasis on the intraclass correlation raises but does not take up is the precision question: how many levels are needed to estimate ρI\rho_I itself to a stated confidence- interval width? DMAR’s accuracy-in-parameter-estimation planner inverts the asymptotic variance of the ICC to answer it. This is a companion addition, not a reproduction of a printed value.

HideShow
ss_aipe_icc(true_icc = 0.5, n_raters = 5, width = 0.20,
            conf_level = 0.95, type = "ICC(1,1)")
term value
necessary_N 88
expected_width 0.199
true_icc 0.500
n_raters 5
width 0.200
conf_level 0.950

Confidence level: 95%

The necessary_N row is the number of levels of the random factor — schools, trainees, clusters — needed so that with 5 observations per level and an anticipated ICC of .5 the 95% confidence interval for the ICC is no wider than .20, and expected_width reports the width that number actually delivers. The lesson is the same one the power table teaches: with random factors it is the number of levels sampled, not the number of observations inside each one, that governs the quality of the inference.

10.4 — Designs with Nested Factors

10.4.3 — Models and Tests

The clinic director tests for a difference across genders in the severity ratings that graduate students assign to clients. Three male and three female clinical students are sampled, and each is assigned four clients for an intake interview. Gender is the fixed factor AA; trainee is the random factor BB, nested within gender, because a given trainee is either male or female and cannot be crossed with gender. The structural model is Equation 10.32:

Yijk=μ+αj+βk/j+εijkY_{ijk} = \mu + \alpha_j + \beta_{k/j} + \varepsilon_{ijk}

where αj\alpha_j is the fixed effect of the jjth gender, βk/j\beta_{k/j} the simple effect of the kkth trainee within that gender, and εijk\varepsilon_{ijk} the within-cell error. No interaction term exists, so SSB/ASS_{B/A} is the pooled sum of squares from one-way analyses within each gender. The data are Table 10.9.

HideShow
data(chapter_10_table_9)
str(chapter_10_table_9)
HideShow
'data.frame':   24 obs. of  3 variables:
 $ Gender  : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Trainee : int  1 1 1 1 2 2 2 2 3 3 ...
 $ Severity: int  49 40 31 40 42 48 52 58 42 46 ...
HideShow
chapter_10_table_9$Gender  <- factor(chapter_10_table_9$Gender)
chapter_10_table_9$Trainee <- factor(chapter_10_table_9$Trainee)

# Cell means, gender marginal means, and the grand mean of Table 10.9, part I.
tapply(chapter_10_table_9$Severity,
       list(chapter_10_table_9$Gender, chapter_10_table_9$Trainee), mean)
HideShow
   1  2  3
1 40 50 48
2 61 54 65
HideShow
#> 40, 50, 48 for the male trainees and 61, 54, 65 for the female trainees —
#> matches Table 10.9, book p. 559
tapply(chapter_10_table_9$Severity, chapter_10_table_9$Gender, mean)
HideShow
 1  2 
46 60 
HideShow
#> 46 and 60 — matches book p. 559
mean(chapter_10_table_9$Severity)
HideShow
[1] 53
HideShow
#> 53 — matches book p. 559

In base R the nesting is written into the error structure. Error(Gender/Trainee) tells aov() that trainee is nested within gender, which puts the gender effect in the Gender:Trainee stratum and so tests it against MSB/AMS_{B/A} rather than MSWMS_W.

HideShow
nested_aov <- aov(Severity ~ Gender + Error(Gender / Trainee),
                  data = chapter_10_table_9)
summary(nested_aov)
HideShow

Error: Gender
       Df Sum Sq Mean Sq
Gender  1   1176    1176

Error: Gender:Trainee
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  4    472     118               

Error: Within
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals 18    820   45.56               
HideShow
#> SS_A = 1176, SS_B/A = 472, SS_W = 820 with MS 1176, 118, 45.556 — matches
#> Table 10.9, parts II to IV, book p. 559

aov_summary <- summary(nested_aov)
MS_A  <- aov_summary[["Error: Gender"]][[1]]["Gender", "Mean Sq"]
MS_BA <- aov_summary[["Error: Gender:Trainee"]][[1]]["Residuals", "Mean Sq"]
MS_W  <- aov_summary[["Error: Within"]][[1]]["Residuals", "Mean Sq"]
df_BA <- aov_summary[["Error: Gender:Trainee"]][[1]]["Residuals", "Df"]
df_W  <- aov_summary[["Error: Within"]][[1]]["Residuals", "Df"]

aov() leaves the FF column blank for gender, because the test spans two strata. The two ratios are a line of arithmetic each.

HideShow
f_gender <- MS_A / MS_BA
p_gender <- pf(f_gender, 1, df_BA, lower.tail = FALSE)
c(F = f_gender, p = p_gender)
HideShow
         F          p 
9.96610169 0.03428551 
HideShow
#> F = 1176 / 118 = 9.966 on (1, 4) df, p = .034 — matches Table 10.9, book
#> p. 559

f_trainee <- MS_BA / MS_W
p_trainee <- pf(f_trainee, df_BA, df_W, lower.tail = FALSE)
c(F = f_trainee, p = p_trainee)
HideShow
         F          p 
2.59024390 0.07164886 
HideShow
#> F = 118 / 45.556 = 2.590 on (4, 18) df, p = .072 — matches Table 10.9, book
#> p. 559

The book notes that the test of the nonnested factor is equivalent to a one-way ANOVA carried out on the cluster means themselves. That claim is worth checking, because it explains where the 4 denominator degrees of freedom come from.

HideShow
cluster_means <- aggregate(Severity ~ Gender + Trainee,
                           data = chapter_10_table_9, FUN = mean)
cluster_means
HideShow
  Gender Trainee Severity
1      1       1       40
2      2       1       61
3      1       2       50
4      2       2       54
5      1       3       48
6      2       3       65
HideShow
summary(aov(Severity ~ Gender, data = cluster_means))
HideShow
            Df Sum Sq Mean Sq F value Pr(>F)  
Gender       1    294   294.0   9.966 0.0343 *
Residuals    4    118    29.5                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 294 / 29.5 = 9.966 on (1, 4) df — the same F as the full hierarchical
#> analysis, as stated on book p. 562

Six numbers, one per trainee, and the resulting FF is the FF of Table 10.9. The 24 client ratings contribute to the precision of each cluster mean but not to the degrees of freedom of the gender test, which is why adding clients per trainee cannot buy power for the fixed effect and adding trainees can.

The modern equivalent is a mixed-effects model with the nested factor as a random intercept. (1 | Gender:Trainee) forms one grouping level per trainee-within-gender, and lmerTest supplies the FF test.

HideShow
nested_lmm <- lmer(Severity ~ Gender + (1 | Gender:Trainee),
                   data = chapter_10_table_9)
anova(nested_lmm)
HideShow
Type III Analysis of Variance Table with Satterthwaite'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 = 9.966 on (1, 4) df, p = .034 — matches Table 10.9, book p. 559

The nested source table of Table 10.9, in APA style. Gender is tested against MSB/AMS_{B/A}, the nested trainee effect against MSWMS_W; partial η2\eta^2 is each effect’s share of effect-plus-within variance.

HideShow
ss_a_nest  <- aov_summary[["Error: Gender"]][[1]]["Gender", "Sum Sq"]
ss_ba_nest <- aov_summary[["Error: Gender:Trainee"]][[1]]["Residuals", "Sum Sq"]
ss_w_nest  <- aov_summary[["Error: Within"]][[1]]["Residuals", "Sum Sq"]

nested_source <- data.frame(
  Source = c("A (Gender)", "B/A (Trainee within Gender)", "Within"),
  SS     = c(ss_a_nest, ss_ba_nest, ss_w_nest),
  df     = c(1, df_BA, df_W),
  MS     = c(MS_A, MS_BA, MS_W),
  Fstat  = c(f_gender, f_trainee, NA_real_),
  p      = c(p_gender, p_trainee, NA_real_),
  Denom  = c("B/A", "Within", ""),
  row.names = NULL
)
nested_source$peta <- ifelse(nested_source$Source == "Within", NA_real_,
                             nested_source$SS / (nested_source$SS + ss_w_nest))

nested_source |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 3) |>
  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(paste("**Table 10.9**. Analysis of Variance for",
                              "General Severity Ratings (Nested Design)"))) |>
  cols_align(align = "center", columns = -Source)
Table 10.9. Analysis of Variance for General Severity Ratings (Nested Design)
Source SS df MS F p Denom Partial η2
A (Gender) 1,176.000 1 1,176.000 9.966 0.0343 B/A 0.589
B/A (Trainee within Gender) 472.000 4 118.000 2.590 0.0716 Within 0.365
Within 820.000 18 45.556


HideShow
#> F = 9.966 with p = .034 and F = 2.590 with p = .072 — matches Table 10.9,
#> part IV, book p. 559

sjPlot::tab_model() summarizes the same model, with the trainee random-effect variance and the intraclass correlation reported beside the gender fixed effect.

HideShow
tab_model(nested_lmm,
          show.icc    = TRUE,
          show.re.var = TRUE,
          dv.labels   = "Severity")
  Severity
Predictors Estimates CI p
(Intercept) 46.00 39.46 – 52.54 <0.001
Gender [2] 14.00 4.75 – 23.25 0.005
Random Effects
σ2 45.56
τ00 Gender:Trainee 18.11
ICC 0.28
N Gender 2
N Trainee 3
Observations 24
Marginal R2 / Conditional R2 0.445 / 0.603

10.4.4 — Degrees of Freedom

The nonnested factor keeps its usual a−1a – 1 degrees of freedom. The nested factor pools the simple effects: b−1b – 1 within each of the aa levels of AA, for a(b−1)a(b – 1) in total. The precaution the book flags is that bb is the number of levels per nest, not the total number of distinct levels of BB in the design.

HideShow
a_nest <- nlevels(chapter_10_table_9$Gender)    # 2 genders
b_nest <- 3   # 3 trainees per gender, not the 6 distinct trainees in the study
n_nest <- 4   # 4 clients per trainee

c(df_A = a_nest - 1,
  df_BA = a_nest * (b_nest - 1),
  df_W  = a_nest * b_nest * (n_nest - 1))
HideShow
 df_A df_BA  df_W 
    1     4    18 
HideShow
#> 1, 4, 18 — matches Table 10.9, book p. 559, and the rule on book p. 563

10.4.6 — Follow-Up Tests and Confidence Intervals

The rule from Section 10.3.6 carries over unchanged: the mean square that served as the denominator of an effect’s omnibus test is the one that appears in intervals for that effect. For gender that is MSB/A=118MS_{B/A} = 118 on 4 degrees of freedom (Equation 10.43).

HideShow
gender_means <- tapply(chapter_10_table_9$Severity,
                       chapter_10_table_9$Gender, mean)
mean_diff_gender <- gender_means[["1"]] - gender_means[["2"]]
mean_diff_gender
HideShow
[1] -14
HideShow
#> -14 = 46 - 60 — matches book p. 565

n_gender <- sum(chapter_10_table_9$Gender == 1)   # 12 clients per gender
ME_gender <- sqrt(qf(0.95, 1, df_BA)) *
  sqrt(MS_BA * (1 / n_gender + 1 / n_gender))

c(lower = mean_diff_gender - ME_gender, upper = mean_diff_gender + ME_gender)
HideShow
     lower      upper 
-26.312733  -1.687267 
HideShow
#> -26.313, -1.687 — matches book p. 565, where rounding F(.05; 1, 4) to 7.71
#> gives -26.314 and -1.686

Comparing two trainees is a test of the nested factor, so it drops back down the hierarchy to MSW=45.556MS_W = 45.556 on 18 degrees of freedom. The book defines the family as the three pairwise comparisons among male trainees plus the three among female trainees, which makes Bonferroni preferable to Tukey, and reads the critical value for 6 comparisons on 18 degrees of freedom from Appendix Table A.3.

HideShow
# Table 10.9 labels the female trainees 4, 5, and 6; within gender 2 they are
# coded k = 1, 2, 3, so female Trainee 5 is Trainee 2 and Trainee 6 is Trainee 3.
sev <- chapter_10_table_9
mean_T5 <- mean(sev$Severity[sev$Gender == 2 & sev$Trainee == 2])
mean_T6 <- mean(sev$Severity[sev$Gender == 2 & sev$Trainee == 3])
c(Trainee_5 = mean_T5, Trainee_6 = mean_T6)
HideShow
Trainee_5 Trainee_6 
       54        65 
HideShow
#> 54 and 65 — matches Table 10.9, book p. 559

alpha_bonf  <- 0.05 / 6
F_crit_bonf <- qf(1 - alpha_bonf, df1 = 1, df2 = df_W)
F_crit_bonf
HideShow
[1] 8.777796
HideShow
#> 8.78 — matches the Appendix Table A.3 value used on book p. 565

n_trainee  <- sum(sev$Gender == 2 & sev$Trainee == 2)   # 4 clients per trainee
ME_trainee <- sqrt(F_crit_bonf) * sqrt(MS_W * (1 / n_trainee + 1 / n_trainee))

c(estimate = mean_T5 - mean_T6,
  lower = (mean_T5 - mean_T6) - ME_trainee,
  upper = (mean_T5 - mean_T6) + ME_trainee)
HideShow
  estimate      lower      upper 
-11.000000 -25.139968   3.139968 
HideShow
#> -11 with a half-width of 14.140 — matches book p. 565; the interval contains
#> zero, so these two trainees do not differ significantly

10.4.7 — Standardized Effect Size Estimates

A nested design offers more than one standard deviation to standardize against, so the choice has to be made explicitly. Table 10.10 gives the variance components for the design at hand (factor AA fixed, factor BB random and nested), and the estimates follow from the mean squares.

HideShow
var_error_nest   <- MS_W                                         # sigma^2_epsilon
var_trainee_nest <- (MS_BA - MS_W) / n_nest                      # sigma^2_beta
var_gender_nest  <- ((a_nest - 1) / a_nest) *
  ((MS_A - MS_BA) / (b_nest * n_nest))                           # sum(alpha^2)/a

round(c(sigma2_epsilon = var_error_nest, sigma2_beta = var_trainee_nest,
        sum_alpha_sq_over_a = var_gender_nest), 3)
HideShow
     sigma2_epsilon         sigma2_beta sum_alpha_sq_over_a 
             45.556              18.111              44.083 
HideShow
#> 45.556, 18.111, 44.083 — matches book p. 567; sigma^2_beta = 18.111 is also
#> quoted on book p. 566

Standardizing by the between-cluster standard deviation gives dBd_B (Equation 10.44), by the within-cluster standard deviation dWd_W (Equation 10.45), and by both sources together dTd_T (Equation 10.46). The last is usually the one to report, because it anticipates a population in which both clients and therapists vary.

HideShow
d_B <- mean_diff_gender / sqrt(var_trainee_nest)
d_W <- mean_diff_gender / sqrt(var_error_nest)
d_T <- mean_diff_gender / sqrt(var_trainee_nest + var_error_nest)

round(c(d_B = d_B, d_W = d_W, d_T = d_T), 3)
HideShow
   d_B    d_W    d_T 
-3.290 -2.074 -1.755 
HideShow
#> -3.290, -2.074, -1.755 — matches book p. 566

# The standardizers themselves, for comparison with the book's arithmetic.
round(c(sigma_beta = sqrt(var_trainee_nest),
        sigma_epsilon = sqrt(var_error_nest),
        sigma_total = sqrt(var_trainee_nest + var_error_nest)), 3)
HideShow
   sigma_beta sigma_epsilon   sigma_total 
        4.256         6.749         7.979 
HideShow
#> 4.256, 6.749, 7.979 with a total variance of 63.667 — matches book p. 566

dBd_B and dWd_W are both larger in magnitude than dTd_T, and both would overstate the effect expected in a population of varying clients and varying therapists.

10.4.8 — Strength of Association in Nested Designs

The sample proportions come first. Two partial measures are defensible here, depending on whether the comparison variability is that among client ratings or that among trainees.

HideShow
ss_total_nest <- ss_a_nest + ss_ba_nest + ss_w_nest
ss_total_nest
HideShow
[1] 2468
HideShow
#> 1176 + 472 + 820 = 2468 — matches book p. 566

round(c(R2 = ss_a_nest / ss_total_nest,
        R2_partial_within = ss_a_nest / (ss_a_nest + ss_w_nest),
        R2_partial_nested = ss_a_nest / (ss_a_nest + ss_ba_nest)), 3)
HideShow
               R2 R2_partial_within R2_partial_nested 
            0.476             0.589             0.714 
HideShow
#> .476 and .589 — matches book p. 566; .714 — matches book p. 567, which is
#> the quantity SPSS labels partial eta squared for this design

The population estimates use the variance components of Section 10.4.7.

HideShow
omega_sq_overall <- var_gender_nest /
  (var_gender_nest + var_trainee_nest + var_error_nest)
omega_sq_partial <- var_gender_nest / (var_gender_nest + var_error_nest)
icc_trainee      <- var_trainee_nest / (var_trainee_nest + var_error_nest)

round(c(omega_sq_overall = omega_sq_overall,
        omega_sq_partial = omega_sq_partial,
        icc_trainee = icc_trainee), 3)
HideShow
omega_sq_overall omega_sq_partial      icc_trainee 
           0.409            0.492            0.284 
HideShow
#> omega^2 = 44.083 / 107.750 = .409 and omega^2_partial = 44.083 / 89.639
#> = .492 — matches book p. 567
#> ICC = 18.111 / (18.111 + 45.556) = .284 — matches book p. 567

An ICC of .284 says that some 28% of the variance in client severity ratings that remains after gender is accounted for belongs to the trainee doing the interviewing rather than to the client being rated. The book cites Wampold and Serlin (2000) on what ignoring a nested random factor of roughly this size costs: a threefold or greater inflation of the Type I error rate, and estimates of ω̂2\widehat\omega^2 for the nonnested factor twice as large as they should be.

The same ICC and its interval in DMAR

The ICC above was assembled from mean squares by hand. icc_lmer() reads the same quantity off a fitted mixed model, and what it adds is the interval: the point estimate alone says nothing about how well six trainees pin down a population ICC.

HideShow
icc_lmer(nested_lmm, 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 and sigma2_within = 45.556 —
#> matches book p. 567

The icc row reproduces .284 and the sigma2_between and sigma2_within rows reproduce 18.111 and 45.556, so the REML and method-of-moments partitions coincide exactly for this balanced design. The ci_lower and ci_upper rows are the addition: the interval runs essentially from zero to .75, which is the honest summary of what six clusters support.

DMAR also supplies the analytic route to the same interval. The Burdick and Graybill modified-large-sample intervals are built from the method-of-moments mean squares rather than from a likelihood, so they can be computed from the published source table alone, without the raw data. These are companion additions; the book develops the variance components but not intervals around them.

HideShow
variance_components_mls(
  ms_between  = MS_BA,
  ms_within   = MS_W,
  df_between  = df_BA,
  df_within   = df_W,
  n_per_group = n_nest,
  conf_level  = 0.95
)
term value
sigma2_between 18.111
sigma2_between_ci_lower 0.000
sigma2_between_ci_upper 231.470
sigma2_within 45.556
sigma2_within_ci_lower 26.010
sigma2_within_ci_upper 99.626
icc 0.284
icc_ci_lower 0.000
icc_ci_upper 0.899

Confidence level: 95%

HideShow
#> sigma2_between = 18.111, sigma2_within = 45.556, icc = 0.284 — matches
#> book p. 567, now each with a confidence interval

The point estimates agree with the hand computation and with icc_lmer(), which is the check worth making; the _ci_lower and _ci_upper rows are what the call buys. The asymptotic sampling variance of the ICC estimate is available on its own, and it is the quantity the precision planner of Section 10.3.9 inverts.

HideShow
var_icc(icc = icc_trainee, N = 6, n_raters = n_nest, type = "ICC(1,1)")
term value
var_icc 0.049

With N=6N = 6 clusters of 4 observations each, the sampling variance of the ICC estimate is about .049, so a standard error near .22 — the same message the wide interval above delivers, in a different currency.

10.4.9 — Using Statistical Computer Programs to Analyze Nested Designs

As the chapter observes, the initial description of a nested design looks much like that of a crossed one in most programs: MANOVA Y BY THERAPY (1,2), TRAINEE (1,3) is the same line either way, and the nesting shows up only in which effects are requested and against what they are tested. SAS’s PROC GLM writes the nesting into the model as model y = a b(a); and then needs test H = a E = b(a); to get the right denominator.

R has the same trap. Listing both factors with * on nested data runs a crossed two-way analysis, and everything gets tested against MSWMS_W.

HideShow
wrong_aov <- aov(Severity ~ Gender * Trainee, data = chapter_10_table_9)
summary(wrong_aov)
HideShow
               Df Sum Sq Mean Sq F value  Pr(>F)    
Gender          1   1176  1176.0  25.815 7.8e-05 ***
Trainee         2    156    78.0   1.712  0.2086    
Gender:Trainee  2    316   158.0   3.468  0.0532 .  
Residuals      18    820    45.6                    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The gender effect is unchanged at SSA=1176SS_A = 1176, but dividing it by MSW=45.556MS_W = 45.556 rather than MSB/A=118MS_{B/A} = 118 sends FF from 9.966 to 25.815 and pp from .034 to below .0001. Worse, the Trainee and Gender:Trainee rows of that table are not interpretable at all: trainee 2 is a different person in each gender, so there is no trainee main effect to speak of and no interaction to estimate. The crossed analysis has silently split SSB/A=472SS_{B/A} = 472 into a fictitious 156 and 316.

HideShow
wrong_tab <- as.data.frame(summary(wrong_aov)[[1]])
c(fictitious_main = wrong_tab[2, "Sum Sq"],
  fictitious_interaction = wrong_tab[3, "Sum Sq"],
  total = wrong_tab[2, "Sum Sq"] + wrong_tab[3, "Sum Sq"])
HideShow
       fictitious_main fictitious_interaction                  total 
                   156                    316                    472 
HideShow
#> 156 + 316 = 472, which is SS_B/A of Table 10.9, book p. 559, carved up
#> between two effects that do not exist in a nested design
c(F_wrong = wrong_tab[1, "Mean Sq"] / wrong_tab[4, "Mean Sq"],
  F_right = f_gender)
HideShow
  F_wrong   F_right 
25.814634  9.966102 
HideShow
#> 25.815 against MS_W versus 9.966 against MS_B/A; the second is the value in
#> Table 10.9, book p. 559

The correct base-R syntax is the one used in Section 10.4.3, and it is worth seeing the two side by side.

HideShow
right_aov <- aov(Severity ~ Gender + Error(Gender / Trainee),
                 data = chapter_10_table_9)
summary(right_aov)
HideShow

Error: Gender
       Df Sum Sq Mean Sq
Gender  1   1176    1176

Error: Gender:Trainee
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  4    472     118               

Error: Within
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals 18    820   45.56               
HideShow
#> MS_B/A = 118 on 4 df is now the residual of the stratum holding Gender —
#> matches Table 10.9, book p. 559

The cost of the correct syntax is the blank FF column: aov() will not form a ratio across strata, so the test has to be finished by hand, as F=1176/118=9.966F = 1176/118 = 9.966. That is the practical reason to prefer a mixed-effects fit, which carries the hierarchy in the model rather than in the error strata and reports the test directly.

HideShow
anova(nested_lmm)
HideShow
Type III Analysis of Variance Table with Satterthwaite'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 = 9.966 on (1, 4) df, p = .034 — matches Table 10.9, book p. 559

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 10: Designs with Random or Nested Factors (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