Chapter 11: One-Way Within-Subjects Designs: Univariate Approach

R Code and Instructions

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

Code
Results
On this page

Examples follow the book’s section numbers.

Chapter 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 tables

11.5 — Analysis of Repeated-Measures Designs with Two Levels

11.5.1 — The Problem of Correlated Errors

When moving from a between-subjects design to a within-subjects (repeated-measures) design, the fundamental assumption of independent errors is violated. Because the same subjects are measured across multiple conditions, a subject who naturally scores high in Condition 1 is likely to score high in Condition 2.

Tables 11.1 and 11.2 in the text illustrate this by calculating the error for each subject (eij=Yij−Y‾je_{ij} = Y_{ij} – \bar{Y}_j). We can use R to replicate this and demonstrate the severe correlation between the errors across the two conditions.

HideShow
# Load the Chapter 11 Table 1 data
data(chapter_11_table_1)

# Display structure and data
str(chapter_11_table_1)
HideShow
'data.frame':   6 obs. of  2 variables:
 $ YCondition1: int  8 3 12 5 7 13
 $ YCondition2: int  10 6 13 9 8 14
HideShow
chapter_11_table_1
HideShow
  YCondition1 YCondition2
1           8          10
2           3           6
3          12          13
4           5           9
5           7           8
6          13          14
HideShow
# Calculate Condition Means
mean_Y1 <- mean(chapter_11_table_1$YCondition1)
mean_Y2 <- mean(chapter_11_table_1$YCondition2)
cat("Condition means:", mean_Y1, "and", mean_Y2, "\n")
HideShow
Condition means: 8 and 10 
HideShow
#> 8 and 10 — matches Table 11.1, book p. 592

# Calculate the Errors (e_ij = Y_ij - Condition Mean)
e1 <- chapter_11_table_1$YCondition1 - mean_Y1
e2 <- chapter_11_table_1$YCondition2 - mean_Y2

# Calculate the correlation between the errors (Table 11.2)
cor_errors <- cor(e1, e2)
cat("Correlation between errors across conditions:", round(cor_errors, 2), "\n")
HideShow
Correlation between errors across conditions: 0.96 
HideShow
#> .96 — matches book p. 592 ("the correlation between e_i1 and e_i2 ... .96 here")

Because standard ANOVA is not robust to violations of the independence assumption, we must reformulate our model to handle this dependency.

11.5.2 — Reformulation of Model

To eliminate the correlated errors, we transform the two scores per subject into a single difference score (DiD_i).Di=Yi2−Yi1D_i = Y_{i2} – Y_{i1}

This reduces the model to a single parameter representing the mean difference:Di=μD+εiD_i = \mu_D + \varepsilon_i

Because there is now only one observation (εi\varepsilon_i) per subject, the dependency among errors is removed. Our null hypothesis simplifies to testing whether the population mean difference is zero (H0:μD=0H_0: \mu_D = 0).

We can replicate the step-by-step model comparison shown in Table 11.3 by calculating the full-model error (EFE_F) and restricted-model error (ERE_R) 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
cat("Restricted Error (E_R):", E_R, "\n")
HideShow
Restricted Error (E_R): 32 
HideShow
cat("Full Error (E_F):", E_F, "\n")
HideShow
Full Error (E_F): 8 
HideShow
cat("F statistic:", F_stat, "\n")
HideShow
F statistic: 15 
HideShow
#> sum(D) = 12, E_R = 32, E_F = 8, F = 15.0 — matches Table 11.3, book p. 595

# The book compares this to a critical F with 1 and n - 1 degrees of freedom.
cat("Critical F(.05; 1, 5):", round(qf(0.95, df1 = 1, df2 = n - 1), 2), "\n")
HideShow
Critical F(.05; 1, 5): 6.61 
HideShow
#> 6.61 — matches book p. 595, so H0 is rejected at the .05 level

Because this FF test has a single numerator degree of freedom, it is mathematically identical to a dependent (paired) tt 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 Y2−Y1Y_2 – Y_1, which is the direction of DD in Table 11.3.

HideShow
# Paired samples t test, in the direction D = Y2 - Y1 used in Table 11.3
paired_t <- t.test(
  x           = chapter_11_table_1$YCondition2,
  y           = chapter_11_table_1$YCondition1,
  paired      = TRUE,
  alternative = "two.sided",
  conf.level  = 0.95
)
paired_t
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
# The square of the t value is exactly the F value above
cat("t =", round(paired_t$statistic, 4), " t^2 =", round(paired_t$statistic^2, 2), "\n")
HideShow
t = 3.873  t^2 = 15 
HideShow
#> t = 3.873, t^2 = 15.0 — the same F as Table 11.3, book p. 595

As shown, t2=Ft^2 = F, so for a two-level repeated-measures design the model-comparison approach and the paired tt test are the same test. The mean difference of D‾=2\bar{D} = 2 is what Equation 11.18 standardizes.

In DMAR: an exact test that does not assume normality

The paired tt test assumes the difference scores are normally distributed, which is a strong assumption with n=6n = 6. DMAR’s randomization_test_paired() returns an exact pp value obtained by enumerating all 2n2^n 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 y−xy – x, 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 D=Y2−Y1D = Y_2 – Y_1.

HideShow
# Exact sign-flip randomization test on the same six pairs
randomization_test_paired(
  x           = chapter_11_table_1$YCondition1,
  y           = chapter_11_table_1$YCondition2,
  statistic   = "mean",
  alternative = "two_sided",
  exact       = TRUE
)
term value
statistic 2.000
p_value 0.0312
n_pairs 6
n_evaluated 64
exact 1
HideShow
#> statistic = 2 — the same mean difference D_bar the t test reports

Both routes reject at the .05 level, and the mean difference is identical. The randomization pp value is coarser than the tt test’s because with six pairs there are only 26=642^6 = 64 sign patterns, so the smallest attainable two-sided pp value is 2/64=.0312/64 = .031. 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 FF test is the interaction of the two, MSA×SMS_{A \times S}. This interaction measures how inconsistently the treatment effect behaves across subjects. Dropping the (πα)ij(\pi\alpha)_{ij} terms from Equations 11.20 and 11.21 gives the two models that are actually compared:

