R Code and Instructions
On this page
- 10.3 — Designs with Random Factors
- 10.3.3 — Two-Factor Case
- 10.3.3.1 — Expected Mean Squares
- 10.3.3.3 — Selection of Error Terms
- 10.3.4 — Numerical Example
- 10.3.5 — Alternative Tests and Design Considerations with Random Factors
- 10.3.6 — Follow-Up Tests and Confidence Intervals
- 10.3.7 — Measures of Association Strength
- 10.3.7.2 — Numerical Example
- 10.3.8 — Using Statistical Computer Programs to Analyze Designs with Random Factors
- 10.3.9 — Determining Power in Designs with Random Factors
- 10.4 — Designs with Nested Factors
- 10.4.3 — Models and Tests
- 10.4.4 — Degrees of Freedom
- 10.4.5 — Statistical Assumptions and Related Issues
- 10.4.6 — Follow-Up Tests and Confidence Intervals
- 10.4.7 — Standardized Effect Size Estimates
- 10.4.8 — Strength of Association in Nested Designs
- 10.4.9 — Using Statistical Computer Programs to Analyze Nested Designs
- How to Cite This Page
- References
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 test follows, and the familiar habit of dividing everything by 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: for the fixed factor and the intraclass correlation 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 ICC10.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
g k r
4 4 4 HideShow
[1] 4The 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 in a mixed design as rather than .
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 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_tableHideShow
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 NAHideShow
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.29654Tested against , the therapy effect comes out at with — a confident conclusion that one therapy is better than another, drawn from a population in which no therapy-mode effect exists. Tested against , the same data give , , 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 fixed, factor random), the error term for is , while and are both tested against . 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.0000The 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 (fixed; is the computer-based program, the paper-and-pencil program) and school is factor (random). The data are Table 10.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 5HideShow
Computer Paper-and-Pencil
21 27 HideShow
1 2 3 4
25 26 22 23 HideShow
[1] 24The 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 tests change.
The crossed aov() fit supplies all of them.
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 NAHideShow
#> 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 rather than .
HideShow
F p
13.50000000 0.03489698 HideShow
[1] 10.12796For contrast, the same numerator divided by gives the liberal test the book reports in Section 10.3.5.
HideShow
F p
1.993080e+01 9.352074e-05 The full source table of Table 10.5, in APA style with gt. The and columns use the Table 10.4 denominators: for the fixed program effect, for the random school factor and for the interaction. Partial for each effect is its share of effect-plus-within variance, which is the book’s 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 η<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 | ||||
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 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 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.
The same source table in DMAR
The bookkeeping above — build the crossed ANOVA table, then divide
by 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.
| 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 |
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 returning , which is the case here — the term can be dropped and the interaction and within-cell sources pooled into a single residual.
HideShow
[1] 18.8HideShow
F p
1.914894e+01 1.038738e-04 If instead one concluded there was no evidence for either a effect or an interaction, the analysis could be rerun as a one-factor design, pooling , , and within.
HideShow
HideShow
F p
18.047493404 0.000134292 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-05The legitimacy of the last three rows hinges on the preliminary test having reached the right conclusion. As the book argues, an interaction that went undetected is still an interaction, so continuing to use 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 in the interval. For the two-level fixed factor that means and its 3 degrees of freedom.
HideShow
[1] -6HideShow
HideShow
lower upper
-11.1969131 -0.8030869 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 , since is the denominator for the random factor.
HideShow
HideShow
[1] 3.831616HideShow
estimate lower upper
4.000000 -1.149569 9.149569 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
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 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: (Equation 10.13) and (Equation 10.14).
HideShow
[1] 1118HideShow
A B AB
0.322 0.089 0.072 HideShow
A B AB
0.384 0.147 0.122 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, , 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 Equation 10.20 then gives the overall measures and Equation 10.22 the partial ones. The fixed factor’s measure is written ; the random factors’ are intraclass correlations .
HideShow
[1] 29.64375HideShow
#> 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
omega_sq_A_partial rho_I_B_partial rho_I_AB_partial
0.316 0.078 0.087 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 |
The overall counts school-to-school variability and the program-by-school interaction as part of the variance the program has to explain. The partial 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
Groups Name Variance
Program:School (Intercept) 1.72082
School (Intercept) 0.66668
Residual 18.06250The 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 as ,
which is what Equation 10.21 inverts. Fitting (1 | School)
and (1 | Program:School) as two separate random terms
implies instead that also
carries an interaction component, , and subtracting
that extra term accounts for the whole discrepancy:
HideShow
[1] 0.6666667So the two answers differ by , 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
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 The Error: School:Program stratum holds the test of the
fixed factor, with the interaction mean square as its residual, so the
reported and 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 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
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 ' ' 1The 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 for the fixed effect that
is not the book’s : the
likelihood- based fit works on a different scale, and it is the 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.
| 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.
| 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 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 , and the multiplier is the ratio of expected mean squares (Equation 10.23). For a one-way random-effects design that ratio is (Equation 10.24), with , so Equation 10.25 gives
The book computes this with SPSS syntax over a table of scenarios: three levels of a random factor, , , and 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.80Reaching power of .80 takes 240 subjects in total even though 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 . Redistributing the same 240 subjects over more levels shows the second point directly.
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.93HideShow
a n f_rand alpha EMSratio F_crit power
1 7 20 0.4 0.05 4.2 2.17 0.8The effect size itself can be estimated from pilot data. Equation 10.26 estimates as . The book’s illustration is a three-group pilot study with means of 40, 45, and 50, 20 subjects per group, and .
HideShow
[1] 500HideShow
f2_rand f_rand
0.2000000 0.4472136 HideShow
a n f_rand alpha EMSratio F_crit power
1 3 64 0.4472136 0.05 13.8 3.04 0.8Planning 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 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.
| 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 ; trainee is the random factor , 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:
where is the fixed effect of the th gender, the simple effect of the th trainee within that gender, and the within-cell error. No interaction term exists, so is the pooled sum of squares from one-way analyses within each gender. The data are Table 10.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 65HideShow
1 2
46 60 HideShow
[1] 53In 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 rather than .
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
column blank for gender, because the test spans two strata. The two
ratios are a line of arithmetic each.
HideShow
F p
9.96610169 0.03428551 HideShow
F p
2.59024390 0.07164886 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
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 65HideShow
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 ' ' 1Six numbers, one per trainee, and the resulting is the 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 test.
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 ' ' 1The nested source table of Table 10.9, in APA style. Gender is tested against , the nested trainee effect against ; partial 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 η<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 | ||||
sjPlot::tab_model() summarizes the same model, with the
trainee random-effect variance and the intraclass correlation reported
beside the gender fixed effect.
| 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 degrees of freedom. The nested factor pools the simple effects: within each of the levels of , for in total. The precaution the book flags is that is the number of levels per nest, not the total number of distinct levels of in the design.
HideShow
df_A df_BA df_W
1 4 18 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 on 4 degrees of freedom (Equation 10.43).
HideShow
[1] -14HideShow
lower upper
-26.312733 -1.687267 Comparing two trainees is a test of the nested factor, so it drops back down the hierarchy to 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
[1] 8.777796HideShow
#> 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 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 fixed, factor 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 Standardizing by the between-cluster standard deviation gives (Equation 10.44), by the within-cluster standard deviation (Equation 10.45), and by both sources together (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 d_W d_T
-3.290 -2.074 -1.755 HideShow
sigma_beta sigma_epsilon sigma_total
4.256 6.749 7.979 and are both larger in magnitude than , 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
[1] 2468HideShow
R2 R2_partial_within R2_partial_nested
0.476 0.589 0.714 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 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 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.
| 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%
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.
| 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%
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.
| term | value |
|---|---|
| var_icc | 0.049 |
With 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 .
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 ' ' 1The gender effect is unchanged at , but dividing it by rather than sends from 9.966 to
25.815 and 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 into
a fictitious 156 and 316.
HideShow
fictitious_main fictitious_interaction total
156 316 472 HideShow
F_wrong F_right
25.814634 9.966102 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
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 The cost of the correct syntax is the blank column: aov() will not
form a ratio across strata, so the test has to be finished by hand, as
. 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
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 ' ' 1How 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
Arel-Bundock V (2026). modelsummary: Summary Tables and Plots for Statistical Models and Data: Beautiful, Customizable, and Publication-Ready. doi:10.32614/CRAN.package.modelsummary https://doi.org/10.32614/CRAN.package.modelsummary. R package version 2.6.0, https://CRAN.R-project.org/package=modelsummary.
Bates D, Maechler M, Bolker B, Walker S, Ly A, Jagan M (2026). lme4: Linear Mixed-Effects Models using ‘Eigen’ and S4. doi:10.32614/CRAN.package.lme4 https://doi.org/10.32614/CRAN.package.lme4. R package version 2.0-6, https://CRAN.R-project.org/package=lme4.
Iannone R, Cheng J, Schloerke B, Haughton S, Hughes E, Lauer A, François R, Seo J, Brevoort K, Roy O (2026). gt: Easily Create Presentation-Ready Display Tables. doi:10.32614/CRAN.package.gt https://doi.org/10.32614/CRAN.package.gt. R package version 1.3.0, https://CRAN.R-project.org/package=gt.
Kelley K (2026). DMAR: Design, Measurement, and Analysis in R (DMAR). R package version 1.2.0, https://kenkelley.org.
Kuznetsova A, Bruun Brockhoff P, Haubo Bojesen Christensen R (2026). lmerTest: Tests in Linear Mixed Effects Models. doi:10.32614/CRAN.package.lmerTest https://doi.org/10.32614/CRAN.package.lmerTest. R package version 3.2-1, https://CRAN.R-project.org/package=lmerTest.
Lenth R, Piaskowski J (2026). emmeans: Estimated Marginal Means, aka Least-Squares Means. doi:10.32614/CRAN.package.emmeans https://doi.org/10.32614/CRAN.package.emmeans. R package version 2.0.4, https://CRAN.R-project.org/package=emmeans.
Lüdecke D (2025). sjPlot: Data Visualization for Statistics in Social Science. doi:10.32614/CRAN.package.sjPlot https://doi.org/10.32614/CRAN.package.sjPlot. R package version 2.9.0, https://CRAN.R-project.org/package=sjPlot.
Maxwell S, Delaney H, Kelley K (2026). AMCP: Data Sets to Accompany Designing Experiments and Analyzing Data: A Model Comparison Perspective (Maxwell, Delaney, and Kelley, 2027, 4th Edition). doi:10.32614/CRAN.package.AMCP https://doi.org/10.32614/CRAN.package.AMCP. R package version 2.0.0, https://CRAN.R-project.org/package=AMCP.
Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.
R Core Team (2026). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria. doi:10.32614/R.manuals https://doi.org/10.32614/R.manuals. https://www.R-project.org/.
Sjoberg D, Larmarange J, Curry M, de la Rua E, Lavery J, Whiting K, Zabor E (2026). gtsummary: Presentation-Ready Data Summary and Analytic Result Tables. doi:10.32614/CRAN.package.gtsummary https://doi.org/10.32614/CRAN.package.gtsummary. R package version 2.5.1, https://CRAN.R-project.org/package=gtsummary.
Wickham H, Chang W, Henry L, Pedersen T, Takahashi K, Wilke C, Woo K, Yutani H, Dunnington D, van den Brand T (2026). ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics. doi:10.32614/CRAN.package.ggplot2 https://doi.org/10.32614/CRAN.package.ggplot2. R package version 4.0.3, https://CRAN.R-project.org/package=ggplot2.
Wickham H, François R, Henry L, Müller K, Vaughan D (2026). dplyr: A Grammar of Data Manipulation. doi:10.32614/CRAN.package.dplyr https://doi.org/10.32614/CRAN.package.dplyr. R package version 1.2.1, https://CRAN.R-project.org/package=dplyr.