R Code and Instructions
On this page
- 11.5 — Analysis of Repeated-Measures Designs with Two Levels
- 11.5.1 — The Problem of Correlated Errors
- 11.5.2 — Reformulation of Model
- 11.7 — Traditional Univariate (Mixed-Model) Approach
- 11.7.1 — Comparison of Full and Restricted Models
- 11.7.2 — Estimation of Parameters: Numerical Example
- 11.8 — Assumptions in the Traditional Univariate (Mixed-Model) Approach
- 11.8.1 — Homogeneity, Sphericity, and Compound Symmetry
- 11.8.2 — Numerical Example
- 11.9 — Adjusted Univariate Tests
- 11.9.1 — Lower-Bound Adjustment
- 11.9.2 — ε̂ Adjustment
- 11.9.3 — ε̃ Adjustment
- 11.9.4 — Summary of Four Mixed-Model Approaches
- 11.10 — Measures of Effect
- 11.11 — Comparisons among Individual Means
- 11.12 — Confidence Intervals for Comparisons
- 11.13 — Confidence Intervals with Pooled and Separate Variances
- Reproducing Figure 11.2
- 11.14 — Considerations in Designing Within-Subjects Experiments
- 11.14.1 — Order Effects
- 11.14.2 — Differential Carryover Effects
- 11.14.3 — Controlling for Order Effects with More Than Two Levels: Latin Square Designs
- 11.15 — Relative Advantages of Between-Subjects and Within-Subjects Designs
- 11.16 — Power Analysis and Sample Size Planning
- Unequal correlations
- 11.17 — Intraclass Correlations for Assessing Reliability
- How to Cite This Page
- References
Examples follow the book’s section numbers.
Chapter 11 provides a comprehensive overview of the traditional univariate approach to one-way within-subjects (repeated-measures) designs. It highlights the primary advantage of these designs, which is removing systematic individual differences to drastically increase statistical power, while carefully addressing the fundamental statistical challenge of correlated errors. To manage this challenge, the text details critical assumptions like sphericity and compound symmetry, alongside vital epsilon adjustments (such as Greenhouse–Geisser) for when these assumptions are violated. Furthermore, the chapter covers essential practical considerations for researchers, including controlling for order effects using Latin squares, computing effect sizes, and conducting accurate power analyses. Finally, the ANOVA framework is extended beyond experimental design to demonstrate how intraclass correlations (ICCs) can be calculated to assess rater and measurement reliability.
Chapter 1 explains how AMCP names the book’s data
sets; these notes assume that explanation and get on with the
statistics. The data used here are chapter_11_table_1 (two
conditions, six subjects), chapter_11_table_4 (four
conditions, ten subjects), chapter_11_table_5 (the McCarthy
scores for 12 children at four ages), and
chapter_11_table_19 and chapter_11_table_20
(the judges’ ratings used for the intraclass correlations).
HideShow
# Load all of the packages used.
library(AMCP) # the textbook's data sets
library(DMAR) # design, measurement, and analysis
library(tidyverse) # data wrangling and plotting (dplyr, ggplot2, and friends)
library(MASS) # mvrnorm() for the multivariate-normal simulations (Figure 11.2, Section 11.16)
library(car) # Anova() for repeated-measures tests with sphericity corrections
library(broom) # tidy model output into data frames
library(gt) # polished HTML tables
library(gtsummary) # publication-ready regression / comparison tables
library(modelsummary) # side-by-side model-comparison tables11.5 — Analysis of Repeated-Measures Designs with Two Levels
11.5.2 — Reformulation of Model
To eliminate the correlated errors, we transform the two scores per subject into a single difference score ().
This reduces the model to a single parameter representing the mean difference:
Because there is now only one observation () per subject, the dependency among errors is removed. Our null hypothesis simplifies to testing whether the population mean difference is zero ().
We can replicate the step-by-step model comparison shown in Table 11.3 by calculating the full-model error () and restricted-model error () from these difference scores.
HideShow
# Replicating Table 11.3: the F test via model comparison
n <- nrow(chapter_11_table_1)
# Calculate Difference Scores (D) and the Mean Difference (D_bar)
D <- chapter_11_table_1$YCondition2 - chapter_11_table_1$YCondition1
D_bar <- mean(D)
# Restricted Error (E_R), Equation 11.12: the restricted model predicts 0.
E_R <- sum(D^2)
# Full Error (E_F), Equation 11.11: the full model predicts D_bar.
E_F <- sum((D - D_bar)^2)
df_R <- n # 6
df_F <- n - 1 # 5
F_stat <- ((E_R - E_F) / (df_R - df_F)) / (E_F / df_F)
cat("Sum of D:", sum(D), " Sum of D^2:", E_R, "\n")HideShow
Sum of D: 12 Sum of D^2: 32 HideShow
Restricted Error (E_R): 32 HideShow
Full Error (E_F): 8 HideShow
F statistic: 15 HideShow
Critical F(.05; 1, 5): 6.61 Because this test has a single
numerator degree of freedom, it is mathematically identical to a
dependent (paired) test, which is
Equation 11.19. We run it with t.test(), spelling out the
options rather than relying on defaults. Note the argument order:
putting Condition 2 first makes t.test() report the mean of
, which is the direction
of in Table 11.3.
HideShow
Paired t-test
data: chapter_11_table_1$YCondition2 and chapter_11_table_1$YCondition1
t = 3.873, df = 5, p-value = 0.01172
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
0.6725572 3.3274428
sample estimates:
mean difference
2 HideShow
t = 3.873 t^2 = 15 As shown, , so for a two-level repeated-measures design the model-comparison approach and the paired test are the same test. The mean difference of is what Equation 11.18 standardizes.
In DMAR: an exact test that does not assume normality
The paired test assumes the
difference scores are normally distributed, which is a strong assumption
with . DMAR’s
randomization_test_paired() returns an exact value obtained by enumerating all within-pair sign patterns, assuming
only that the labeling of the two conditions within a pair is arbitrary
under the null hypothesis. Note that DMAR defines the within-pair
difference as , the reverse of
the x - y convention in stats::t.test(), so
the arguments are supplied in the opposite order here to keep the
direction .
| term | value |
|---|---|
| statistic | 2.000 |
| p_value | 0.0312 |
| n_pairs | 6 |
| n_evaluated | 64 |
| exact | 1 |
Both routes reject at the .05 level, and the mean difference is identical. The randomization value is coarser than the test’s because with six pairs there are only sign patterns, so the smallest attainable two-sided value is . That coarseness is the price of dropping the normality assumption at this sample size, and it is worth knowing before a small paired study is run.
11.7 — Traditional Univariate (Mixed-Model) Approach
When a within-subjects design has more than two levels, it can be viewed as a two-factor design, as Table 11.4 in the text (book p. 596) lays out. Specifically:
Factor A (treatment condition): a fixed factor.
Factor S (subjects): a random factor, because the subjects are viewed as a random sample from a larger population.
11.7.1 — Comparison of Full and Restricted Models
Because we are testing a fixed main effect (condition) in the presence of a random factor (subjects), the appropriate error term for the test is the interaction of the two, . This interaction measures how inconsistently the treatment effect behaves across subjects. Dropping the terms from Equations 11.20 and 11.21 gives the two models that are actually compared:
with and , so that .
11.7.2 — Estimation of Parameters: Numerical Example
Let’s look at the data from Table 11.5, which tracks the general cognitive scores of 12 children on the McCarthy Scales of Children’s Abilities at 4 different ages (30, 36, 42, and 48 months). First, we load the data and calculate the marginal means.
HideShow
'data.frame': 12 obs. of 4 variables:
$ Months30: int 108 103 96 84 118 110 129 90 84 96 ...
$ Months36: int 96 117 107 85 125 107 128 84 104 100 ...
$ Months42: int 110 127 106 92 125 96 123 101 100 103 ...
$ Months48: int 122 133 107 99 116 91 128 113 88 105 ...HideShow
Months30 Months36 Months42 Months48
1 108 96 110 122
2 103 117 127 133
3 96 107 106 107
4 84 85 92 99
5 118 125 125 116
6 110 107 96 91
7 129 128 123 128
8 90 84 101 113
9 84 104 100 88
10 96 100 103 105
11 105 114 105 112
12 113 117 132 130HideShow
# Calculate Marginal Means
# Means by row (subjects)
subject_means <- apply(chapter_11_table_5, MARGIN = 1, FUN = mean)
# Means by column (ages)
condition_means <- apply(chapter_11_table_5, MARGIN = 2, FUN = mean)
grand_mean <- mean(as.matrix(chapter_11_table_5))
cat("Subject Means:\n", round(subject_means, 2), "\n\n")HideShow
Subject Means:
109 120 104 90 121 101 127 97 94 101 109 123 HideShow
Condition Means:
103 107 110 112 HideShow
Grand Mean: 108 To see how the ANOVA partitions variance, we can compute the full and restricted models exactly as the textbook does in Tables 11.6 through 11.9.
Restricted model (, Equation 11.25): no age effect. The predicted score for a child is that child’s own mean across all ages.
Full model (, Equation 11.24): age effects allowed. The predicted score is the age mean plus the child’s mean minus the grand mean.
HideShow
# Setup empty matrices to hold our predicted scores and squared errors
n_subj <- nrow(chapter_11_table_5)
a_cond <- ncol(chapter_11_table_5)
Y_hat_full <- matrix(NA, n_subj, a_cond)
Y_hat_restricted <- matrix(NA, n_subj, a_cond)
sq_error_full <- matrix(NA, n_subj, a_cond)
sq_error_restricted <- matrix(NA, n_subj, a_cond)
# Calculate Predictions and Squared Errors cell-by-cell
for (i in 1:n_subj) {
for (j in 1:a_cond) {
actual_Y <- chapter_11_table_5[i, j]
# Restricted Model: Predicted score is just the Subject's mean
Y_hat_restricted[i, j] <- subject_means[i]
sq_error_restricted[i, j] <- (actual_Y - Y_hat_restricted[i, j])^2
# Full Model: Predicted score accounts for both Subject and Condition effects
Y_hat_full[i, j] <- condition_means[j] + subject_means[i] - grand_mean
sq_error_full[i, j] <- (actual_Y - Y_hat_full[i, j])^2
}
}
# Column sums of squared discrepancies, as the book's tables report them
cat("Full model, column sums (Table 11.8): ", colSums(sq_error_full), "\n")HideShow
Full model, column sums (Table 11.8): 474 584 220 728 HideShow
Restricted model, column sums (Table 11.9): 774 596 268 920 HideShow
#> 474, 584, 220, 728 — matches Table 11.8, book p. 600
#> 774, 596, 268, 920 — matches Table 11.9, book p. 601
# Calculate Total Error for both models
E_R <- sum(sq_error_restricted)
E_F <- sum(sq_error_full)
# Calculate F statistic
df_R <- n_subj * (a_cond - 1) # 12 * 3 = 36
df_F <- (n_subj - 1) * (a_cond - 1) # 11 * 3 = 33
F_stat <- ((E_R - E_F) / (df_R - df_F)) / (E_F / df_F)
cat("\nRestricted Error (E_R):", E_R, "\n")HideShow
Restricted Error (E_R): 2558 HideShow
Full Error (E_F): 2006 HideShow
SS_A = E_R - E_F: 552 HideShow
F statistic: 3.03 While hand calculation builds intuition, aov() is the
practical route. Standard ANOVA functions in R require data in “long”
(person-period) format rather than the “wide” (multivariate) format we
currently have, so we reshape with tidyr and
dplyr first.
HideShow
# Add an ID variable (by row number)
C11_T5_PP <- chapter_11_table_5
C11_T5_PP$ID <- as.factor(1:nrow(C11_T5_PP))
# Reshape the data from Wide to Long
# The "sep=-3" partitions between the 3rd and 2nd value from the end of the column name.
C11_T5_PP <- C11_T5_PP %>%
pivot_longer(
cols = -ID,
names_to = c("Unit", "Month"),
names_sep = -3,
values_to = "Values"
) %>%
arrange(ID, Month)
# We do not need the "Unit" variable, so we drop it.
C11_T5_PP$Unit <- NULL
# Both ID and the Repeated Measure (Month) must be factors
# If not, the model will be incorrectly fitted
C11_T5_PP$Month <- as.factor(C11_T5_PP$Month)
head(C11_T5_PP, 10)HideShow
# A tibble: 10 × 3
ID Month Values
<fct> <fct> <int>
1 1 s30 108
2 1 s36 96
3 1 s42 110
4 1 s48 122
5 2 s30 103
6 2 s36 117
7 2 s42 127
8 2 s48 133
9 3 s30 96
10 3 s36 107HideShow
tibble [48 × 3] (S3: tbl_df/tbl/data.frame)
$ ID : Factor w/ 12 levels "1","2","3","4",..: 1 1 1 1 2 2 2 2 3 3 ...
$ Month : Factor w/ 4 levels "s30","s36","s42",..: 1 2 3 4 1 2 3 4 1 2 ...
$ Values: int [1:48] 108 96 110 122 103 117 127 133 96 107 ...With the data in the correct format, we can run the model. To tell R
that Month is a within-subjects factor, we define the error strata with
+ Error(ID/Month). This builds the same error term we computed by
hand.
HideShow
Error: ID
Df Sum Sq Mean Sq F value Pr(>F)
Residuals 11 6624 602.2
Error: ID:Month
Df Sum Sq Mean Sq F value Pr(>F)
Month 3 552 184.00 3.027 0.0432 *
Residuals 33 2006 60.79
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1The same source table laid out APA-style, with sums of squares, df, mean squares, the omnibus F, its p value, and partial . The error term for the age effect is the Age Subjects interaction, so partial is . The table is built with gt because the plain-text ANOVA summary above does not format well in HTML.
HideShow
# Pull the error-stratum ANOVA into a tidy data frame, then format as APA.
aov_tbl <- broom::tidy(Repeated_Measures_ANOVA)
# Locate the three pieces we report: the Subjects stratum (S), the Age main
# effect (A), and the Age x Subjects residual that serves as its error term.
ss_S <- aov_tbl$sumsq[aov_tbl$stratum == "ID" & aov_tbl$term == "Residuals"]
ss_A <- aov_tbl$sumsq[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Month"]
ss_AxS <- aov_tbl$sumsq[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Residuals"]
tibble(
Source = c("Subjects (S)", "Age (A)", "A × S (error)"),
SS = c(ss_S, ss_A, ss_AxS),
df = c(aov_tbl$df[aov_tbl$stratum == "ID" & aov_tbl$term == "Residuals"],
aov_tbl$df[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Month"],
aov_tbl$df[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Residuals"]),
MS = c(ss_S / 11, ss_A / 3, ss_AxS / 33),
Fstat = c(NA, aov_tbl$statistic[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Month"], NA),
p = c(NA, aov_tbl$p.value[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Month"], NA),
# Partial eta-squared for the Age effect: its share of effect-plus-error SS.
peta = c(NA, ss_A / (ss_A + ss_AxS), NA)
) |>
gt() |>
fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
fmt_number(columns = peta, decimals = 3) |>
fmt_number(columns = p, decimals = 4) |>
sub_missing(missing_text = "") |>
cols_label(Fstat = md("*F*"), p = md("*p*"),
peta = md("Partial η<sup>2</sup>")) |>
tab_header(title = md("**Table 11.5 ANOVA**. Repeated-Measures Analysis of Variance for McCarthy Scores")) |>
cols_align(align = "center", columns = -Source)| Table 11.5 ANOVA. Repeated-Measures Analysis of Variance for McCarthy Scores | ||||||
| Source | SS | df | MS | F | p | Partial η2 |
|---|---|---|---|---|---|---|
| Subjects (S) | 6,624.00 | 11 | 602.18 | |||
| Age (A) | 552.00 | 3 | 184.00 | 3.03 | 0.0432 | 0.216 |
| A × S (error) | 2,006.00 | 33 | 60.79 | |||
This is the basic, unadjusted repeated-measures ANOVA. It assumes sphericity holds exactly. Section 11.8 examines that assumption for these data, and Section 11.9 shows what happens to the test once it is relaxed.
The two models side by side
The full and restricted models of Equations 11.22 and 11.23 are
ordinary least-squares fits once the data are in long format: the full
model regresses Values on subjects (ID) and
age (Month), and the restricted model drops age, keeping
only the subject effects. Their residual sums of squares are exactly the
and we computed by hand, and comparing
them with anova() returns the same as the repeated-measures table
above.
HideShow
E_F (full residual SS) = 2006 HideShow
E_R (restricted residual SS) = 2558 HideShow
Analysis of Variance Table
Model 1: Values ~ ID
Model 2: Values ~ ID + Month
Res.Df RSS Df Sum of Sq F Pr(>F)
1 36 2558
2 33 2006 3 552 3.0269 0.04322 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1A modelsummary table places the two models next to each
other with their fit statistics at the foot; the 11 subject dummy
coefficients are omitted so the age effect stands out. Each age
coefficient is that month’s mean minus the 30-month mean, which from the
Table 11.5 marginal means is 4, 7, and 9 points.
HideShow
| Subjects only (restricted) | Subjects + Age (full) | |
|---|---|---|
| (Intercept) | 109.000 | 104.000 |
| (4.215) | (4.358) | |
| Months36 | 4.000 | |
| (3.183) | ||
| Months42 | 7.000 | |
| (3.183) | ||
| Months48 | 9.000 | |
| (3.183) | ||
| Num.Obs. | 48 | 48 |
| AIC | 353.1 | 347.4 |
| BIC | 377.4 | 377.3 |
| Log.Lik. | -163.528 | -157.694 |
A gtsummary tbl_regression() table reports
the age effect from the full model with confidence intervals and
p values. The restricted model has no age term by construction
(that is the whole point of the restriction), so the regression table
belongs to the full model; the subject dummies are dropped with
include so only the Month terms appear.
| Characteristic | Beta | 95% CI | p-value |
|---|---|---|---|
| Month | |||
| s30 | — | — | |
| s36 | 4.0 | -2.5, 10 | 0.2 |
| s42 | 7.0 | 0.52, 13 | 0.035 |
| s48 | 9.0 | 2.5, 15 | 0.008 |
| Abbreviation: CI = Confidence Interval | |||
11.8 — Assumptions in the Traditional Univariate (Mixed-Model) Approach
In addition to the standard ANOVA assumptions of normality, independence of subjects, and random sampling, the traditional univariate repeated-measures ANOVA requires a strict assumption about variances: homogeneity of treatment-difference variances.
This means that if you calculate the difference between any two treatment levels (), the population variance of those differences must be identical for every possible pair of levels. By Equation 11.30, the variance of a difference is
11.8.1 — Homogeneity, Sphericity, and Compound Symmetry
The homogeneity assumption is satisfied when the population covariance matrix meets the condition of sphericity. A related but stricter condition is compound symmetry.
Sphericity: the variances of the differences are equal, even if the underlying variances and correlations differ.
Compound symmetry: all treatment variances are equal to each other () and all correlations between treatments are equal to each other (), as in Equations 11.31 and 11.32. Then the variance of a difference reduces to , a constant, so compound symmetry guarantees sphericity.
As the text notes, compound symmetry is sufficient but technically not necessary. However, in a one-way design with more than two levels it would be highly unusual to find a matrix with sphericity but not compound symmetry, so for practical purposes compound symmetry is the requirement here.
11.8.2 — Numerical Example
We can use the McCarthy scores (Table 11.5) to check the sample variances, correlations, and variances of the differences to see whether they are consistent with sphericity.
HideShow
Sample Variances:HideShow
Months30 Months36 Months42 Months48
188.00 200.55 178.00 218.00 HideShow
Months30 Months36 Months42 Months48
Months30 1.000 0.795 0.696 0.599
Months36 0.795 1.000 0.760 0.466
Months42 0.696 0.760 1.000 0.853
Months48 0.599 0.466 0.853 1.000The correlation between adjacent time points (42 and 48 months: ) is much higher than between distant time points (36 and 48 months: ). Because the variances are roughly equal but the correlations are clearly unequal, compound symmetry is violated. The variances of the differences (Table 11.11) show the consequence.
HideShow
# Replicate Table 11.11: Variances of the Differences
# Extract columns for readability
Y1 <- chapter_11_table_5[, 1] # 30 months
Y2 <- chapter_11_table_5[, 2] # 36 months
Y3 <- chapter_11_table_5[, 3] # 42 months
Y4 <- chapter_11_table_5[, 4] # 48 months
var_diffs <- c(
"Var(Y2 - Y1)" = var(Y2 - Y1),
"Var(Y3 - Y2)" = var(Y3 - Y2),
"Var(Y4 - Y3)" = var(Y4 - Y3),
"Var(Y3 - Y1)" = var(Y3 - Y1),
"Var(Y4 - Y2)" = var(Y4 - Y2),
"Var(Y4 - Y1)" = var(Y4 - Y1)
)
data.frame(Variance = round(var_diffs, 2))HideShow
Variance
Var(Y2 - Y1) 79.82
Var(Y3 - Y2) 91.27
Var(Y4 - Y3) 59.82
Var(Y3 - Y1) 111.27
Var(Y4 - Y2) 223.64
Var(Y4 - Y1) 163.64Because these variances range from to , the sample data are far from homogeneous treatment-difference variances. The book reports that when the assumption is false, the actual probability of a Type I error may be as high as .10 or .15 against a nominal .05 (p. 605).
In DMAR: Mauchly’s test from the wide data
DMAR’s mauchly_test() runs Mauchly’s test of sphericity
directly on the wide (multivariate) data, so no multivariate model or
idata frame has to be assembled first.
| W | statistic | df | p_value | n_subjects | n_levels | method |
|---|---|---|---|---|---|---|
| 0.243 | 13.768 | 5 | 0.0177 | 12 | 4 | Mauchly’s test of sphericity |
The test is significant here, agreeing with the unequal variances of the differences above. The book is careful about how much weight this deserves: it cites Keselman, Rogan, Mendoza, and Breen (1980) to the effect that Mauchly’s test has little value as a preliminary test before the test of mean differences (p. 605), and recommends the epsilon adjustments of Section 11.9 regardless of its outcome.
11.9 — Adjusted Univariate Tests
To correct for violations of sphericity, we adjust the degrees of freedom used for the critical value. The adjustment is based on Box’s measure of departure from sphericity, (epsilon).
Perfect sphericity:
Maximum violation:
Multiplying the degrees of freedom by shrinks them, which raises the critical and makes the test more conservative. The observed itself never changes: all four approaches in this section use .
11.9.1 — Lower-Bound Adjustment
Geisser and Greenhouse (1958) showed that the smallest possible value of in an -level design is . Substituting that lower bound into Box’s adjusted degrees of freedom gives and , which for these data is 1 and 11.
HideShow
Lower bound for epsilon, 1/(a - 1): 0.33 HideShow
Critical F(.05; 1, n - 1): 4.84 The observed of 3.03 is well below 4.84, so the null hypothesis is not rejected under this very conservative approach.
11.9.2 — Adjustment
Greenhouse and Geisser’s estimates the
population from the
sample covariance matrix. Its computational formula is tedious, but
car::Anova() reports it (along with ) once the
within-subjects design is specified. The two orderings of the same two
surnames in this section are deliberate and follow the book: the
lower-bound correction is due to Geisser and Greenhouse (1958), whereas
derives from
Greenhouse and Geisser (1959).
HideShow
# Bind the columns of the wide dataset into a single matrix
Y_matrix <- as.matrix(chapter_11_table_5)
# Fit a multivariate linear model with just an intercept
rm_model <- lm(Y_matrix ~ 1)
# Create a data frame defining the within-subjects design
idata <- data.frame(Month = factor(c("30", "36", "42", "48")))
# Run the Anova with the within-subjects design specified
rm_anova <- Anova(rm_model, idata = idata, idesign = ~Month)
# Display the univariate summary (which includes the sphericity corrections)
rm_summary <- summary(rm_anova, multivariate = FALSE)
rm_summaryHideShow
Univariate Type III Repeated-Measures ANOVA Assuming Sphericity
Sum Sq num Df Error SS den Df F value Pr(>F)
(Intercept) 559872 1 6624 11 929.7391 5.586e-12 ***
Month 552 3 2006 33 3.0269 0.04322 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Mauchly Tests for Sphericity
Test statistic p-value
Month 0.24265 0.017718
Greenhouse-Geisser and Huynh-Feldt Corrections
for Departure from Sphericity
GG eps Pr(>F[GG])
Month 0.60954 0.07479 .
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HF eps Pr(>F[HF])
Month 0.7248502 0.06353773HideShow
GG epsilon-hat: 0.61 HideShow
Adjusted df from the book's rounded .61: 1.83 and 20.13 HideShow
Critical F at those df: 3.59 The observed of 3.03 is still below 3.59, so the null hypothesis is not rejected with the approach either. (R’s exact is 0.60954; the book’s degrees of freedom on p. 606 come from the rounded value .61, which is why 20.13 appears there rather than 20.115.)
11.9.3 — Adjustment
Huynh and Feldt’s corrects the tendency of to underestimate , so it is always at least as large and the test is less conservative. Equation 11.34 gives it as a function of , which we can confirm directly.
HideShow
HF epsilon-tilde from car: 0.7249 HideShow
HF epsilon-tilde from Eq. 11.34: 0.7249 HideShow
Adjusted df: 2.17 and 23.92 HideShow
Critical F at those df: 3.32 Again the observed of 3.03 falls short of the critical value, so all three adjustments agree with each other, and disagree with the unadjusted test.
11.9.4 — Summary of Four Mixed-Model Approaches
Table 11.12 in the text collects the four approaches. Every one of them uses the same observed ; only the degrees of freedom for the critical value differ.
HideShow
tibble(
Approach = c("Unadjusted",
"Huynh-Feldt (epsilon-tilde)",
"Greenhouse-Geisser (epsilon-hat)",
"Geisser-Greenhouse lower bound"),
`Observed F` = rm_summary$univariate.tests["Month", "F value"],
`df num` = c(a - 1, eps_HF * (a - 1), 0.61 * (a - 1), 1),
`df den` = c((a - 1) * (n - 1), eps_HF * (a - 1) * (n - 1), 0.61 * (a - 1) * (n - 1), n - 1)
) |>
mutate(`Critical F` = qf(0.95, df1 = `df num`, df2 = `df den`)) |>
gt() |>
fmt_number(columns = c(`Observed F`, `Critical F`), decimals = 2) |>
fmt_number(columns = c(`df num`, `df den`), decimals = 2) |>
tab_header(title = md("**Table 11.12**. Summary of Four Mixed-Model Approaches, Table 11.5 Data")) |>
cols_align(align = "center", columns = -Approach)| Table 11.12. Summary of Four Mixed-Model Approaches, Table 11.5 Data | ||||
| Approach | Observed F | df num | df den | Critical F |
|---|---|---|---|---|
| Unadjusted | 3.03 | 3.00 | 33.00 | 2.89 |
| Huynh-Feldt (epsilon-tilde) | 3.03 | 2.17 | 23.92 | 3.32 |
| Greenhouse-Geisser (epsilon-hat) | 3.03 | 1.83 | 20.13 | 3.59 |
| Geisser-Greenhouse lower bound | 3.03 | 1.00 | 11.00 | 4.84 |
The adjusted values are the
modern equivalent of looking up those critical values, and
car::Anova() reports them.
HideShow
Adjustment epsilon adjusted_p
1 Greenhouse-Geisser 0.6095 0.0748
2 Huynh-Feldt 0.7249 0.0635The unadjusted test is significant at .05, but the book recommends against ever using it (p. 607), and recommends among the remaining three (p. 609). Once the degrees of freedom are shrunk, the age effect no longer meets the .05 criterion.
In DMAR: all four approaches in one table
DMAR’s anova_within() returns the omnibus
within-subjects with the
unadjusted, Greenhouse–Geisser, Huynh–Feldt, and lower-bound results in
a single tidy table, directly from the wide data. The whole of Table
11.12 comes back from one call, with the epsilons, adjusted degrees of
freedom, and values together.
| adjustment | F_value | df_1 | df_2 | p_value | epsilon |
|---|---|---|---|---|---|
| none | 3.027 | 3 | 33 | 0.0432 | NA |
| Greenhouse-Geisser | 3.027 | 1.829 | 20.115 | 0.0748 | 0.610 |
| Huynh-Feldt | 3.027 | 2.175 | 23.920 | 0.0635 | 0.725 |
| lower_bound | 3.027 | 1 | 11 | 0.1098 | 0.333 |
The agreement with car::Anova() confirms the calculation
from two independent implementations.
11.10 — Measures of Effect
A statistically significant value tells us only that an effect exists, not how large it is. For magnitude we use measures of association strength (omega squared) and standardized mean differences (Cohen’s ).
Omega squared ()
Omega squared estimates the proportion of total population variance accounted for by the treatment effect. For a one-way within-subjects design, Equation 11.35 is
The denominator requires and (the mean square for subjects).
Rather than hardcoding them, we extract them from the univariate summary
of the car::Anova model fitted above.
HideShow
# Save the univariate summary table from our rm_anova model
uni_table <- rm_summary$univariate.tests
# 1. Extract Sum of Squares
SS_A <- uni_table["Month", "Sum Sq"]
SS_AxS <- uni_table["Month", "Error SS"]
SS_S <- uni_table["(Intercept)", "Error SS"] # Subject variance is the intercept's error term
# 2. Extract Degrees of Freedom
df_A <- uni_table["Month", "num Df"]
df_AxS <- uni_table["Month", "den Df"]
df_S <- uni_table["(Intercept)", "den Df"]
# 3. Calculate Mean Squares
MS_A <- SS_A / df_A
MS_AxS <- SS_AxS / df_AxS
MS_S <- SS_S / df_S
# 4. Calculate SS_Total (Equation 11.37)
SS_Total <- SS_A + SS_S + SS_AxS
cat("Mean Squares: MS_A =", round(MS_A, 2), " MS_AxS =", round(MS_AxS, 4), "\n")HideShow
Mean Squares: MS_A = 184 MS_AxS = 60.7879 HideShow
Sum of Squares Subjects (SS_S): 6624 HideShow
Total Sum of Squares (SS_Total): 9182 HideShow
#> MS_A = 184.00 and MS_AxS = 60.7879 — match book p. 602
#> SS_S = 6624 and SS_Total = 9182 — match book p. 609
# 5. Calculate Omega Squared (Equation 11.35)
# Note: (a - 1) is exactly equal to df_A
omega_sq <- (df_A * (MS_A - MS_AxS)) / (SS_Total + MS_S)
cat("Omega Squared:", round(omega_sq, 4), "\n")HideShow
Omega Squared: 0.0378 So the age effect accounts for approximately 4% of the total population variance in McCarthy scores.
Standardized mean differences ()
For a standardized effect size we must divide a mean difference by a standard deviation, and the choice of standard deviation matters a great deal.
It is tempting to use , because that is the error term for the test. But subject variance has been partialed out of it, so the denominator is artificially small and the resulting is not comparable to a from a between-subjects study.
Instead we reconstruct the standard deviation as if the data had come from a between-subjects design, by pooling the subject variance () and the error variance () back together. That is Equation 11.38:
HideShow
Reconstructed Standard Deviation (sd): 14 HideShow
sqrt(mean of the four level variances): 14 HideShow
#> 14.00 — matches book p. 611 ("averaging these four values and taking the square root")
# Extract specific condition means (from Table 11.5)
mean_30 <- mean(chapter_11_table_5[, 1]) # 103
mean_36 <- mean(chapter_11_table_5[, 2]) # 107
mean_48 <- mean(chapter_11_table_5[, 4]) # 112
# Calculate Cohen's d for specific comparisons
d_36_vs_30 <- (mean_36 - mean_30) / sd_pooled
d_48_vs_30 <- (mean_48 - mean_30) / sd_pooled
cat("\nEffect Size (d) - 36 vs 30 months:", round(d_36_vs_30, 2), "\n")HideShow
Effect Size (d) - 36 vs 30 months: 0.29 HideShow
Effect Size (d) - 48 vs 30 months: 0.64 HideShow
sqrt(MS_AxS): 7.8 d(48 vs 30) using it: 1.15 The book reads these as follows (p. 611): the 30-to-36-month difference is on the “small” side, and the 30-to-48-month difference is about halfway between “medium” and “large.” Had we used instead, the same 9-point difference would have been reported as , nearly twice as large, purely because systematic individual differences were excluded from the yardstick.
11.11 — Comparisons among Individual Means
The traditional way to test an individual comparison in a repeated-measures design divides the contrast sum of squares by the interaction mean square (Equation 11.40):
with critical values from Equation 11.41 (Tukey) and Equation 11.42 (Scheffé) when other comparisons are to be taken into account. We can compute all of this for the 48-versus-30-month comparison, whose estimate we have already verified against the Table 11.5 marginal means.
HideShow
psi-hat: 9 SS_psi: 486 F: 7.995 HideShow
Per-comparison F(.05; 1, 33): 4.139 HideShow
Bonferroni, C = 6 comparisons: 7.878 HideShow
Tukey, q^2 / 2 (Eq. 11.41): 7.317 HideShow
Scheffe, (a - 1)F (Eq. 11.42): 8.675 These values are not printed in the book; they follow from Equations 11.40 through 11.42 using the mean square and the means already confirmed against Table 11.5 (pp. 598, 602).
The book’s recommendation, however, is that these formulas not be used (p. 612). They lean entirely on sphericity, and Boik (1981) showed that tests of comparisons are far more sensitive to departures from sphericity than the omnibus test is: when is too small for a particular contrast the actual error rate can reach .70 for a nominal .05, and when it is too large the power can collapse to near .05. Nor do the and adjustments fix the power problem. The remedy, a separate error term for each contrast, is what the next two sections preview.
11.12 — Confidence Intervals for Comparisons
Confidence intervals face the same sphericity trap as the tests. With a pooled error term, some 95% intervals are too narrow and others too wide.
Let’s reproduce Table 11.13 and see exactly how the pooled-error approach differs from the separate-error approach for McCarthy scores at 48 versus 42 months and at 48 versus 30 months.
1. Pooled error interval. Equation 11.43 assumes every pairwise difference is estimated with the same precision:
The degrees of freedom for are the residual from the ANOVA, .
HideShow
df_pooled <- (a - 1) * (n - 1) # 33 degrees of freedom
# Critical t (w) for a per-comparison alpha of .05, two-tailed
w_pooled <- qt(0.975, df_pooled)
# Contrast coefficients for a pairwise comparison (1 and -1)
# sum(c_j^2 / n_j) = (1^2 / 12) + ((-1)^2 / 12) = 2/12
contrast_sum <- 2 / n
margin_pooled <- w_pooled * sqrt(MS_AxS * contrast_sum)
cat("Pooled Margin of Error: +/-", round(margin_pooled, 2), "\n")HideShow
Pooled Margin of Error: +/- 6.48 2. Separate error interval. Equation 11.44 replaces the pooled with , an error term specific to the two levels being compared, and the degrees of freedom for drop to .
HideShow
df_sep <- n - 1 # 11
w_sep <- qt(0.975, df_sep)
# Comparison 1: 48 Months vs 42 Months
diff_48_42 <- chapter_11_table_5[, 4] - chapter_11_table_5[, 3]
var_diff_48_42 <- var(diff_48_42)
se_48_42 <- sqrt((var_diff_48_42 / 2) * contrast_sum)
margin_sep_48_42 <- w_sep * se_48_42
# Comparison 2: 48 Months vs 30 Months
diff_48_30 <- chapter_11_table_5[, 4] - chapter_11_table_5[, 1]
var_diff_48_30 <- var(diff_48_30)
se_48_30 <- sqrt((var_diff_48_30 / 2) * contrast_sum)
margin_sep_48_30 <- w_sep * se_48_30
ci_comparison <- data.frame(
Comparison = c("48 vs 42 months", "48 vs 30 months"),
Mean_Diff = c(mean(diff_48_42), mean(diff_48_30)),
Pooled_Margin = c(margin_pooled, margin_pooled),
Separate_Margin = c(margin_sep_48_42, margin_sep_48_30)
)
print(ci_comparison, digits = 3)HideShow
Comparison Mean_Diff Pooled_Margin Separate_Margin
1 48 vs 42 months 2 6.48 4.91
2 48 vs 30 months 9 6.48 8.13The choice of error term does not move the center of the interval, only its width. Scores spaced close together in time (48 versus 42 months) are estimated much more precisely (margin 4.91) than scores spaced further apart (48 versus 30 months, margin 8.13). The pooled term assigns 6.48 to both.
In DMAR: every pairwise comparison with its own error term
The separate-variances logic generalizes to the whole set of pairwise
comparisons. The mainstream route is
stats::pairwise.t.test() with paired = TRUE,
which uses each pair’s own difference scores. To exercise a full
four-condition set we use the Table 11.4 data (book p. 596).
HideShow
C1 C2 C3 C4
1 8 10 7 5
2 9 9 8 6
3 7 5 8 4
4 9 6 5 7
5 8 7 7 6
6 5 4 4 3
7 7 6 5 4
8 8 8 6 6
9 9 8 6 5
10 7 7 4 5HideShow
# Base/mainstream route: all six paired comparisons, Bonferroni-adjusted
four_long <- data.frame(
Value = unlist(four),
Condition = factor(rep(colnames(four), each = nrow(four))),
Subject = factor(rep(seq_len(nrow(four)), times = ncol(four)))
)
pairwise.t.test(x = four_long$Value, g = four_long$Condition,
paired = TRUE, p.adjust.method = "bonferroni")HideShow
Pairwise comparisons using paired t tests
data: four_long$Value and four_long$Condition
C1 C2 C3
C2 0.794 - -
C3 0.026 0.640 -
C4 5.5e-06 0.027 0.727
P value adjustment method: bonferroni pairwise.t.test() reports the adjusted significance
levels alone. DMAR’s pairwise_within() reports the mean
difference, its standard deviation, the per-pair statistic, and a confidence interval
for every comparison, all in one tidy table, taken straight from the
wide data.
| contrast | mean_difference | sd_difference | t_value | df | p_value | p_adjusted | ci_lower | ci_upper | n_pairs |
|---|---|---|---|---|---|---|---|---|---|
| C2 – C1 | -0.700 | 1.337 | -1.655 | 9 | 0.1323 | 0.7938 | -1.657 | 0.257 | 10 |
| C3 – C1 | -1.700 | 1.418 | -3.791 | 9 | 0.0043 | 0.0257 | -2.714 | -0.686 | 10 |
| C4 – C1 | -2.600 | 0.699 | -11.759 | 9 | < 0.0001 | < 0.0001 | -3.100 | -2.100 | 10 |
| C3 – C2 | -1.000 | 1.764 | -1.793 | 9 | 0.1066 | 0.6395 | -2.262 | 0.262 | 10 |
| C4 – C2 | -1.900 | 1.595 | -3.767 | 9 | 0.0044 | 0.0266 | -3.041 | -0.759 | 10 |
| C4 – C3 | -0.900 | 1.663 | -1.711 | 9 | 0.1212 | 0.7274 | -2.090 | 0.290 | 10 |
Confidence level: 95%
The two routes agree on every adjusted value. Each row uses its own difference-score variance, so the confidence intervals widen or narrow with the correlation between the two conditions being compared, exactly as the pooled-versus-separate comparison on Table 11.5 showed by hand.
11.13 — Confidence Intervals with Pooled and Separate Variances
The book marks this section “Optional.” It answers the question left open by Section 11.12: why is the separate-variance approach actually preferable, rather than merely different?
It comes down to the correlations between the repeated measures. By Equation 11.30,
We can show in R how drives the variance of the difference, using the population values of the simulation the book runs in this section: every level has variance 225, levels 1 and 2 correlate .8, and levels 1 and 4 correlate .2.
HideShow
# Both conditions have a variance of 225 (SD = 15)
var_Y1 <- 225
var_Y2 <- 225
sd_Y1 <- sqrt(var_Y1)
sd_Y2 <- sqrt(var_Y2)
# Scenario A: Highly correlated conditions (levels 1 and 2, rho = 0.8)
r_high <- 0.8
var_diff_high <- var_Y1 + var_Y2 - (2 * r_high * sd_Y1 * sd_Y2)
# Scenario B: Weakly correlated conditions (levels 1 and 4, rho = 0.2)
r_low <- 0.2
var_diff_low <- var_Y1 + var_Y2 - (2 * r_low * sd_Y1 * sd_Y2)
cat("Variance of Y2 - Y1 (rho = .8):", var_diff_high, "\n")HideShow
Variance of Y2 - Y1 (rho = .8): 90 HideShow
Variance of Y4 - Y1 (rho = .2): 360 When two conditions are highly correlated, the true variance of their difference shrinks, and a pooled error term makes the interval systematically too wide, costing precision and power. When two conditions are weakly correlated, the true variance of their difference is large, and the pooled term makes the interval systematically too narrow, so coverage falls below the stated 95%. Unless sphericity holds, the separate-variance approach is the one to use.
Reproducing Figure 11.2
Figure 11.2 (book p. 616) displays a simulation described on
pp. 615–617. Data are generated for a four-level within-subjects design
with subjects. Every level
has population mean 50 except level 2, whose mean is 54, so the true
value of is 4 and the
true value of is 0.
Each level has a standard deviation of 15, but sphericity is
deliberately broken: the population correlation matrix (Table 11.14,
book p. 615) has levels 1 and 2 correlating .8 while levels 1 and 4
correlate only .2. Across 10 replications, each contrast gets two
confidence intervals centered at the same estimate: a pooled interval
(Equation 11.43, using ) and a separate interval (Equation 11.44, using that pair’s
own difference-score variance). Because the simulation is random, we fix
set.seed(113) so the figure is reproducible; the book’s own
figure comes from a different draw, so the individual intervals differ
while the pattern does not.
HideShow
# Population from Table 11.14 (book p. 615): 4 levels, sd = 15, sphericity violated.
a_sim <- 4
n_sim <- 50
mu <- c(50, 54, 50, 50) # mu2 - mu1 = 4 (true); mu4 - mu1 = 0 (true)
sd_ <- 15
R <- matrix(c(1.0, 0.8, 0.5, 0.2,
0.8, 1.0, 0.8, 0.5,
0.5, 0.8, 1.0, 0.8,
0.2, 0.5, 0.8, 1.0), nrow = 4, byrow = TRUE)
Sigma <- (sd_^2) * R # variance 225 on the diagonal
# Critical t for a per-comparison interval at alpha = .05 (two-tailed). Pooled
# intervals use df = (a - 1)(n - 1) (Eq. 11.43); separate intervals use df = n - 1
# (Eq. 11.44), because each pair contributes a single difference score per subject.
reps <- 10
w_pool <- qt(0.975, (a_sim - 1) * (n_sim - 1))
w_sep <- qt(0.975, n_sim - 1)
set.seed(113)
sim <- lapply(seq_len(reps), function(r) {
Y <- MASS::mvrnorm(n_sim, mu, Sigma)
# Pooled error term: MS_{A x S} from the additive (subject + level) model.
level_means <- colMeans(Y)
subj_means <- rowMeans(Y)
grand <- mean(Y)
resid_AxS <- Y - outer(subj_means, level_means, "+") + grand
MS_AxS_sim <- sum(resid_AxS^2) / ((a_sim - 1) * (n_sim - 1))
one_contrast <- function(cj, contrast_label) {
psi <- sum(cj * level_means) # point estimate
me_p <- w_pool * sqrt(MS_AxS_sim * sum(cj^2) / n_sim) # pooled half-width
idx <- which(cj != 0) # the two active levels
Dij <- Y[, idx[1]] * cj[idx[1]] + Y[, idx[2]] * cj[idx[2]]
me_s <- w_sep * sqrt(stats::var(Dij) / n_sim) # separate half-width
data.frame(
Contrast = contrast_label, Replication = r, Estimate = psi,
Pooled_lo = psi - me_p, Pooled_hi = psi + me_p,
Separate_lo = psi - me_s, Separate_hi = psi + me_s
)
}
rbind(
one_contrast(c(-1, 0, 0, 1), "mu[4] - mu[1]"), # true value 0
one_contrast(c(-1, 1, 0, 0), "mu[2] - mu[1]") # true value 4
)
})
sim <- do.call(rbind, sim)
# Long form for plotting: one row per (replication, contrast, error-term method),
# offset slightly so the pooled and separate lines do not overprint.
ci_long <- rbind(
transform(sim, Method = "Pooled variance", lo = Pooled_lo, hi = Pooled_hi,
yoff = Replication - 0.16),
transform(sim, Method = "Separate variance", lo = Separate_lo, hi = Separate_hi,
yoff = Replication + 0.16)
)
ci_long$Method <- factor(ci_long$Method,
levels = c("Pooled variance", "Separate variance"))
# Panel order: the weakly correlated pair (mu4 - mu1) on top, which is the order
# the text discusses the two contrasts in. Without this the facets would fall in
# alphabetical order and put mu2 - mu1 first.
contrast_levels <- c("mu[4] - mu[1]", "mu[2] - mu[1]")
ci_long$Contrast <- factor(ci_long$Contrast, levels = contrast_levels)
# Reference lines: the true population value of each contrast.
truth <- data.frame(Contrast = factor(contrast_levels, levels = contrast_levels),
true_value = c(0, 4))HideShow
ggplot(ci_long, aes(y = yoff, color = Method, linetype = Method)) +
geom_vline(data = truth, aes(xintercept = true_value),
color = "#0C2340", linewidth = 0.7) +
geom_segment(aes(x = lo, xend = hi, yend = yoff), linewidth = 0.7) +
geom_point(aes(x = Estimate), size = 1.3) +
facet_wrap(~ Contrast, ncol = 1, labeller = label_parsed) +
scale_y_reverse(breaks = 1:10) +
scale_x_continuous(breaks = seq(-12, 12, 2), limits = c(-12, 12)) +
scale_linetype_manual(values = c("Pooled variance" = "solid",
"Separate variance" = "dashed")) +
labs(title = "Figure 11.2. Confidence intervals over 10 replications",
subtitle = "Reference line marks the true population difference in each panel",
x = "Estimated mean difference", y = "Replication",
color = NULL, linetype = NULL) +
theme(legend.position = "top")Figure 11.2. Confidence intervals over 10 replications for two population mean differences, using pooled versus separate error terms. Solid lines are pooled; dashed lines are separate.
The top panel (, where levels 1 and 4 correlate only .2) shows the separate-variance intervals (dashed) running wider than the pooled intervals (solid): the pooled term understates how variable this far-apart comparison really is. The bottom panel (, where levels 1 and 2 correlate .8) shows the reverse, with the separate intervals narrower, so the pooled term wastes precision and power. The point estimate is identical for the two methods within a replication; only the width differs. We can count the coverage directly rather than reading it off the figure.
HideShow
coverage <- function(df, true_value) {
c(Pooled = sum(df$Pooled_lo <= true_value & df$Pooled_hi >= true_value),
Separate = sum(df$Separate_lo <= true_value & df$Separate_hi >= true_value))
}
s41 <- subset(sim, Contrast == "mu[4] - mu[1]")
s21 <- subset(sim, Contrast == "mu[2] - mu[1]")
cat("Intervals containing the true value of mu4 - mu1 (0):\n"); print(coverage(s41, 0))HideShow
Intervals containing the true value of mu4 - mu1 (0):HideShow
Pooled Separate
7 9 HideShow
Intervals containing the true value of mu2 - mu1 (4):HideShow
Pooled Separate
9 8 HideShow
Mean half-width, mu4 - mu1: pooled 3.74 separate 5.43 HideShow
Mean half-width, mu2 - mu1: pooled 3.74 separate 2.62 With this seed, the separate-variance intervals contain the true value of in 9 of 10 replications against 7 of 10 for the pooled intervals. The book’s own 10 replications (p. 615) come out 9 and 8. The individual counts differ because the two sets of replications are different random draws, and 10 replications is far too few to pin down a coverage rate; what both show is the same qualitative pattern. The half-widths make the mechanism explicit: the pooled half-width is the same number in both panels, while the separate half-width is larger than it for the weakly correlated pair and smaller for the strongly correlated pair. As the book puts it, the pooled approach has the right average width across all pairwise comparisons while none of the individual intervals need have the right width (p. 614).
11.14 — Considerations in Designing Within-Subjects Experiments
11.14.1 — Order Effects
Within-subjects designs must protect internal validity against confounds with time. The standard solution with two levels is a crossover design, in which half the subjects receive Treatment A first and the other half receive Treatment B first, so that the main effect of order is controlled.
11.14.2 — Differential Carryover Effects
A crossover design controls the main effect of order but is vulnerable to differential carryover: the lingering effect of Treatment 1 onto Treatment 2 differs from the lingering effect of Treatment 2 onto Treatment 1.
Table 11.15 gives a set of plausible means for a free-recall study in which half the children receive a chunking strategy first and half receive the control condition first. Computing the marginal means shows how differential carryover masks the true treatment effect.
HideShow
# Create the data matrix from Table 11.15
carryover_matrix <- matrix(
c(10, 20, # Control first, then Strategy
20, 20), # Strategy first, then Control
nrow = 2,
byrow = TRUE,
dimnames = list(
Group = c("Control -> Strategy", "Strategy -> Control"),
Time = c("Phase 1", "Phase 2")
)
)
print(carryover_matrix)HideShow
Time
Group Phase 1 Phase 2
Control -> Strategy 10 20
Strategy -> Control 20 20HideShow
#> 10, 20 / 20, 20 — matches Table 11.15, book p. 618
# Marginal means for the "Treatment"
# Control scores are at [1,1] and [2,2]; Strategy scores are at [1,2] and [2,1]
mean_control <- mean(c(carryover_matrix[1, 1], carryover_matrix[2, 2]))
mean_strategy <- mean(c(carryover_matrix[1, 2], carryover_matrix[2, 1]))
cat(
"\nMarginal Mean for Control:", mean_control,
"\nMarginal Mean for Strategy:", mean_strategy,
"\nApparent Effect:", mean_strategy - mean_control,
"\nEffect in the control-first group only:",
carryover_matrix[1, 2] - carryover_matrix[1, 1],
"\n"
)HideShow
Marginal Mean for Control: 15
Marginal Mean for Strategy: 20
Apparent Effect: 5
Effect in the control-first group only: 10 The marginal means suggest the strategy improves scores by 5 points (20 versus 15). But the children who received the control condition first improved by 10 points, while those who received the strategy first showed no change at all, because strategy training produced a persistent change they carried into the control phase. When effects are intended to persist, the book’s advice is to abandon the within-subjects design and use a between-subjects design (p. 619).
11.14.3 — Controlling for Order Effects with More Than Two Levels: Latin Square Designs
With more than two levels, testing every possible order quickly becomes impractical: conditions have orders, and have 120 (book p. 619).
A more efficient deterministic control is a Latin square, in which each treatment appears exactly once in each sequential position. The text warns against the cyclic square of Table 11.16, because there treatment B always follows A, C always follows B, and so on, which is exactly the arrangement most vulnerable to carryover. Instead, randomly select one of the standard squares of Table 11.17 and randomly permute its rows and columns.
The book works this through with Standard Square 3 and the random orders 3, 1, 4, 2 for rows and 3, 4, 1, 2 for columns (p. 620), which we can reproduce exactly.
HideShow
Standard Square 3:HideShow
[,1] [,2] [,3] [,4]
[1,] "A" "B" "C" "D"
[2,] "B" "A" "D" "C"
[3,] "C" "D" "B" "A"
[4,] "D" "C" "A" "B" HideShow
After the book's row permutation (3, 1, 4, 2):HideShow
[,1] [,2] [,3] [,4]
[1,] "C" "D" "B" "A"
[2,] "A" "B" "C" "D"
[3,] "D" "C" "A" "B"
[4,] "B" "A" "D" "C" HideShow
After the book's column permutation (3, 4, 1, 2):HideShow
[,1] [,2] [,3] [,4]
[1,] "B" "A" "C" "D"
[2,] "C" "D" "A" "B"
[3,] "A" "B" "D" "C"
[4,] "D" "C" "B" "A" In practice the permutation is drawn at random rather than chosen, which R does in two lines.
HideShow
Row Permutation Order: 1 2 4 3
Col Permutation Order: 3 1 2 4
Randomized Latin Square:HideShow
[,1] [,2] [,3] [,4]
[1,] "C" "A" "B" "D"
[2,] "D" "B" "A" "C"
[3,] "A" "D" "C" "B"
[4,] "B" "C" "D" "A" HideShow
[,1] [,2] [,3] [,4]
[1,] "A" "A" "A" "A"
[2,] "B" "B" "B" "B"
[3,] "C" "C" "C" "C"
[4,] "D" "D" "D" "D" Permuting the rows and columns of the four standard squares is what gives the 576 possible Latin squares for reported on book p. 620, and it breaks the systematic treatment sequences that make the cyclic square a poor choice.
11.15 — Relative Advantages of Between-Subjects and Within-Subjects Designs
The main advantage of a within-subjects design is efficiency and power: using subjects as their own controls removes systematic individual differences from the error term.
Venter and Maxwell (1999) give formulas relating the total number of subjects needed in a within-subjects design () to that in a between-subjects posttest-only design (), assuming any position effects have been modeled (Equation 11.45), and to a pretest-posttest design analyzed with ANCOVA (Equation 11.46):
Where is the population correlation between scores at the two levels. We can reproduce all four columns of Table 11.18, which gives the total sample size needed for power of .80 to detect a medium difference between two means.
HideShow
# Base sample size for the between-subjects posttest-only design
N_B <- 128
# Correlation values used in Table 11.18
rho_values <- c(0.0, 0.3, 0.5, 0.7)
# Within-subjects, from Equation 11.45
N_W_exact <- (N_B * (1 - rho_values)) / 2
# Pretest-posttest with ANCOVA, by rearranging Equation 11.46
N_PP_exact <- N_W_exact * 2 * (1 + rho_values)
# Pretest-posttest analyzed with change scores: the variance of a change score
# is 2 sigma^2 (1 - rho), so the design needs 2(1 - rho) times the posttest-only N
N_change_exact <- N_B * 2 * (1 - rho_values)
power_comparison <- data.frame(
Correlation_Rho = rho_values,
Between_Posttest = N_B,
Between_ANCOVA = ceiling(N_PP_exact),
Between_Change = ceiling(N_change_exact),
Within_Subjects = ceiling(N_W_exact)
)
print(power_comparison)HideShow
Correlation_Rho Between_Posttest Between_ANCOVA Between_Change
1 0.0 128 128 256
2 0.3 128 117 180
3 0.5 128 96 128
4 0.7 128 66 77
Within_Subjects
1 64
2 45
3 32
4 20The sample sizes are rounded up, since a design cannot use a fraction of a subject; at and the unrounded within-subjects values are 44.8 and 19.2.
The table makes three points, following the book (p. 624):
Even with zero correlation between conditions, the within-subjects design needs only half the subjects (64 versus 128), because each subject contributes two data points.
As the correlation grows, the requirement falls further still: at , 20 subjects give the power that 128 would give in a between-subjects posttest-only design.
Including a pretest and analyzing change scores can be far worse than ignoring the pretest altogether (256 versus 128 at ), which is why ANCOVA is almost always the better analysis of a randomized pretest-posttest design.
11.16 — Power Analysis and Sample Size Planning
In a within-subjects design, power depends heavily on the correlation () between the repeated measures. When scores are positively correlated, the error variance shrinks, so the noncentrality parameter () and power both rise.
The text compares the noncentrality parameter of a one-way between-subjects design with that of a one-way within-subjects design (Equations 4.49 and 11.50):
Between-subjects:
Within-subjects:
For power of .80 to detect a medium effect () across conditions, the book reports that a between-subjects design requires in total, or 53 per group (p. 626). Let’s confirm the noncentrality parameter and the power that follows from it, then see how the within-subjects requirement changes with .
HideShow
Between-subjects lambda: 9.9375 HideShow
Critical F(.05; 2, 156): 3.054 HideShow
Power: 0.805 HideShow
#> lambda = 9.9375 and critical F = 3.054, giving power of about .80 — match book p. 626
# Scenario 2: Within-subjects, solving Equation 11.50 for n
# lambda = (a * n * f^2) / (1 - rho) => n = lambda * (1 - rho) / (a * f^2)
n_for_rho <- function(rho) (lambda_between * (1 - rho)) / (a_power * f^2)
cat("\nRequired n for the within-subjects design (rho = 0): ", n_for_rho(0), "\n")HideShow
Required n for the within-subjects design (rho = 0): 53 HideShow
Required n for the within-subjects design (rho = 0.5): 26.5 -> round up to 27 When , the within-subjects design needs 53 subjects in total to reach the same as the between-subjects design, which needed 53 per group, or 159 in all (book p. 626). When the correlation rises to a more realistic , the closed form halves that to 26.5, or 27 subjects. The book reports 28 for this case (p. 627), from software that solves for the sample size directly instead of matching noncentrality parameters as the closed form does, and it is explicit that 28 is the requirement whether the unadjusted or the -adjusted test is used. The closed form lands slightly lower because equating to the between-subjects value ignores the degrees of freedom the within-subjects test actually has. The book also notes that at the adjusted test needs 54 rather than 53, so the adjustment costs very little here.
Unequal correlations
Compound symmetry, in which every condition correlates equally with every other, is rarely met in practice. The book works through a case where it fails: population means of 10, 13, and 16, population variance 96 (which implies ), and a correlation matrix whose entries differ (book p. 627).
GLIMMPSE and SAS GLMPOWER, which require a value for each individual correlation, both give a required sample size of 33 for power of .80 with the recommended -adjusted test (book p. 627). The book then names the package an R user is likeliest to reach for: as of its writing Superpower computes power from a given sample size rather than solving for the sample size, so the book uses it the other way round, to confirm that at “the power is indeed .80 (within sampling variability and rounding error)” (p. 627). Reproducing that confirmation is what this subsection does, by hand, in base R.
It is worth going slowly, because this is the one place in the chapter where naming a test is not enough to name a number. Once sphericity fails, the statistic no longer follows a noncentral distribution exactly — the book makes precisely this point on p. 627 — so for each candidate test the distribution the statistic is referred to and the distribution it actually follows come apart. The subsections below take the candidates in turn: the unadjusted test, for which Equation 11.50’s average correlation implies .8776 while the matrix the book prints delivers about .827; the Greenhouse–Geisser test with treated as known, .8384; and the Greenhouse–Geisser test a researcher can actually run, .8045, which is the book’s .80 and the figure its 33 rests on. These are not competing attempts at one number; they answer different questions. This is the part of the book’s power discussion that is hardest to follow along with in R, because software reports one of them and the output label rarely says which.
The design, and Equation 11.50 by hand
HideShow
# The correlation matrix R from the textbook (book p. 627)
R_power <- matrix(
c(1.0, 0.6, 0.3,
0.6, 1.0, 0.6,
0.3, 0.6, 1.0),
nrow = 3, byrow = TRUE
)
# The population means, the population variance, and the covariance matrix
# they imply. The book sets the variance to 96.
mu_power <- c(10, 13, 16)
var_power <- 96
Sigma_power <- var_power * R_power
n_power <- 33 # the book's required sample size
# Equation 3.91: the ratio of the variance of the population means to the
# error variance is f^2, so f is the square root of that ratio. Here the
# design is given by the means and the variance, so f follows from them
# rather than being assumed, and the rest of the subsection uses that f.
sigma_m_sq <- mean((mu_power - mean(mu_power))^2)
f_implied <- sqrt(sigma_m_sq / var_power)
cat("f implied by the means and the variance:", f_implied, "\n")HideShow
f implied by the means and the variance: 0.25 HideShow
HideShow
Average of the off-diagonal correlations: 0.5 HideShow
Equation 11.50 noncentrality: 12.375 The design parameters check out against the book: means of 10, 13, and 16 with a population variance of 96 imply (book p. 627), and Equation 11.50 with , , , and gives .
Notice what that calculation did with the correlation matrix: it replaced all three correlations by their average. That is the reduction the book describes on p. 627 as the older approach, taken by programs that “rely on specifying a mean value for the population correlations.” It is worth knowing exactly what the reduction costs, and the answer is: nothing at all, for the noncentrality parameter. The error term of the within-subjects has expectation , where is the covariance matrix of a set of orthonormal contrasts among the conditions, and that quantity equals for any correlation matrix. Building also gives us , which the book (p. 628) rightly calls tedious to compute from the individual correlations by hand — but which is three lines of R:
HideShow
# A set of orthonormal contrasts among the a condition means: Helmert
# contrasts, each scaled to unit length, so that U %*% t(U) is the identity
U_power <- t(apply(t(contr.helmert(a_power)), 1,
function(r) r / sqrt(sum(r^2))))
Sigma_star <- U_power %*% Sigma_power %*% t(U_power)
b_df <- a_power - 1 # number of contrasts, and the numerator df
# The expected error term, two ways
cat("tr(Sigma*) / (a - 1): ", sum(diag(Sigma_star)) / b_df, "\n")HideShow
tr(Sigma*) / (a - 1): 48 HideShow
sigma^2 * (1 - rho-bar): 48 HideShow
Population epsilon: 0.8621 So is not an approximation: it is the exact noncentrality parameter of this design, unequal correlations and all. What the average correlation cannot capture is the shape of the distribution. When sphericity fails, is a weighted sum of chi-square variables rather than a single scaled one, and is exactly the summary of that measures how far from a single scaled chi-square it falls. Every disagreement in the rest of this subsection comes from how a method handles , never from .
Quantity 1 — the power Equation 11.50 implies
Equation 11.50 gave
exactly. If the design were compound symmetric with every correlation at
, the unadjusted
mixed-model test would be
distributed as a noncentral with that , and its power would be a plain
tail probability needing nothing beyond qf() and
pf().
HideShow
Critical F(.05; 2, 64): 3.14 HideShow
Power implied by Equation 11.50 at n = 33: 0.8776 HideShow
#> critical F = 3.14 and power = .8776, the figure for the compound-symmetric
#> design that the average correlation describes
# What the positive correlations buy, on the effect-size scale power software
# usually prints: the design's own partial eta-squared and the f it implies
eta_p_sq_power <- lambda_power / (lambda_power + df2_un)
cat("Effective partial eta-squared:", round(eta_p_sq_power, 4),
"-> effective f:", round(sqrt(eta_p_sq_power / (1 - eta_p_sq_power)), 4), "\n")HideShow
Effective partial eta-squared: 0.162 -> effective f: 0.4397 That is 87.76%, and the last two lines make concrete how much the
repeated measurements are worth: a raw medium effect () behaves like an effective , with , because each
subject serves as their own control. The same 87.76355% is what
Superpower’s ANOVA_exact() reports for this design with no
correction applied.
What 87.76% is not is the power of the unadjusted test under the matrix the book prints. Being referred to a distribution does not make a statistic follow it, which is the point made just before this subsection: when sphericity fails, is a weighted sum of chi-square variables, so the ratio is not a noncentral and its .05 critical value is not really a .05 critical value. What the unadjusted test does here can be found out by running it on data from this and counting.
HideShow
# One replicate of the one-way within-subjects omnibus test, on a sample drawn
# from the population (mu, Sigma). correction = "none" is the unadjusted test;
# correction = "GG" estimates epsilon-hat from the replicate's own data, which
# is what a researcher does. Returns TRUE if the test rejects.
omnibus_reject <- function(n, mu, Sigma, U, correction = c("none", "GG"),
alpha = 0.05) {
correction <- match.arg(correction)
b <- nrow(U)
D <- MASS::mvrnorm(n = n, mu = mu, Sigma = Sigma) %*% t(U) # contrast scores
S <- cov(D)
F_obs <- n * sum(colMeans(D)^2) / sum(diag(S))
eps <- switch(correction,
none = 1, # no correction
GG = sum(diag(S))^2 / (b * sum(S^2))) # from THIS sample
F_obs > qf(1 - alpha, df1 = b * eps, df2 = b * (n - 1) * eps)
}
set.seed(113)
reps_power <- 50000
hits_un <- replicate(reps_power,
omnibus_reject(n_power, mu_power, Sigma_power, U_power,
correction = "none"))
cat("Simulated power of the unadjusted test at n = 33:", round(mean(hits_un), 4),
" Monte Carlo SE:",
round(sqrt(mean(hits_un) * (1 - mean(hits_un)) / reps_power), 4), "\n")HideShow
Simulated power of the unadjusted test at n = 33: 0.8288 Monte Carlo SE: 0.0017 So under the book’s own correlation matrix the unadjusted test has power of about .827 at , not .8776. The closed form in Quantity 3 puts it at .8268, and this simulation lands about one Monte Carlo standard error above that. The .8776 is what Equation 11.50’s average correlation implies, and it is the right answer for the design that average describes — the compound-symmetric design of the previous subsection, where sphericity does hold and the reference distribution is the right one. It is not a property of the unequal-correlation design this subsection is about.
That distinction is not local to this example. The book states it directly when it turns to the two-factor case: “if sphericity does not hold, we cannot simply rely on the mean correlation, and must instead specify each element of the covariance (or correlation) matrix” (p. 685). Chapter 12 of these notes works through what that costs, reproducing the table of required sample sizes on book p. 686 from the full matrix rather than from its average. The book sets an exercise on the Type I error side of the same point (p. 641, Exercise 27), where the reader computes the rejection rate of the unadjusted test under a non-spherical matrix with the null hypothesis true. Either way, .8776 and .827 are both reference points rather than planning figures, because the book is explicit (p. 627) that it does not recommend the unadjusted test at all.
Quantity 2 — the Greenhouse–Geisser test with treated as known
The textbook correction multiplies both degrees of freedom by . If we pretend is known and equal to its
population value, the noncentrality is rescaled along with the degrees
of freedom, and the power is again one pf() call:
HideShow
HideShow
GG power with epsilon treated as known: 0.8384 This is the quantity that ANOVA_exact(correction = "GG")
reports, and the three lines above reproduce its 83.84% for this design
to four decimals. It is a clearly defined and clearly documented
quantity: the power of a Greenhouse–Geisser test whose correction factor
is the population . It
is the right thing to report if the question is how much the
non-sphericity costs with the correction held fixed. It is not the
quantity the book’s 33 rests on, for a reason that has nothing to do
with the arithmetic: no researcher can run that test. The population
is unknown, and the
test that actually gets run substitutes computed from the very
same data that produce .
Quantity 3 — the Greenhouse–Geisser test a researcher actually runs
This is the book’s quantity, and the one SAS GLMPOWER reports under
mtest=gg. Because and are computed from the same sample, they
are not independent, and the power is not a single noncentral tail. SAS uses the UNIREP approximation
of Muller and Barton (1989), as refined by Muller, Edwards, Simpson, and
Taylor (2007): the numerator and denominator degrees of freedom and the
noncentrality are all rescaled from the eigenvalues of , and the critical value is
taken at an approximation to rather than
at . Those are
documented closed-form expressions, so they can be written out
directly:
HideShow
# The UNIREP approximation for the one-way within-subjects omnibus test.
# mu and Sigma are the population means and covariance matrix; n is the
# number of subjects; test says which critical value the statistic is judged
# against, the epsilon-hat-corrected one ("GG") or the nominal one
# ("uncorrected"). Returns the power, and the pieces it is built from.
power_unirep <- function(mu, Sigma, n, alpha = 0.05,
test = c("GG", "uncorrected")) {
test <- match.arg(test)
a <- length(mu); rM <- a - 1; nu <- n - 1
# orthonormal contrasts, and the contrast covariance matrix and means
U <- t(apply(t(contr.helmert(a)), 1, function(r) r / sqrt(sum(r^2))))
Estar <- U %*% Sigma %*% t(U)
ev <- eigen(Estar, symmetric = TRUE)
phi <- ev$values # eigenvalues of Sigma*
theta <- as.numeric(U %*% mu)
# per-eigenvector noncentrality contributions
om <- n * as.numeric(diag(t(ev$vectors) %*% outer(theta, theta) %*%
ev$vectors)) / phi
# the four trace-like sums the approximation is built from
S1 <- sum(phi); S2 <- sum(phi * om)
S3 <- sum(phi^2); S4 <- sum(phi^2 * om)
# rescaled df and noncentrality (Muller & Barton 1989, Muller et al. 2007)
Rs1 <- (S3 + 2 * S4) / (S1 + 2 * S2)
Rs2 <- S3 / S1
nu1_star <- S1 / Rs1
nu2_star <- nu * S1 / Rs2
lambda <- S2 / Rs1
# the Muller-Barton closed-form approximation to E[epsilon-hat], which is
# what sets the critical value for the GG test
Et1 <- 2 * nu * S3 + nu^2 * S1^2
Et2 <- nu * (nu + 2) * S3 +
2 * nu * sum(outer(phi, phi)[lower.tri(diag(rM))])
E_eps_hat <- Et1 / (rM * Et2)
e <- switch(test, uncorrected = 1, GG = E_eps_hat)
crit <- qf(1 - alpha, df1 = rM * e, df2 = rM * nu * e)
list(power = pf(crit, df1 = nu1_star, df2 = nu2_star,
ncp = lambda, lower.tail = FALSE),
E_eps_hat = E_eps_hat, nu1_star = nu1_star,
nu2_star = nu2_star, lambda = lambda)
}
gg_33 <- power_unirep(mu_power, Sigma_power, n = n_power, test = "GG")
cat("Muller-Barton E[epsilon-hat]:", round(gg_33$E_eps_hat, 4),
" (population epsilon:", round(eps_pop, 4), ")\n")HideShow
Muller-Barton E[epsilon-hat]: 0.8232 (population epsilon: 0.8621 )HideShow
Rescaled df1, df2, lambda: 1.447 55.172 8.954 HideShow
GG power of the test actually run, at n = 33: 0.8045 HideShow
#> .8045 — confirms the book's power of .80 at N = 33, book p. 627
# The same rescaled statistic judged against the nominal critical value, which
# is the unadjusted test of Quantity 1 evaluated under this Sigma
cat("Unadjusted test under this Sigma, same closed form:",
round(power_unirep(mu_power, Sigma_power, n_power,
test = "uncorrected")$power, 4), "\n")HideShow
Unadjusted test under this Sigma, same closed form: 0.8268 That reproduces the book’s claim on p. 627 directly, and it also puts a closed form behind Quantity 1: the .8268 on the last line is the unadjusted test evaluated under the actual rather than under its average correlation, which is the .827 the simulation there estimated.
Two things in that output deserve care. First, the 0.8232 is not itself; it is the Muller–Barton closed-form approximation to it, and the approximation is not sharp here. Second, it is tempting to read the drop from Quantity 2’s .8384 to .8045 as a consequence of being biased downward, since a smaller correction factor means a larger critical value. Both points can be checked directly.
HideShow
# E[epsilon-hat] by simulation: draw a sample, compute its epsilon-hat, repeat
set.seed(113)
eps_hats <- replicate(20000, {
D <- MASS::mvrnorm(n = n_power, mu = mu_power, Sigma = Sigma_power) %*% t(U_power)
S <- cov(D)
sum(diag(S))^2 / (b_df * sum(S^2))
})
cat("Simulated E[epsilon-hat]:", round(mean(eps_hats), 4),
" Muller-Barton approximation:", round(gg_33$E_eps_hat, 4), "\n")HideShow
Simulated E[epsilon-hat]: 0.8414 Muller-Barton approximation: 0.8232 HideShow
#> .8414 against .8232: epsilon-hat is biased downward from the population
#> .8621, but by about .021, not the .039 the closed form implies
# How much of the .8384 -> .8045 drop is the critical value alone? Hold the
# rescaled df and noncentrality fixed and move only the critical value.
crit_at_eps_pop <- qf(0.95, df1 = b_df * eps_pop,
df2 = b_df * (n_power - 1) * eps_pop)
cat("Same rescaled test, critical value taken at the population epsilon:",
round(pf(crit_at_eps_pop, df1 = gg_33$nu1_star, df2 = gg_33$nu2_star,
ncp = gg_33$lambda, lower.tail = FALSE), 4), "\n")HideShow
Same rescaled test, critical value taken at the population epsilon: 0.81 So the bias in is real but mild, and it is not where the conservatism mostly comes from. The larger part is in the rescaling: against Quantity 2’s , and against 1.724. That rescaling is the approximation’s way of carrying the dependence between and — the two are built from the same sums of squares, so a sample that happens to inflate also sets its own critical value. Moving the critical value across the whole distance from the closed form’s 0.8232 to the population 0.8621 accounts for at most a sixth of the gap, and for less than that in truth, since the simulated of 0.8414 is nearer the population value than the closed form’s 0.8232 is. The dependence accounts for the rest.
An approximation deserves a check, and here the check is easy: run
the test itself, with omnibus_reject() from Quantity 1 and
the correction switched on. Each replicate draws subjects, computes its own , and is judged against
its own critical value — which is what a researcher does. No
approximation is involved at all. Because the seed and the replication
count are the ones Quantity 1 used, these are the same 50,000 samples,
now judged the way the book recommends judging them.
HideShow
Simulated GG power at n = 33: 0.806 Monte Carlo SE: 0.0018 The simulation and the closed form agree to within one Monte Carlo standard error, so for this design the UNIREP approximation and brute force are telling the same story, and both put the power of the realized Greenhouse–Geisser test at essentially at .80. The simulation is also the honest adjudicator among the quantities above, since it makes no distributional approximation: it simply runs the test 50,000 times. Report the Monte Carlo standard error whenever you plan this way, and raise the replications if the third decimal matters.
Superpower, the package the book names, has two engines, and they
answer two of the questions separated above. ANOVA_exact()
refers one exact data set to its nominal distribution, returning
Quantity 1’s 87.76% with no correction and Quantity 2’s 83.84% with
correction = "GG"; ANOVA_power() re-estimates
in each simulated
replicate, so it estimates the realized test of Quantity 3, and it is
that engine that lands near the book’s .80 at , within its own Monte Carlo
error.
Solving for the sample size
Nothing above solves for , but a one-line search over the closed forms does, and it is worth seeing what each definition of power asks for.
HideShow
# Smallest n at which a power function reaches the target
smallest_n <- function(power_fn, target = 0.80, n_max = 200) {
for (n in 2:n_max) if (power_fn(n) >= target) return(n)
NA_integer_
}
# Route 1: Equation 11.50's average correlation, referred to a noncentral F.
# This is the spherical calculation, so it describes the rho-bar = .5 design.
n_eq_11_50 <- smallest_n(function(n) {
lam <- a_power * n * f_implied^2 / (1 - rho_bar)
pf(qf(0.95, df1 = a_power - 1, df2 = (a_power - 1) * (n - 1)),
df1 = a_power - 1, df2 = (a_power - 1) * (n - 1),
ncp = lam, lower.tail = FALSE)
})
# Routes 2 and 3: the two tests, both evaluated under the printed matrix
n_unadjusted <- smallest_n(function(n)
power_unirep(mu_power, Sigma_power, n, test = "uncorrected")$power)
n_adjusted <- smallest_n(function(n)
power_unirep(mu_power, Sigma_power, n, test = "GG")$power)
cat("Equation 11.50 with rho-bar = .5, noncentral F: ", n_eq_11_50, "\n")HideShow
Equation 11.50 with rho-bar = .5, noncentral F: 28 HideShow
Unadjusted test under the printed matrix: 31 HideShow
Epsilon-hat-adjusted test, printed matrix: 33 HideShow
HideShow
Unadjusted test at n = 31, under the printed matrix: 0.8022 HideShow
The same test at n = 31, as Equation 11.50 sees it: 0.8544 HideShow
GG power at n = 32 and n = 33: 0.7914 and 0.8045 Two of those three integers are the book’s, and they answer different questions. The 28 is the requirement the book gives for the compound-symmetric case with every correlation at .50 (p. 627), where it holds “whether we use an unadjusted test or an -adjusted test”; solving the noncentral for power .80, rather than equating noncentrality parameters as the closed form earlier in this section did, lands on it exactly rather than on the 26.5 that route produced. The 33 is the requirement the book gives for the unequal-correlation matrix under the -adjusted test (p. 627), and the search reaches it because gives .7914 and gives .8045.
The 31 is the number that makes the comparison honest. Under the printed matrix the unadjusted test needs 31 subjects, not 28: the spherical calculation credits it with .8544 at that sample size, while the test itself delivers .8022. So the price of the recommended adjustment in this design is two subjects, 31 against 33 — and the five-subject gap between 28 and 33 is a gap between two designs, not between two tests.
That the search lands on 33 is a confirmation, not a guarantee. The 33 itself comes from GLIMMPSE and SAS GLMPOWER solving for sample size under the -adjusted test, and different exact solutions for a design that violates sphericity need not land on the same integer: the quantity is approximated differently by different programs, and a power curve that crosses .80 between two consecutive integers will be rounded by whichever side of the crossing a given method falls on. Two subjects is also a small enough difference to be worth reading alongside the book’s warning on p. 627, offered where the unadjusted and adjusted requirements differed by a single subject, that “the difference is not always this small.”
In DMAR: planning a longitudinal within-subjects study
Every calculation above fixes a sample size and reads off the
resulting power; smallest_n() then had to step through
candidate sample sizes one at a time to invert it. When the
within-subjects design is a polynomial change model
(subjects measured repeatedly over time, with interest in the slope of
change), DMAR solves for the sample size directly. Two complementary
planners are available: an accuracy-in-parameter-estimation (AIPE)
planner that targets a confidence-interval width, and a power planner
that targets statistical power.
ss_aipe_pcm() plans the per-group sample size so that
the confidence interval on the group-by-time linear slope difference is
no wider than a target. The calls below use the level-one error variance
of 0.0262 and between-subject slope variance of 0.003 that DMAR’s
documentation takes from Kelley and Rausch (2011).
| term | value |
|---|---|
| necessary_n_per_group | 278 |
Confidence level: 95%
| term | value |
|---|---|
| necessary_n_per_group | 165 |
Confidence level: 95%
HideShow
#> 165 per group; DMAR documents this as Kelley and Rausch (2011, Table 1, M = 10)
# Adding 85% assurance (the realized CI meets the target width with
# probability 0.85, not just on average) raises the requirement:
ss_aipe_pcm(true_var_trend = 0.003, true_var_error = 0.0262,
duration = 4, frequency = 1, width = 0.025,
conf_level = 0.95, assurance = 0.85)| term | value |
|---|---|
| necessary_n_per_group | 295 |
Confidence level: 95%
For the power-analytic counterpart, ss_power_pcm()
solves for the that detects a
given slope difference with target power.
| term | value |
|---|---|
| necessary_n_per_group | 185 |
| total_N | 370 |
| actual_power | 0.801 |
| frequency | 1 |
| duration | 4 |
| n_occasions | 5 |
| polynomial_order | 1 |
| true_reg_coef | -0.022 |
| true_std_reg_coef | -0.400 |
| true_var_error | 0.026 |
| true_var_trend | 0.003 |
| true_var_trend_error | 0.003 |
| reliability | 0.534 |
| noncentral_t_parm | 2.811 |
These two planners answer different questions, the accuracy of the slope estimate versus the power to detect a slope difference. Both make explicit how the number of measurement occasions and the within-subject correlation structure drive the sample size required for a longitudinal within-subjects design. Neither number appears in the printed book; they are reproductions of the sources DMAR’s documentation cites.
11.17 — Intraclass Correlations for Assessing Reliability
Intraclass correlations (ICCs) adapt the within-subjects ANOVA framework to measure the reliability of ratings given by multiple judges (or items). Following Shrout and Fleiss (1979), the key decision is whether you care about agreement (do the judges give the same numbers?) or consistency (do the judges rank the subjects in the same order?).
Case 2 (agreement), Equation 11.51:
Case 3 (consistency), Equation 11.52:
The distinction is clearest in the artificial data of Table 11.20: five subjects rated by three judges, where Judge 2 rates everyone exactly 4 points below Judge 1 and Judge 3 rates everyone exactly 2 points above. There is literally no interaction, so and the usual tests are undefined. We therefore read the mean squares straight off the two-way decomposition rather than from an table.
HideShow
Judge1 Judge2 Judge3
1 9 5 11
2 6 2 8
3 8 4 10
4 7 3 9
5 4 0 6HideShow
#> matches Table 11.20, book p. 629
# Two-way decomposition: subject, judge, and residual (A x S) sums of squares
n <- nrow(ratings_20) # 5 subjects
a <- ncol(ratings_20) # 3 judges
grand <- mean(ratings_20)
subj_dev <- rowMeans(ratings_20) - grand
judge_dev <- colMeans(ratings_20) - grand
resid_mat <- ratings_20 - outer(rowMeans(ratings_20), colMeans(ratings_20), "+") + grand
MS_S <- a * sum(subj_dev^2) / (n - 1)
MS_A <- n * sum(judge_dev^2) / (a - 1)
MS_AxS <- sum(resid_mat^2) / ((n - 1) * (a - 1))
cat("MS_S:", round(MS_S, 2), " MS_A:", round(MS_A, 2), " MS_AxS:", round(MS_AxS, 2), "\n")HideShow
MS_S: 11.1 MS_A: 46.67 MS_AxS: 0 HideShow
ICC(2,1) Agreement: 0.28 HideShow
ICC(3,1) Consistency: 1 Consistency is perfect, so . Agreement is poor, because the judges use very different parts of the scale, and is only .28. Which of the two is the right reliability depends entirely on whether mean differences between judges should count against you.
Composite reliability
Often we want the reliability not of a single judge but of the
average over all judges. The book’s running example is Table 11.19, six
subjects rated by four judges, also in AMCP. Here is nonzero, so the
ordinary aov() route works, and we compute all four Shrout
and Fleiss coefficients from the mean squares.
HideShow
data(chapter_11_table_19)
chapter_11_table_19$Subject <- factor(chapter_11_table_19$Subject)
chapter_11_table_19$Judge <- factor(chapter_11_table_19$Judge)
# Mean squares from the Subject + Judge ANOVA on the ratings.
sf <- summary(aov(Rating ~ Subject + Judge, data = chapter_11_table_19))[[1]]
MS_S <- sf["Subject", "Mean Sq"]
MS_A <- sf["Judge", "Mean Sq"]
MS_AxS <- sf["Residuals", "Mean Sq"]
n_19 <- nlevels(chapter_11_table_19$Subject) # subjects (6)
a_19 <- nlevels(chapter_11_table_19$Judge) # judges (4)
# Single-judge coefficients (Equations 11.51 and 11.52).
icc_2_1 <- (MS_S - MS_AxS) / (MS_S + (a_19 - 1) * MS_AxS + a_19 * (MS_A - MS_AxS) / n_19)
icc_3_1 <- (MS_S - MS_AxS) / (MS_S + (a_19 - 1) * MS_AxS)
# Composite (a-judge average) coefficients (Equations 11.53 and 11.54).
icc_2_a <- (MS_S - MS_AxS) / (MS_S + (MS_A - MS_AxS) / n_19)
icc_3_a <- (MS_S - MS_AxS) / MS_S
cat(
"Single-judge ICC(2,1) Agreement:", round(icc_2_1, 2),
"\nSingle-judge ICC(3,1) Consistency:", round(icc_3_1, 2),
"\n\nComposite ICC(2,4) Agreement:", round(icc_2_a, 2),
"\nComposite ICC(3,4) Consistency (Cronbach's alpha):", round(icc_3_a, 2),
"\n"
)HideShow
Single-judge ICC(2,1) Agreement: 0.29
Single-judge ICC(3,1) Consistency: 0.71
Composite ICC(2,4) Agreement: 0.62
Composite ICC(3,4) Consistency (Cronbach's alpha): 0.91 The averaging gain is the Spearman-Brown prediction formula, which scales a single-judge reliability up to an -judge composite, :
HideShow
Spearman-Brown ICC(2,1) -> 4 judges: 0.62
Spearman-Brown ICC(3,1) -> 4 judges: 0.91 Averaging over four judges lifts consistency reliability from .71 for a single judge to .91 for the four-judge mean.
In DMAR: the four coefficients with confidence intervals
The formulas above give point estimates only. DMAR’s
icc() also returns the confidence intervals and the
significance test that Shrout and Fleiss describe, taking the
subjects-by-judges matrix directly.
HideShow
Judge1 Judge2 Judge3 Judge4
1 9 2 5 8
2 6 1 3 2
3 8 4 6 8
4 7 1 2 6
5 10 5 6 9
6 6 2 4 7HideShow
type value ci_lower ci_upper F_value df_1 df_2 p_value
ICC(2,1) 0.290 0.019 0.761 11.027 5 15 0.0001
Confidence level: 95%
type value ci_lower ci_upper F_value df_1 df_2 p_value
ICC(3,1) 0.715 0.342 0.946 11.027 5 15 0.0001
Confidence level: 95%
type value ci_lower ci_upper F_value df_1 df_2 p_value
ICC(2,k) 0.620 0.071 0.927 11.027 5 15 0.0001
Confidence level: 95%
type value ci_lower ci_upper F_value df_1 df_2 p_value
ICC(3,k) 0.909 0.676 0.986 11.027 5 15 0.0001
Confidence level: 95%The book notes (p. 631) that is equivalent to Cronbach’s alpha, which DMAR’s reliability family lets us check directly.
| term | value | ci_method |
|---|---|---|
| estimate | 0.909 | none |
| se | NA | none |
| ci_lower | NA | none |
| ci_upper | NA | none |
| conf_level | 0.950 | none |
| N | 6 | none |
| N_complete | 6 | none |
| n_items | 4 | none |
That equivalence is why is so often the reliability that behavioral measurement actually reports.
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 11: One-Way Within-Subjects Designs: Univariate Approach (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.
Fox J, Weisberg S, Price B (2026). car: Companion to Applied Regression. doi:10.32614/CRAN.package.car https://doi.org/10.32614/CRAN.package.car. R package version 3.1-5, https://CRAN.R-project.org/package=car.
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.
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/.
Ripley B, Venables B (2026). MASS: Support Functions and Datasets for Venables and Ripley’s MASS. doi:10.32614/CRAN.package.MASS https://doi.org/10.32614/CRAN.package.MASS. R package version 7.3-66, https://CRAN.R-project.org/package=MASS.
Robinson D, Hayes A, Couch S, Hvitfeldt E (2026). broom: Convert Statistical Objects into Tidy Tibbles. doi:10.32614/CRAN.package.broom https://doi.org/10.32614/CRAN.package.broom. R package version 1.0.13, https://CRAN.R-project.org/package=broom.
Sjoberg D, Larmarange J, Curry M, de la Rua E, Lavery J, Whiting K, Zabor E (2026). gtsummary: Presentation-Ready Data Summary and Analytic Result Tables. doi:10.32614/CRAN.package.gtsummary https://doi.org/10.32614/CRAN.package.gtsummary. R package version 2.5.1, https://CRAN.R-project.org/package=gtsummary.
Wickham H (2023). tidyverse: Easily Install and Load the ‘Tidyverse’. doi:10.32614/CRAN.package.tidyverse https://doi.org/10.32614/CRAN.package.tidyverse. R package version 2.0.0, https://CRAN.R-project.org/package=tidyverse.