Full (11.22): Yij=μ+αj+πi+εijRestricted (11.23): Yij=μ+πi+εij\text{Full (11.22): } Y_{ij} = \mu + \alpha_j + \pi_i + \varepsilon_{ij} \qquad \text{Restricted (11.23): } Y_{ij} = \mu + \pi_i + \varepsilon_{ij}

with dfF=(n−1)(a−1)df_F = (n-1)(a-1) and dfR=n(a−1)df_R = n(a-1), so that dfR−dfF=a−1df_R – df_F = a – 1.

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
# Load the Chapter 11 Table 5 data
data(chapter_11_table_5)
str(chapter_11_table_5)
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
chapter_11_table_5
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      130
HideShow
# 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
cat("Condition Means:\n", round(condition_means, 2), "\n\n")
HideShow
Condition Means:
 103 107 110 112 
HideShow
cat("Grand Mean:", round(grand_mean, 2), "\n")
HideShow
Grand Mean: 108 
HideShow
#> condition means 103, 107, 110, 112 and grand mean 108 — match Table 11.5, book p. 598
#> subject means 109, 120, 104, 90, 121, 101, 127, 97, 94, 101, 109, 123 — match p. 598

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 (ERE_R, Equation 11.25): no age effect. The predicted score for a child is that child’s own mean across all ages.

  • Full model (EFE_F, 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
cat("Restricted model, column sums (Table 11.9):", colSums(sq_error_restricted), "\n")
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
cat("Full Error (E_F):", E_F, "\n")
HideShow
Full Error (E_F): 2006 
HideShow
cat("SS_A = E_R - E_F:", E_R - E_F, "\n")
HideShow
SS_A = E_R - E_F: 552 
HideShow
cat("F statistic:", round(F_stat, 2), "\n")
HideShow
F statistic: 3.03 
HideShow
#> E_F = SS_AxS = 2006 — matches book p. 600; E_R = 2558 — matches book p. 601
#> SS_A = 552 and F(3, 33) = 3.03 — match book p. 602

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      107
HideShow
str(C11_T5_PP)
HideShow
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 MSA×SMS_{A \times S} error term we computed by hand.

HideShow
# Run the repeated-measures ANOVA
Repeated_Measures_ANOVA <- aov(Values ~ Month + Error(ID/Month), data = C11_T5_PP)
summary(Repeated_Measures_ANOVA)
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 ' ' 1
HideShow
#> Month: SS = 552, MS = 184.0, F = 3.027, p = .0432 — matches book p. 602
#> Residuals (A x S): SS = 2006, MS = 60.79 — matches book p. 602

The same source table laid out APA-style, with sums of squares, df, mean squares, the omnibus F, its p value, and partial η2\eta^2. The error term for the age effect is the Age ×\times Subjects interaction, so partial η2\eta^2 is SSA/(SSA+SSA×S)SS_A / (SS_A + SS_{A \times S}). 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 &eta;<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


HideShow
#> SS_S = 6624 (book p. 609), SS_A = 552 and SS_AxS = 2006 (book p. 602)

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 EFE_F and ERE_R we computed by hand, and comparing them with anova() returns the same FF as the repeated-measures table above.

HideShow
# Full model (Eq 11.22): subjects + age. Restricted model (Eq 11.23): subjects only.
fit_full       <- lm(Values ~ ID + Month, data = C11_T5_PP)
fit_restricted <- lm(Values ~ ID,         data = C11_T5_PP)

cat("E_F (full residual SS)       =", round(sum(resid(fit_full)^2), 2), "\n")
HideShow
E_F (full residual SS)       = 2006 
HideShow
cat("E_R (restricted residual SS) =", round(sum(resid(fit_restricted)^2), 2), "\n")
HideShow
E_R (restricted residual SS) = 2558 
HideShow
#> E_F = 2006 (book p. 600) and E_R = 2558 (book p. 601)

# The model comparison reproduces the omnibus F(3, 33) = 3.03 from the ANOVA.
anova(fit_restricted, fit_full)
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 ' ' 1
HideShow
#> Sum of Sq = 552, F = 3.027, p = .0432 — matches book p. 602

A 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
modelsummary(
  list("Subjects only (restricted)" = fit_restricted,
       "Subjects + Age (full)"      = fit_full),
  estimate  = "{estimate}",
  statistic = "({std.error})",                 # standard errors in parentheses
  coef_omit = "ID",                            # hide the 11 subject dummies
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  output    = "gt"
)
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
HideShow
#> Month36 = 4, Month42 = 7, Month48 = 9 — the Table 11.5 age means minus 103, book p. 598

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.

HideShow
tbl_regression(fit_full, include = "Month") |>
  modify_caption("**Age effect (full model), relative to 30 months**")
Age effect (full model), relative to 30 months
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 (Yl−YmY_l – Y_m), 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σYl−Ym2=σYl2+σYm2−2ρlmσYlσYm\sigma^2_{Y_l-Y_m} = \sigma^2_{Y_l} + \sigma^2_{Y_m} – 2\rho_{lm}\sigma_{Y_l}\sigma_{Y_m}

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 (σ2\sigma^2) and all correlations between treatments are equal to each other (ρ\rho), as in Equations 11.31 and 11.32. Then the variance of a difference reduces to 2σ2(1−ρ)2\sigma^2(1-\rho), 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 for each Month
sample_vars <- apply(chapter_11_table_5, MARGIN = 2, FUN = var)
cat("Sample Variances:\n")
HideShow
Sample Variances:
HideShow
round(sample_vars, 2)
HideShow
Months30 Months36 Months42 Months48 
  188.00   200.55   178.00   218.00 
HideShow
#> 188.00, 200.55, 178.00, 218.00 — match book p. 603

# Table 11.10: Correlation Matrix
cor_matrix <- cor(chapter_11_table_5)
round(cor_matrix, 3)
HideShow
         Months30 Months36 Months42 Months48
Months30    1.000    0.795    0.696    0.599
Months36    0.795    1.000    0.760    0.466
Months42    0.696    0.760    1.000    0.853
Months48    0.599    0.466    0.853    1.000
HideShow
#> .795, .696, .599, .760, .466, .853 — match Table 11.10, book p. 604

The correlation between adjacent time points (42 and 48 months: .853.853) is much higher than between distant time points (36 and 48 months: .466.466). 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.64
HideShow
#> 79.82, 91.27, 59.82, 111.27, 223.64, 163.64 — match Table 11.11, book p. 604

Because these variances range from 59.8259.82 to 223.64223.64, 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.

HideShow
# Mauchly's test of sphericity on the four month columns (Table 11.5)
mauchly_test(chapter_11_table_5[, c("Months30", "Months36", "Months42", "Months48")])
W statistic df p_value n_subjects n_levels method
0.243 13.768 5 0.0177 12 4 Mauchly’s test of sphericity
HideShow
#> W = 0.243, p = .018 — the same statistic car::Anova reports in Section 11.9.2

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 FF value. The adjustment is based on Box’s measure of departure from sphericity, ε\varepsilon (epsilon).

  • Perfect sphericity: ε=1.0\varepsilon = 1.0

  • Maximum violation: ε=1/(a−1)\varepsilon = 1 / (a-1)

Multiplying the degrees of freedom by ε\varepsilon shrinks them, which raises the critical FF and makes the test more conservative. The observed FF itself never changes: all four approaches in this section use F=MSA/MSA×S=3.03F = MS_A / MS_{A \times S} = 3.03.

11.9.1 — Lower-Bound Adjustment

Geisser and Greenhouse (1958) showed that the smallest possible value of ε\varepsilon in an aa-level design is 1/(a−1)1/(a-1). Substituting that lower bound into Box’s adjusted degrees of freedom gives 11 and n−1n-1, which for these data is 1 and 11.

HideShow
a <- ncol(chapter_11_table_5)  # 4 conditions
n <- nrow(chapter_11_table_5)  # 12 subjects

cat("Lower bound for epsilon, 1/(a - 1):", round(1 / (a - 1), 2), "\n")
HideShow
Lower bound for epsilon, 1/(a - 1): 0.33 
HideShow
cat("Critical F(.05; 1, n - 1):", round(qf(0.95, df1 = 1, df2 = n - 1), 2), "\n")
HideShow
Critical F(.05; 1, n - 1): 4.84 
HideShow
#> epsilon = .33 and critical F = 4.84 — match book p. 606

The observed FF of 3.03 is well below 4.84, so the null hypothesis is not rejected under this very conservative approach.

11.9.2 — ε̂\hat{\varepsilon} Adjustment

Greenhouse and Geisser’s ε̂\hat{\varepsilon} estimates the population ε\varepsilon from the sample covariance matrix. Its computational formula is tedious, but car::Anova() reports it (along with ε̃\tilde{\varepsilon}) 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 ε̂\hat{\varepsilon} 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_summary
HideShow

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.06353773
HideShow
#> unadjusted F(3, 33) = 3.027, p = .0432 — matches book p. 602
#> Mauchly W = 0.243, p = .018 — the same test DMAR reported in Section 11.8.2
HideShow
eps_GG <- rm_summary$pval.adjustments["Month", "GG eps"]
eps_HF <- rm_summary$pval.adjustments["Month", "HF eps"]

cat("GG epsilon-hat:", round(eps_GG, 3), "\n")
HideShow
GG epsilon-hat: 0.61 
HideShow
cat("Adjusted df from the book's rounded .61:", 0.61 * (a - 1), "and", 0.61 * (a - 1) * (n - 1), "\n")
HideShow
Adjusted df from the book's rounded .61: 1.83 and 20.13 
HideShow
cat("Critical F at those df:", round(qf(0.95, df1 = 1.83, df2 = 20.13), 2), "\n")
HideShow
Critical F at those df: 3.59 
HideShow
#> epsilon-hat = .61, df = 1.83 and 20.13, critical F = 3.59 — match book p. 606

The observed FF of 3.03 is still below 3.59, so the null hypothesis is not rejected with the ε̂\hat{\varepsilon} approach either. (R’s exact ε̂\hat{\varepsilon} 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 — ε̃\tilde{\varepsilon} Adjustment

Huynh and Feldt’s ε̃\tilde{\varepsilon} corrects the tendency of ε̂\hat{\varepsilon} to underestimate ε\varepsilon, so it is always at least as large and the test is less conservative. Equation 11.34 gives it as a function of ε̂\hat{\varepsilon}, which we can confirm directly.

HideShow
# Equation 11.34, from epsilon-hat
eps_HF_formula <- (n * (a - 1) * eps_GG - 2) / ((a - 1) * (n - 1 - (a - 1) * eps_GG))

cat("HF epsilon-tilde from car:        ", round(eps_HF, 4), "\n")
HideShow
HF epsilon-tilde from car:         0.7249 
HideShow
cat("HF epsilon-tilde from Eq. 11.34:  ", round(eps_HF_formula, 4), "\n")
HideShow
HF epsilon-tilde from Eq. 11.34:   0.7249 
HideShow
cat("Adjusted df:", round(eps_HF * (a - 1), 2), "and", round(eps_HF * (a - 1) * (n - 1), 2), "\n")
HideShow
Adjusted df: 2.17 and 23.92 
HideShow
cat("Critical F at those df:", round(qf(0.95, df1 = eps_HF * (a - 1),
                                        df2 = eps_HF * (a - 1) * (n - 1)), 2), "\n")
HideShow
Critical F at those df: 3.32 
HideShow
#> epsilon-tilde = .72, df = 2.17 and 23.92, critical F = 3.32 — match book p. 607

Again the observed FF 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 F=MSA/MSA×S=3.03F = MS_A / MS_{A \times S} = 3.03; 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
HideShow
#> critical F values 2.89, 3.32, 3.59, 4.84 — match Table 11.12, book p. 608

The adjusted pp values are the modern equivalent of looking up those critical values, and car::Anova() reports them.

HideShow
data.frame(
  Adjustment  = c("Greenhouse-Geisser", "Huynh-Feldt"),
  epsilon     = round(c(eps_GG, eps_HF), 4),
  adjusted_p  = round(c(rm_summary$pval.adjustments[1, "Pr(>F[GG])"],
                        rm_summary$pval.adjustments[1, "Pr(>F[HF])"]), 4)
)
HideShow
          Adjustment epsilon adjusted_p
1 Greenhouse-Geisser  0.6095     0.0748
2        Huynh-Feldt  0.7249     0.0635
HideShow
#> GG-adjusted p = .0748 and HF-adjusted p = .0635
#> The book reports critical values rather than these p values (pp. 606-608);
#> both routes reach the same decision, since the observed F of 3.03 falls short.

The unadjusted test is significant at .05, but the book recommends against ever using it (p. 607), and recommends ε̂\hat{\varepsilon} 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 FF 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 pp values together.

HideShow
# Omnibus F with no adjustment plus GG, HF, and lower-bound corrections
anova_within(chapter_11_table_5[, c("Months30", "Months36", "Months42", "Months48")])
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
HideShow
#> F = 3.027 throughout; GG eps = .610 with df 1.829 / 20.115; HF eps = .725 with
#> df 2.175 / 23.920; lower-bound eps = .333 with df 1 / 11 — the same quantities
#> car::Anova produced above, and the book's Table 11.12 structure (p. 608)

The agreement with car::Anova() confirms the calculation from two independent implementations.

11.10 — Measures of Effect

A statistically significant pp 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 dd).

Omega squared (ω̂2\hat{\omega}^2)

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ω̂2=(a−1)(MSA−MSA×S)SSTotal+MSS\hat{\omega}^2 = \frac{(a-1)(MS_A – MS_{A \times S})}{SS_{Total} + MS_S}

The denominator requires SSTotalSS_{Total} and MSSMS_S (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
cat("Sum of Squares Subjects (SS_S):", round(SS_S, 2), "\n")
HideShow
Sum of Squares Subjects (SS_S): 6624 
HideShow
cat("Total Sum of Squares (SS_Total):", round(SS_Total, 2), "\n\n")
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 
HideShow
#> .04 — matches book p. 609

So the age effect accounts for approximately 4% of the total population variance in McCarthy scores.

Standardized mean differences (dd)

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 MSA×S\sqrt{MS_{A \times S}}, because that is the error term for the FF test. But subject variance has been partialed out of it, so the denominator is artificially small and the resulting dd is not comparable to a dd 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 (SSSSS_S) and the error variance (SSA×SSS_{A \times S}) back together. That is Equation 11.38:

sd=SSS+SSA×Sa(n−1)sd = \sqrt{\frac{SS_S + SS_{A \times S}}{a(n-1)}}

HideShow
# Calculate the comparable between-subjects standard deviation (Equation 11.38)
sd_pooled <- sqrt((SS_S + SS_AxS) / (a * (n - 1)))
cat("Reconstructed Standard Deviation (sd):", round(sd_pooled, 2), "\n")
HideShow
Reconstructed Standard Deviation (sd): 14 
HideShow
#> 14.00 — matches book p. 611

# The book notes this equals the square root of the MSW we would compute if the
# data were treated as between-subjects: the mean of the four level variances.
cat("sqrt(mean of the four level variances):", round(sqrt(mean(sample_vars)), 2), "\n")
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
cat("Effect Size (d) - 48 vs 30 months:", round(d_48_vs_30, 2), "\n")
HideShow
Effect Size (d) - 48 vs 30 months: 0.64 
HideShow
#> 0.29 and 0.64 — match book p. 611

# The alternative, and inferior, denominator
cat("\nsqrt(MS_AxS):", round(sqrt(MS_AxS), 2),
    " d(48 vs 30) using it:", round((mean_48 - mean_30) / sqrt(MS_AxS), 2), "\n")
HideShow

sqrt(MS_AxS): 7.8  d(48 vs 30) using it: 1.15 
HideShow
#> sqrt(MS_AxS) = 7.80 — matches book p. 611, "only a little more than half" of 14.00

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 MSA×S=7.80\sqrt{MS_{A \times S}} = 7.80 instead, the same 9-point difference would have been reported as d=1.15d = 1.15, 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):

SSψ=nψ̂2∑cj2,F=SSψMSA×SSS_\psi = \frac{n\hat{\psi}^2}{\sum c_j^2}, \qquad F = \frac{SS_\psi}{MS_{A \times S}}

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 ψ̂=9\hat{\psi} = 9 we have already verified against the Table 11.5 marginal means.

HideShow
psi_hat   <- mean_48 - mean_30          # 112 - 103
c_squared <- 1^2 + (-1)^2               # pairwise contrast coefficients

SS_psi <- n * psi_hat^2 / c_squared
F_psi  <- SS_psi / MS_AxS

cat("psi-hat:", psi_hat, " SS_psi:", SS_psi, " F:", round(F_psi, 3), "\n")
HideShow
psi-hat: 9  SS_psi: 486  F: 7.995 
HideShow
# Critical values from Equations 11.41 and 11.42, plus per-comparison and Bonferroni
cat("\nPer-comparison F(.05; 1, 33):   ", round(qf(0.95, 1, (a - 1) * (n - 1)), 3), "\n")
HideShow

Per-comparison F(.05; 1, 33):    4.139 
HideShow
cat("Bonferroni, C = 6 comparisons:  ", round(qf(1 - 0.05 / 6, 1, (a - 1) * (n - 1)), 3), "\n")
HideShow
Bonferroni, C = 6 comparisons:   7.878 
HideShow
cat("Tukey, q^2 / 2 (Eq. 11.41):     ",
    round(qtukey(0.95, a, (a - 1) * (n - 1))^2 / 2, 3), "\n")
HideShow
Tukey, q^2 / 2 (Eq. 11.41):      7.317 
HideShow
cat("Scheffe, (a - 1)F (Eq. 11.42):  ",
    round((a - 1) * qf(0.95, a - 1, (a - 1) * (n - 1)), 3), "\n")
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 MSA×S=60.79MS_{A \times S} = 60.79 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 MSA×SMS_{A \times S} 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 ε̂\hat{\varepsilon} and ε̃\tilde{\varepsilon} 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 FF 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:ψ̂±wMSA×S∑j=1a(cj2/nj)\hat{\psi} \pm w \sqrt{ MS_{A \times S} \sum_{j=1}^{a} (c_j^2 / n_j) }

The degrees of freedom for ww are the residual dfdf from the ANOVA, (a−1)(n−1)=33(a-1)(n-1) = 33.

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 
HideShow
#> 6.48 — matches Table 11.13, book p. 614

2. Separate error interval. Equation 11.44 replaces the pooled MSA×SMS_{A \times S} with Var(Yl−Ym)/2Var(Y_l – Y_m)/2, an error term specific to the two levels being compared, and the degrees of freedom for ww drop to n−1n – 1.

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.13
HideShow
#> mu4 - mu3: 2.00 +/- 6.48 pooled, 2.00 +/- 4.91 separate
#> mu4 - mu1: 9.00 +/- 6.48 pooled, 9.00 +/- 8.13 separate
#> all four margins and both estimates match Table 11.13, book p. 614

The 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
# Load the four-condition within-subjects data (Table 11.4)
data(chapter_11_table_4)
four <- chapter_11_table_4
colnames(four) <- c("C1", "C2", "C3", "C4")
four
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  5
HideShow
# 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 tt statistic, and a confidence interval for every comparison, all in one tidy table, taken straight from the wide data.

HideShow
# All pairwise within-subjects comparisons, separate variances, Bonferroni-adjusted
pairwise_within(four[, c("C1", "C2", "C3", "C4")], adjust = "bonferroni")
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%

HideShow
#> adjusted p values reproduce pairwise.t.test() above: C4 - C1 < .0001,
#> C3 - C1 = .026, C4 - C2 = .027, and the other three not significant

The two routes agree on every adjusted pp 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,σYl−Ym2=σYl2+σYm2−2ρlmσYlσYm\sigma^2_{Y_l – Y_m} = \sigma^2_{Y_l} + \sigma^2_{Y_m} – 2\rho_{lm}\sigma_{Y_l}\sigma_{Y_m}

We can show in R how ρ\rho 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
cat("Variance of Y4 - Y1 (rho = .2):", var_diff_low, "\n")
HideShow
Variance of Y4 - Y1 (rho = .2): 360 
HideShow
#> 90 and 360 — match book p. 617; the first comparison is one-fourth as variable

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 n=50n = 50 subjects. Every level has population mean 50 except level 2, whose mean is 54, so the true value of μ2−μ1\mu_2 – \mu_1 is 4 and the true value of μ4−μ1\mu_4 – \mu_1 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 MSA×SMS_{A \times S}) 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.

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 (μ4−μ1\mu_4 – \mu_1, 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 (μ2−μ1\mu_2 – \mu_1, 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
cat("\nIntervals containing the true value of mu2 - mu1 (4):\n"); print(coverage(s21, 4))
HideShow

Intervals containing the true value of mu2 - mu1 (4):
HideShow
  Pooled Separate 
       9        8 
HideShow
cat("\nMean half-width, mu4 - mu1: pooled",
    round(mean(s41$Pooled_hi - s41$Pooled_lo) / 2, 2),
    " separate", round(mean(s41$Separate_hi - s41$Separate_lo) / 2, 2), "\n")
HideShow

Mean half-width, mu4 - mu1: pooled 3.74  separate 5.43 
HideShow
cat("Mean half-width, mu2 - mu1: pooled",
    round(mean(s21$Pooled_hi - s21$Pooled_lo) / 2, 2),
    " separate", round(mean(s21$Separate_hi - s21$Separate_lo) / 2, 2), "\n")
HideShow
Mean half-width, mu2 - mu1: pooled 3.74  separate 2.62 

With this seed, the separate-variance intervals contain the true value of μ4−μ1\mu_4 – \mu_1 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      20
HideShow
#> 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 
HideShow
#> control mean 15, strategy mean 20, apparent 5-point effect — matches book p. 618
#> the control-first group improves by 10 points, which the book reads as the
#> more plausible estimate of the true effect (p. 618)

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: a=4a = 4 conditions have 4!=244! = 24 orders, and a=5a = 5 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 from Table 11.17 (book p. 621)
sq3 <- matrix(
  c("A", "B", "C", "D",
    "B", "A", "D", "C",
    "C", "D", "B", "A",
    "D", "C", "A", "B"),
  nrow = 4, byrow = TRUE
)
cat("Standard Square 3:\n")
HideShow
Standard Square 3:
HideShow
print(sq3)
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
#> matches Square 3 of Table 11.17, book p. 621

# The book's worked permutation: rows in the order 3, 1, 4, 2 ...
cat("\nAfter the book's row permutation (3, 1, 4, 2):\n")
HideShow

After the book's row permutation (3, 1, 4, 2):
HideShow
print(sq3[c(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
#> C D B A / A B C D / D C A B / B A D C — matches book p. 620

# ... then columns in the order 3, 4, 1, 2.
cat("\nAfter the book's column permutation (3, 4, 1, 2):\n")
HideShow

After the book's column permutation (3, 4, 1, 2):
HideShow
print(sq3[c(3, 1, 4, 2), c(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" 
HideShow
#> B A C D / C D A B / A B D C / D C B A — matches book p. 620

In practice the permutation is drawn at random rather than chosen, which R does in two lines.

HideShow
set.seed(113)

row_perm <- sample(1:4)
col_perm <- sample(1:4)

randomized_square <- sq3[row_perm, col_perm]

cat(
  "Row Permutation Order:", row_perm,
  "\nCol Permutation Order:", col_perm,
  "\n\nRandomized Latin Square:\n"
)
HideShow
Row Permutation Order: 1 2 4 3 
Col Permutation Order: 3 1 2 4 

Randomized Latin Square:
HideShow
print(randomized_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
# Each treatment still appears exactly once in each position.
apply(randomized_square, MARGIN = 2, FUN = function(x) sort(x))
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 a=4a = 4 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 (NWN_W) to that in a between-subjects posttest-only design (NBN_B), assuming any position effects have been modeled (Equation 11.45), and to a pretest-posttest design analyzed with ANCOVA (Equation 11.46):

NW=NB(1−ρ)2NW=NPP2(1+ρ)N_W = \frac{N_B(1 – \rho)}{2} \qquad\qquad N_W = \frac{N_{PP}}{2(1+\rho)}

Where ρ\rho 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              20
HideShow
#> 128 / 128 / 256 / 64, 128 / 117 / 180 / 45, 128 / 96 / 128 / 32, 128 / 66 / 77 / 20
#> all sixteen cells match Table 11.18, book p. 623

The sample sizes are rounded up, since a design cannot use a fraction of a subject; at ρ=0.3\rho = 0.3 and ρ=0.7\rho = 0.7 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 ρ=0.7\rho = 0.7, 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 ρ=0\rho = 0), 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 (ρ\rho) between the repeated measures. When scores are positively correlated, the error variance shrinks, so the noncentrality parameter (λ\lambda) 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:λ=Nf2\lambda = N f^2

Within-subjects:λ=anf21−ρ\lambda = \frac{an f^2}{1-\rho}

For power of .80 to detect a medium effect (f=0.25f = 0.25) across a=3a = 3 conditions, the book reports that a between-subjects design requires N=159N = 159 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 ρ\rho.

HideShow
# Constants for the design
f <- 0.25      # Medium effect size
a_power <- 3   # Number of conditions

# Scenario 1: Between-subjects
N_between <- 159
lambda_between <- N_between * f^2
cat("Between-subjects lambda:", lambda_between, "\n")
HideShow
Between-subjects lambda: 9.9375 
HideShow
cat("Critical F(.05; 2, 156):", round(qf(0.95, df1 = 2, df2 = N_between - a_power), 3), "\n")
HideShow
Critical F(.05; 2, 156): 3.054 
HideShow
cat("Power:", round(pf(qf(0.95, 2, N_between - a_power), df1 = 2, df2 = N_between - a_power,
                       ncp = lambda_between, lower.tail = FALSE), 3), "\n")
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
cat("Required n for the within-subjects design (rho = 0.5):",
    n_for_rho(0.5), "-> round up to", ceiling(n_for_rho(0.5)), "\n")
HideShow
Required n for the within-subjects design (rho = 0.5): 26.5 -> round up to 27 

When ρ=0\rho = 0, the within-subjects design needs 53 subjects in total to reach the same λ\lambda 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 ρ=0.5\rho = 0.5, 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 ε̂\hat{\varepsilon}-adjusted test is used. The closed form lands slightly lower because equating λ\lambda to the between-subjects value ignores the degrees of freedom the within-subjects test actually has. The book also notes that at ρ=0\rho = 0 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 f=0.25f = 0.25), 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 ε̂\hat{\varepsilon}-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 N=33N = 33 “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 FF statistic no longer follows a noncentral FF 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 ε\varepsilon 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
#> 0.25 — matches book p. 627, and the f of the two scenarios above

# Equation 11.50: lambda = a * n * f^2 / (1 - rho-bar)
rho_bar      <- mean(R_power[upper.tri(R_power)])
lambda_power <- a_power * n_power * f_implied^2 / (1 - rho_bar)
cat("Average of the off-diagonal correlations:", rho_bar, "\n")
HideShow
Average of the off-diagonal correlations: 0.5 
HideShow
cat("Equation 11.50 noncentrality:", lambda_power, "\n")
HideShow
Equation 11.50 noncentrality: 12.375 
HideShow
#> rho-bar = 0.5, so lambda = 12.375 — Equation 11.50, book p. 626

The design parameters check out against the book: means of 10, 13, and 16 with a population variance of 96 imply f=0.25f = 0.25 (book p. 627), and Equation 11.50 with a=3a = 3, n=33n = 33, f2=.0625f^2 = .0625, and ρ‾=.5\bar{\rho} = .5 gives 3×33×.0625/(1−.5)=12.3753 \times 33 \times .0625 / (1 – .5) = 12.375.

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 FF has expectation tr(Σ*)/(a−1)\mathrm{tr}(\Sigma^{*}) / (a – 1), where Σ*\Sigma^{*} is the covariance matrix of a set of orthonormal contrasts among the conditions, and that quantity equals σ2(1−ρ‾)\sigma^2 (1 – \bar{\rho}) for any correlation matrix. Building Σ*\Sigma^{*} also gives us ε\varepsilon, 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
cat("sigma^2 * (1 - rho-bar):   ", var_power * (1 - rho_bar), "\n")
HideShow
sigma^2 * (1 - rho-bar):    48 
HideShow
#> both 48 — the average correlation reproduces the error term exactly

# Box's epsilon for the population covariance matrix
eps_pop <- sum(diag(Sigma_star))^2 / (b_df * sum(Sigma_star^2))
cat("Population epsilon:        ", round(eps_pop, 4), "\n")
HideShow
Population epsilon:         0.8621 
HideShow
#> 0.8621 — sphericity fails, but not badly (epsilon = 1 would be sphericity)

So λ=12.375\lambda = 12.375 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, 𝑀𝑆A×S\mathit{MS}_{A \times S} is a weighted sum of chi-square variables rather than a single scaled one, and ε\varepsilon is exactly the summary of Σ*\Sigma^{*} 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 ε\varepsilon, never from λ\lambda.

Quantity 1 — the power Equation 11.50 implies

Equation 11.50 gave λ\lambda exactly. If the design were compound symmetric with every correlation at ρ‾=.5\bar{\rho} = .5, the unadjusted mixed-model FF test would be distributed as a noncentral F(a−1,(a−1)(n−1))F(a – 1, (a-1)(n-1)) with that λ\lambda, and its power would be a plain tail probability needing nothing beyond qf() and pf().

HideShow
df1_un  <- a_power - 1                      # 2
df2_un  <- (a_power - 1) * (n_power - 1)    # 64
crit_un <- qf(0.95, df1 = df1_un, df2 = df2_un)

power_un <- pf(crit_un, df1 = df1_un, df2 = df2_un,
               ncp = lambda_power, lower.tail = FALSE)
cat("Critical F(.05; 2, 64):", round(crit_un, 3), "\n")
HideShow
Critical F(.05; 2, 64): 3.14 
HideShow
cat("Power implied by Equation 11.50 at n = 33:", round(power_un, 4), "\n")
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 (f=0.25f = 0.25) behaves like an effective f≈0.44f \approx 0.44, with ηp2≈0.16\eta_p^2 \approx 0.16, 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, 𝑀𝑆A×S\mathit{MS}_{A \times S} is a weighted sum of chi-square variables, so the ratio is not a noncentral FF 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 Σ\Sigma 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 
HideShow
#> .8288 (SE .0017) — about .827, five points below the .8776 above

So under the book’s own correlation matrix the unadjusted test has power of about .827 at n=33n = 33, 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 ρ‾=.5\bar{\rho} = .5 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 ε\varepsilon treated as known

The textbook correction multiplies both degrees of freedom by ε\varepsilon. If we pretend ε\varepsilon 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
df1_known <- b_df * eps_pop
df2_known <- b_df * (n_power - 1) * eps_pop

power_gg_known <- pf(qf(0.95, df1 = df1_known, df2 = df2_known),
                     df1 = df1_known, df2 = df2_known,
                     ncp = lambda_power * eps_pop, lower.tail = FALSE)
cat("GG power with epsilon treated as known:", round(power_gg_known, 4), "\n")
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 ε\varepsilon. 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 ε\varepsilon is unknown, and the test that actually gets run substitutes ε̂\hat{\varepsilon} computed from the very same data that produce FF.

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 ε̂\hat{\varepsilon} and FF are computed from the same sample, they are not independent, and the power is not a single noncentral FF 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 Σ*\Sigma^{*}, and the critical value is taken at an approximation to E[ε̂]\mathrm{E}[\hat{\varepsilon}] rather than at ε\varepsilon. 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
cat("Rescaled df1, df2, lambda:", round(gg_33$nu1_star, 3),
    round(gg_33$nu2_star, 3), round(gg_33$lambda, 3), "\n")
HideShow
Rescaled df1, df2, lambda: 1.447 55.172 8.954 
HideShow
cat("GG power of the test actually run, at n = 33:", round(gg_33$power, 4), "\n")
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 
HideShow
#> .8268 — the closed-form counterpart of the simulated .8288 in Quantity 1,
#> and five points below the .8776 that Equation 11.50 implies

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 Σ\Sigma 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 E[ε̂]\mathrm{E}[\hat{\varepsilon}] 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 ε̂\hat{\varepsilon} 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 
HideShow
#> 0.81 — moving the critical value recovers .0056 of the .0339 drop, a sixth

So the bias in ε̂\hat{\varepsilon} is real but mild, and it is not where the conservatism mostly comes from. The larger part is in the rescaling: λ*=8.954\lambda^{*} = 8.954 against Quantity 2’s λε=10.668\lambda \varepsilon = 10.668, and 𝑑𝑓1*=1.447\mathit{df}_1^{*} = 1.447 against 1.724. That rescaling is the approximation’s way of carrying the dependence between ε̂\hat{\varepsilon} and FF — the two are built from the same sums of squares, so a sample that happens to inflate FF 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 E[ε̂]\mathrm{E}[\hat{\varepsilon}] 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 nn subjects, computes its own ε̂\hat{\varepsilon}, 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
set.seed(113)
hits <- replicate(reps_power,
                  omnibus_reject(n_power, mu_power, Sigma_power, U_power,
                                 correction = "GG"))

cat("Simulated GG power at n = 33:", round(mean(hits), 4),
    "  Monte Carlo SE:",
    round(sqrt(mean(hits) * (1 - mean(hits)) / reps_power), 4), "\n")
HideShow
Simulated GG power at n = 33: 0.806   Monte Carlo SE: 0.0018 
HideShow
#> .806 (SE .0018) — agrees with the UNIREP .8045 and with book p. 627

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 N=33N = 33 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 ε̂\hat{\varepsilon} 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 N=33N = 33, within its own Monte Carlo error.

Solving for the sample size

Nothing above solves for nn, 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
#> 28 — matches the compound-symmetric rho = .50 requirement, book p. 627
cat("Unadjusted test under the printed matrix:           ", n_unadjusted, "\n")
HideShow
Unadjusted test under the printed matrix:            31 
HideShow
#> 31 — the unequal-correlation requirement for the same unadjusted test
cat("Epsilon-hat-adjusted test, printed matrix:          ", n_adjusted, "\n")
HideShow
Epsilon-hat-adjusted test, printed matrix:           33 
HideShow
#> 33 — matches book p. 627
# The two routes compared at the same sample size, n = 31
n_31   <- 31
lam_31 <- a_power * n_31 * f_implied^2 / (1 - rho_bar)
cat("Unadjusted test at n = 31, under the printed matrix:",
    round(power_unirep(mu_power, Sigma_power, n_31,
                       test = "uncorrected")$power, 4), "\n")
HideShow
Unadjusted test at n = 31, under the printed matrix: 0.8022 
HideShow
cat("The same test at n = 31, as Equation 11.50 sees it: ",
    round(pf(qf(0.95, df1 = a_power - 1, df2 = (a_power - 1) * (n_31 - 1)),
             df1 = a_power - 1, df2 = (a_power - 1) * (n_31 - 1),
             ncp = lam_31, lower.tail = FALSE), 4), "\n")
HideShow
The same test at n = 31, as Equation 11.50 sees it:  0.8544 
HideShow
#> .8022 delivered against .8544 credited
cat("GG power at n = 32 and n = 33:",
    round(power_unirep(mu_power, Sigma_power, 32, test = "GG")$power, 4), "and",
    round(power_unirep(mu_power, Sigma_power, 33, test = "GG")$power, 4), "\n")
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 ε̂\hat{\varepsilon}-adjusted test”; solving the noncentral FF for power ≥\geq .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 ε̂\hat{\varepsilon}-adjusted test (p. 627), and the search reaches it because n=32n = 32 gives .7914 and n=33n = 33 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 ε̂\hat{\varepsilon}-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).

HideShow
# M = frequency * duration + 1 = 5 measurement occasions, target width 0.025:
ss_aipe_pcm(true_var_trend = 0.003, true_var_error = 0.0262,
            duration = 4, frequency = 1, width = 0.025, conf_level = 0.95)
term value
necessary_n_per_group 278

Confidence level: 95%

HideShow
#> 278 per group; DMAR documents this as Kelley and Rausch (2011, Table 1, M = 5)

# Doubling the occasions to M = 10 sharpens the slope estimate:
ss_aipe_pcm(true_var_trend = 0.003, true_var_error = 0.0262,
            duration = 9, frequency = 1, width = 0.025, conf_level = 0.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%

HideShow
#> 295 per group; DMAR documents this as Kelley and Rausch (2011, Table 2, M = 5)

For the power-analytic counterpart, ss_power_pcm() solves for the nn that detects a given slope difference with target power.

HideShow
ss_power_pcm(true_std_reg_coef = -0.40, true_var_trend = 0.003, true_var_error = 0.0262,
             frequency = 1, duration = 4, desired_power = 0.80)
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
HideShow
#> 185 per group, 370 in total, achieved power .801; DMAR documents this as the
#> Raudenbush and Liu (2001) National Youth Survey illustration

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: ICC(2,1)=MSS−MSA×SMSS+(a−1)MSA×S+a(MSA−MSA×S)/nICC(2,1) = \frac{MS_S – MS_{A \times S}}{MS_S + (a-1)MS_{A \times S} + a(MS_A – MS_{A \times S})/n}

  • Case 3 (consistency), Equation 11.52: ICC(3,1)=MSS−MSA×SMSS+(a−1)MSA×SICC(3,1) = \frac{MS_S – MS_{A \times S}}{MS_S + (a-1)MS_{A \times S}}

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 MSA×S=0MS_{A \times S} = 0 and the usual FF tests are undefined. We therefore read the mean squares straight off the two-way decomposition rather than from an FF table.

HideShow
data(chapter_11_table_20)

# Reshape the ratings into the subjects-by-judges layout the book prints
ratings_20 <- chapter_11_table_20 |>
  pivot_wider(names_from = Judge, values_from = Rating, names_prefix = "Judge") |>
  column_to_rownames("Subject") |>
  as.matrix()
ratings_20
HideShow
  Judge1 Judge2 Judge3
1      9      5     11
2      6      2      8
3      8      4     10
4      7      3      9
5      4      0      6
HideShow
#> 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
#> 11.10, 46.67, 0.00 — match book p. 630

icc_2_1 <- (MS_S - MS_AxS) / (MS_S + (a - 1) * MS_AxS + a * (MS_A - MS_AxS) / n)
icc_3_1 <- (MS_S - MS_AxS) / (MS_S + (a - 1) * MS_AxS)

cat("ICC(2,1) Agreement:  ", round(icc_2_1, 2), "\n")
HideShow
ICC(2,1) Agreement:   0.28 
HideShow
cat("ICC(3,1) Consistency:", round(icc_3_1, 2), "\n")
HideShow
ICC(3,1) Consistency: 1 
HideShow
#> .28 and 1.00 — match book p. 630

Consistency is perfect, so ICC(3,1)=1.00ICC(3,1) = 1.00. Agreement is poor, because the judges use very different parts of the scale, and ICC(2,1)ICC(2,1) 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 MSA×SMS_{A \times S} 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 
HideShow
#> ICC(2,1) = .29 and ICC(3,1) = .71 — match book p. 630
#> ICC(2,4) = .62 and ICC(3,4) = .91 — match book p. 631

The averaging gain is the Spearman-Brown prediction formula, which scales a single-judge reliability up to an aa-judge composite, aρ1+(a−1)ρ\frac{a\,\rho}{1 + (a-1)\rho}:

HideShow
spearman_brown <- function(rho, k) (k * rho) / (1 + (k - 1) * rho)
cat("Spearman-Brown ICC(2,1) -> 4 judges:", round(spearman_brown(icc_2_1, a_19), 2),
    "\nSpearman-Brown ICC(3,1) -> 4 judges:", round(spearman_brown(icc_3_1, a_19), 2), "\n")
HideShow
Spearman-Brown ICC(2,1) -> 4 judges: 0.62 
Spearman-Brown ICC(3,1) -> 4 judges: 0.91 
HideShow
#> reproduces the composite ICC(2,4) = .62 and ICC(3,4) = .91 from Equations 11.53-11.54

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
ratings_19 <- chapter_11_table_19 |>
  pivot_wider(names_from = Judge, values_from = Rating, names_prefix = "Judge") |>
  column_to_rownames("Subject") |>
  as.matrix()
ratings_19
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      7
HideShow
#> matches Table 11.19, book p. 628

for (case in c("ICC(2,1)", "ICC(3,1)", "ICC(2,k)", "ICC(3,k)")) {
  print(icc(ratings_19, type = case, conf_level = 0.95))
}
HideShow
 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%
HideShow
#> point estimates .290, .715, .620, .909 — the same four coefficients computed by
#> hand above, and matching the book's .29, .71 (p. 630) and .62, .91 (p. 631)

The book notes (p. 631) that ICC(3,k)ICC(3,k) is equivalent to Cronbach’s alpha, which DMAR’s reliability family lets us check directly.

HideShow
reliability_alpha(data = as.data.frame(ratings_19), ci_method = "none")
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
HideShow
#> alpha = .909 — the same value as ICC(3,4) above, confirming the equivalence

That equivalence is why ICC(3,k)ICC(3,k) 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

Scroll to Top