Chapter 12: Higher-Order Designs with Within-Subjects Factors: 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 12 expands on univariate analysis techniques by exploring higher-order experimental designs that incorporate at least one within-subjects factor. The first major section focuses on designs utilizing two within-subjects factors, detailing the procedures for omnibus tests, investigating main effects and interactions, and evaluating necessary statistical assumptions. The text then transitions to mixed designs that combine one within-subjects factor with one between-subjects factor, explaining the unique error terms and restricted models required for accurate analysis. For both of these foundational designs, the chapter provides guidance on conducting follow-up investigations, such as testing simple effects, calculating interaction contrasts, and applying adjusted univariate tests. Finally, the chapter concludes with practical guidelines for power analysis and sample size planning, alongside strategies for handling more complex arrangements like Latin Square designs.

Chapter 1 covers the R groundwork these notes take for granted: installing packages from CRAN, loading them, and the way the book’s data sets are named. This chapter draws on five of them — chapter_12_table_1, chapter_12_table_7, chapter_12_table_11, chapter_12_table_15, and chapter_12_table_29. data(package = "AMCP") lists every data set in the package.

HideShow
# Load all of the packages used.
library(tidyverse)      # data wrangling and plotting (dplyr, tidyr, ggplot2, and friends)
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(effectsize)     # effect sizes (eta-squared, omega-squared)
library(emmeans)        # estimated marginal means and contrasts
library(car)            # Anova() for Type II/III tests and regression diagnostics
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

12.2 — Designs with Two Within-Subjects Factors

Load the data for Table 12.1 from the AMCP package.

HideShow
data(chapter_12_table_1)

First, we need to change the structure of the data. We use PP here to denote “person-period”, which means that the data will be in the “univariate” (or “long”) form from the “multivariate” form it is currently in. We find the easiest way to do this is with tidyr and dplyr, both of which the library(tidyverse) call above has already attached.

HideShow
# Add an ID variable (by row number)
C12_T1_PP <- chapter_12_table_1
C12_T1_PP$ID <- as.factor(1:nrow(C12_T1_PP))

# View the names
names(chapter_12_table_1)
HideShow
[1] "Absent0"  "Absent4"  "Absent8"  "Present0" "Present4" "Present8"
HideShow
# Reshape the data to long format
# The columns representing conditions (e.g., abs0, pres8) are collapsed.
# We separate the condition name into "Noise" and "Angle" by pulling the last
# character (the angle) into its own column.
C12_T1_PP <- C12_T1_PP %>%
  pivot_longer(
    cols = -ID,
    names_to = c("Noise", "Angle"),
    names_pattern = "(Absent|Present)(\\d+)",
    values_to = "Reaction_Time"
  ) %>%
  arrange(ID, Noise, Angle)

# Ensure our factors are treated categorically by R
C12_T1_PP$Angle <- as.factor(C12_T1_PP$Angle)
C12_T1_PP$Noise <- as.factor(C12_T1_PP$Noise)

# Display the first few rows of the restructured data
head(C12_T1_PP)
HideShow
# A tibble: 6 × 4
  ID    Noise   Angle Reaction_Time
  <fct> <fct>   <fct>         <int>
1 1     Absent  0               420
2 1     Absent  4               420
3 1     Absent  8               480
4 1     Present 0               480
5 1     Present 4               600
6 1     Present 8               780
HideShow
str(C12_T1_PP)
HideShow
tibble [60 × 4] (S3: tbl_df/tbl/data.frame)
 $ ID           : Factor w/ 10 levels "1","2","3","4",..: 1 1 1 1 1 1 2 2 2 2 ...
 $ Noise        : Factor w/ 2 levels "Absent","Present": 1 1 1 2 2 2 1 1 1 2 ...
 $ Angle        : Factor w/ 3 levels "0","4","8": 1 2 3 1 2 3 1 2 3 1 ...
 $ Reaction_Time: int [1:60] 420 420 480 480 600 780 420 480 480 360 ...

12.2.1 — Omnibus Tests

The omnibus questions addressed in this factorial design are the same as those for a two-way between-subjects design: we want to test the main effect of Angle, the main effect of Noise, and the Angle ×\times Noise interaction.

However, because the factors are entirely within-subjects, the choice of the error term changes. The general rule for fixed factors in a within-subjects design is that the appropriate error term for any effect is the interaction of that effect with the random Subjects (SS) factor. This is Equation 12.5 of the book (p. 649):

F=MSeffectMSeffect×SF = \frac{MS_{effect}}{MS_{effect \times S}}

Using base R’s aov() function, we specify the expected mean squares error structure using the Error() wrapper. Error(ID/(Angle*Noise)) correctly maps the error strata so that the main effects and interactions are tested against their respective subject-interaction terms.

12.2.2 — Numerical Example

Before the omnibus tests, the cell means and marginal means of Table 12.4 give the picture the tests will be about.

HideShow
# Table 12.4: cell means, with the Angle and Noise marginal means.
C12_T1_PP |>
  group_by(Angle, Noise) |>
  summarize(Mean_RT = mean(Reaction_Time), .groups = "drop") |>
  pivot_wider(names_from = Noise, values_from = Mean_RT) |>
  mutate(`Marginal Means` = (Absent + Present) / 2)
HideShow
# A tibble: 3 × 4
  Angle Absent Present `Marginal Means`
  <fct>  <dbl>   <dbl>            <dbl>
1 0        462     492              477
2 4        510     660              585
3 8        528     762              645
HideShow
#> 462, 492, 477 / 510, 660, 585 / 528, 762, 645 — matches Table 12.4, book p. 649

C12_T1_PP |>
  group_by(Noise) |>
  summarize(Mean_RT = mean(Reaction_Time), .groups = "drop")
HideShow
# A tibble: 2 × 2
  Noise   Mean_RT
  <fct>     <dbl>
1 Absent      500
2 Present     638
HideShow
#> 500 (absent) and 638 (present) — matches Table 12.4, book p. 649
HideShow
Repeated_Measures_ANOVA <- aov(Reaction_Time ~ Angle + Noise + Angle*Noise +
                               Error(ID/(Angle*Noise)), data=C12_T1_PP)

aov_summary <- summary(Repeated_Measures_ANOVA)
summary(Repeated_Measures_ANOVA)
HideShow

Error: ID
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  9 292140   32460               

Error: ID:Angle
          Df Sum Sq Mean Sq F value   Pr(>F)    
Angle      2 289920  144960   40.72 2.09e-07 ***
Residuals 18  64080    3560                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: ID:Noise
          Df Sum Sq Mean Sq F value   Pr(>F)    
Noise      1 285660  285660   33.77 0.000256 ***
Residuals  9  76140    8460                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: ID:Angle:Noise
            Df Sum Sq Mean Sq F value   Pr(>F)    
Angle:Noise  2 105120   52560   45.31 9.42e-08 ***
Residuals   18  20880    1160                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> A: SS = 289,920, MS = 144,960, F = 40.72; A x S: SS = 64,080, MS = 3,560
#> B: SS = 285,660, MS = 285,660, F = 33.77; B x S: SS = 76,140, MS = 8,460
#> A x B: SS = 105,120, MS = 52,560, F = 45.31; A x B x S: SS = 20,880, MS = 1,160
#> all of the above match Table 12.5, book p. 650

Notice from the output that both main effects (Angle and Noise) and the Angle ×\times Noise interaction are highly statistically significant (p<.05p < .05).

The same results as an APA-style table reproduce Table 12.5. Each within-subjects effect sits above its own subject-by-effect error stratum, so the table keeps the error rows next to the effects they test. summary() of a multi-stratum aov() returns one ANOVA table per error stratum, so building a single table means walking the strata and carrying each one’s label along.

HideShow
# Pull every stratum of the aov summary into one tidy frame, keeping the
# stratum label so the error rows can be paired with the effects they test.
# Each element of the summary is a one-element list holding that stratum's table.
aov_rows <- purrr::imap_dfr(aov_summary, function(stratum_tables, stratum) {
  as.data.frame(stratum_tables[[1]]) |>
    tibble::rownames_to_column("Source") |>
    dplyr::mutate(Stratum = stratum)
})

aov_rows |>
  dplyr::transmute(
    Source = dplyr::if_else(trimws(Source) == "Residuals",
                            paste0("Error (", sub("Error: ", "", Stratum), ")"),
                            trimws(Source)),
    SS = `Sum Sq`, df = Df, MS = `Mean Sq`,
    Fstat = `F value`, p = `Pr(>F)`
  ) |>
  gt() |>
  fmt_number(columns = c(SS, MS), decimals = 0) |>
  fmt_number(columns = Fstat, decimals = 2) |>
  fmt_number(columns = p, decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*")) |>
  tab_header(title = md("**Table 12.5**. ANOVA for the Two Within-Subjects Factors")) |>
  cols_align(align = "center", columns = -Source)
Table 12.5. ANOVA for the Two Within-Subjects Factors
Source SS df MS F p
Error (ID) 292,140 9 32,460

Angle 289,920 2 144,960 40.72 0.0000
Error (ID:Angle) 64,080 18 3,560

Noise 285,660 1 285,660 33.77 0.0003
Error (ID:Noise) 76,140 9 8,460

Angle:Noise 105,120 2 52,560 45.31 0.0000
Error (ID:Angle:Noise) 20,880 18 1,160

Measures of effect: partial ω̂2\hat{\omega}^2

While the FF-values are large, we want to calculate the partial ω̂2\hat{\omega}^2 to understand the magnitude of these effects in a way that is comparable to a single-factor between-subjects design (partialling out other effects except the subjects effect).

The book provides Equation 12.6 for this calculation: ω̂2=dfeffect(MSeffect−MSeffect×S)SSeffect+SSeffect×S+SSS+MSS\hat{\omega}^2 = \frac{df_{effect}(MS_{effect} – MS_{effect \times S})}{SS_{effect} + SS_{effect \times S} + SS_S + MS_S}

HideShow
# Note: it is arguably more efficient but less reproducible to just manually type the parameters

# Extract Subject Variance (From the "Error: ID" stratum)
# Note: We pull the Sum Sq and Mean Sq from the "Residuals" row of this stratum
SS_S <- aov_summary$`Error: ID`[[1]]["Residuals", "Sum Sq"]
MS_S <- aov_summary$`Error: ID`[[1]]["Residuals", "Mean Sq"]
#> SS_S = 292,140 and MS_S = 32,460, the values stated below Table 12.5 (book p. 650)

# Extract Values for Main Effect of A (Angle)
df_A   <- aov_summary$`Error: ID:Angle`[[1]]["Angle", "Df"]
SS_A   <- aov_summary$`Error: ID:Angle`[[1]]["Angle", "Sum Sq"]
MS_A   <- aov_summary$`Error: ID:Angle`[[1]]["Angle", "Mean Sq"]
SS_AxS <- aov_summary$`Error: ID:Angle`[[1]]["Residuals", "Sum Sq"]
MS_AxS <- aov_summary$`Error: ID:Angle`[[1]]["Residuals", "Mean Sq"]

omega2_A <- (df_A * (MS_A - MS_AxS)) / (SS_A + SS_AxS + SS_S + MS_S)

# Extract Values for Main Effect of B (Noise)
df_B   <- aov_summary$`Error: ID:Noise`[[1]]["Noise", "Df"]
SS_B   <- aov_summary$`Error: ID:Noise`[[1]]["Noise", "Sum Sq"]
MS_B   <- aov_summary$`Error: ID:Noise`[[1]]["Noise", "Mean Sq"]
SS_BxS <- aov_summary$`Error: ID:Noise`[[1]]["Residuals", "Sum Sq"]
MS_BxS <- aov_summary$`Error: ID:Noise`[[1]]["Residuals", "Mean Sq"]

omega2_B <- (df_B * (MS_B - MS_BxS)) / (SS_B + SS_BxS + SS_S + MS_S)

# Extract Values for the A x B Interaction (Angle:Noise)
df_AB   <- aov_summary$`Error: ID:Angle:Noise`[[1]]["Angle:Noise", "Df"]
SS_AB   <- aov_summary$`Error: ID:Angle:Noise`[[1]]["Angle:Noise", "Sum Sq"]
MS_AB   <- aov_summary$`Error: ID:Angle:Noise`[[1]]["Angle:Noise", "Mean Sq"]
SS_ABxS <- aov_summary$`Error: ID:Angle:Noise`[[1]]["Residuals", "Sum Sq"]
MS_ABxS <- aov_summary$`Error: ID:Angle:Noise`[[1]]["Residuals", "Mean Sq"]

omega2_AB <- (df_AB * (MS_AB - MS_ABxS)) / (SS_AB + SS_ABxS + SS_S + MS_S)

# print results
cat(
  "Partial Omega Squared for Angle (A):", round(omega2_A, 2),
  "\nPartial Omega Squared for Noise (B):", round(omega2_B, 2),
  "\nPartial Omega Squared for A x B Interaction:", round(omega2_AB, 2),
  "\n"
)
HideShow
Partial Omega Squared for Angle (A): 0.42 
Partial Omega Squared for Noise (B): 0.4 
Partial Omega Squared for A x B Interaction: 0.23 
HideShow
#> matches book p. 650: omega-squared = .42 (A), .40 (B), .23 (AB)
The same three values from effectsize

The hand calculation is worth doing once, because it makes plain which sums of squares Equation 12.6 draws on. For routine work the effectsize package reads the same quantities straight off the fitted aov object and reports a confidence interval alongside each estimate.

HideShow
# effectsize:: is written explicitly because DMAR also exports an
# omega_squared(); the qualifier keeps this call pointed at the effectsize version.
effectsize::omega_squared(Repeated_Measures_ANOVA, partial = TRUE)
HideShow
# Effect Size for ANOVA (Type I)

Group          |   Parameter | Omega2 (partial) |       95% CI
--------------------------------------------------------------
ID:Angle       |       Angle |             0.42 | [0.10, 1.00]
ID:Noise       |       Noise |             0.40 | [0.02, 1.00]
ID:Angle:Noise | Angle:Noise |             0.23 | [0.00, 1.00]

- One-sided CIs: upper bound fixed at [1.00].
HideShow
#> .42 (Angle), .40 (Noise), .23 (Angle:Noise) — the same three values, book p. 650
In DMAR: the sphericity bookkeeping in one call

With the base-R analysis in hand, the DMAR package supplies the ϵ\epsilon-adjusted tests that aov() does not print. anova_within_two_way() returns the three effects, each with its own subject-by-effect error term, and attaches to each the Greenhouse-Geisser and Huynh-Feldt corrections, the adjusted degrees of freedom, and the adjusted pp value. The unadjusted FF values are the ones already computed above, so the two routes can be read against each other. We name the outcome, the two within-subjects factors, and the subject identifier, keeping factor_A on Angle and factor_B on Noise so that DMAR’s A and B match the book’s.

HideShow
anova_within_two_way(
  data     = C12_T1_PP,
  outcome  = "Reaction_Time",
  factor_A = "Angle",
  factor_B = "Noise",
  subject  = "ID"
)
effect adjustment F_value df_1 df_2 p_value epsilon eta_squared_partial
A none 40.719 2 18 < 0.0001 NA 0.819
A Greenhouse-Geisser 40.719 1.923 17.309 < 0.0001 0.962 0.819
A Huynh-Feldt 40.719 2 18 < 0.0001 1.000 0.819
A lower_bound 40.719 1 9 0.0001 0.500 0.819
B none 33.766 1 9 0.0003 NA 0.790
B Greenhouse-Geisser 33.766 1 9 0.0003 1.000 0.790
B Huynh-Feldt 33.766 1 9 0.0003 1.000 0.790
B lower_bound 33.766 1 9 0.0003 1.000 0.790
A:B none 45.310 2 18 < 0.0001 NA 0.834
A:B Greenhouse-Geisser 45.310 1.808 16.272 < 0.0001 0.904 0.834
A:B Huynh-Feldt 45.310 2 18 < 0.0001 1.000 0.834
A:B lower_bound 45.310 1 9 < 0.0001 0.500 0.834
HideShow
#> unadjusted F = 40.72 (A), 33.77 (B), 45.31 (A:B) — Table 12.5, book p. 650
#> Greenhouse-Geisser epsilon = .962 (A), 1.000 (B), .904 (A:B), with adjusted
#> df 1.92 and 17.31 for A and 1.81 and 16.27 for A:B — Table 12.13, book p. 660

DMAR also carries a per-pair companion on the probability scale, which the book does not report: the probability that a randomly chosen subject scores higher in one condition than in the other, with a confidence interval that respects the pairing.

HideShow
# Noise present vs noise absent at an angle of 0 degrees:
probability_of_superiority_paired(x = chapter_12_table_1$Absent0,
                                  y = chapter_12_table_1$Present0,
                                  conf_level = 0.95)
term value
probability_of_superiority 0.650
ci_lower 0.353
ci_upper 0.864
var_ps 0.020
wins_y_over_x 6
losses_y_under_x 3
ties 1

Confidence level: 95%

HideShow
# An 8-degree angle vs a 0-degree angle within the noise-absent half:
probability_of_superiority_paired(x = chapter_12_table_1$Absent0,
                                  y = chapter_12_table_1$Absent8,
                                  conf_level = 0.95)
term value
probability_of_superiority 0.850
ci_lower 0.650
ci_upper 0.945
var_ps 0.005
wins_y_over_x 7
losses_y_under_x 0
ties 3

Confidence level: 95%

12.2.3 — Further Investigation of Main Effects

A significant main effect for a three-level quantitative factor invites a trend analysis. The book tests the quadratic trend among the Angle marginal means of 477, 585, and 645, with coefficients 1,−2,11, -2, 1, and shows that the choice of error term matters: Equation 12.7 divides by the pooled MSA×SMS_{A \times S}, while Equation 12.8 builds a separate error term from that one contrast.

As with the interaction contrast later in the chapter, the cleanest route is to reduce each subject to a single contrast score. Averaging over Noise first gives the per-subject Angle scores printed as Table 12.7; the quadratic combination of those three numbers is one value per subject.

HideShow
# Each subject's three Angle scores, averaged over Noise (Table 12.7).
angle_scores <- C12_T1_PP |>
  group_by(ID, Angle) |>
  summarize(Mean_RT = mean(Reaction_Time), .groups = "drop") |>
  pivot_wider(names_from = Angle, values_from = Mean_RT)

# One quadratic contrast score per subject.
quad_i <- 1 * angle_scores$`0` - 2 * angle_scores$`4` + 1 * angle_scores$`8`

n_subj <- length(quad_i)
b_lev  <- 2                        # levels of Noise, averaged over
sum_c2 <- 1^2 + (-2)^2 + 1^2       # = 6

mean(quad_i)
HideShow
[1] -48
HideShow
#> -48, i.e. 477 - 2(585) + 645 — matches book p. 651

# Equation 12.9: each A marginal mean rests on nb scores, so nb appears here.
SS_quad <- n_subj * b_lev * mean(quad_i)^2 / sum_c2
SS_quad
HideShow
[1] 7680
HideShow
#> 7,680 — matches book p. 651

MS_AxS      <- aov_summary$`Error: ID:Angle`[[1]]["Residuals", "Mean Sq"]
MS_Acomp_xS <- b_lev * var(quad_i) / sum_c2

c(MS_pooled = MS_AxS, MS_separate = MS_Acomp_xS)
HideShow
  MS_pooled MS_separate 
       3560        2880 
HideShow
#> 3,560 (Table 12.5) and 2,880 — matches book p. 651

c(F_pooled   = SS_quad / MS_AxS,           # Equation 12.7, 1 and 18 df
  F_separate = SS_quad / MS_Acomp_xS)      # Equation 12.8, 1 and 9 df
HideShow
  F_pooled F_separate 
  2.157303   2.666667 
HideShow
#> F = 2.16 and F = 2.67 — matches book p. 651; nonsignificant either way

Both tests are also available from packages a reader already has. emmeans gives Equation 12.7’s pooled test, and an ordinary one-sample t.test() on the contrast scores gives Equation 12.8’s separate-error test; squaring each tt returns the corresponding FF.

HideShow
# Pooled error term (Equation 12.7) via emmeans.
em_angle_2w <- emmeans(Repeated_Measures_ANOVA, ~ Angle)
quad_pooled <- contrast(em_angle_2w, list("Quadratic" = c(1, -2, 1)))
quad_pooled
HideShow
 contrast  estimate   SE df t.ratio p.value
 Quadratic      -48 32.7 18  -1.469  0.1592

Results are averaged over the levels of: Noise 
HideShow
as.data.frame(quad_pooled)$t.ratio^2
HideShow
[1] 2.157303
HideShow
#> 2.16 — the pooled F of Equation 12.7, book p. 651

# Separate error term (Equation 12.8): the contrast scores against zero.
quad_separate <- t.test(x = quad_i, mu = 0,
                        alternative = "two.sided", conf.level = 0.95)
quad_separate
HideShow

    One Sample t-test

data:  quad_i
t = -1.633, df = 9, p-value = 0.1369
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 -114.49357   18.49357
sample estimates:
mean of x 
      -48 
HideShow
quad_separate$statistic^2
HideShow
       t 
2.666667 
HideShow
#> 2.67 — the separate-error F of Equation 12.8, book p. 651

Because the separate-error route is an ordinary tt test, it also hands back a confidence interval on the quadratic trend itself, which neither FF ratio gives.

12.2.4 — Further Investigation of an Interaction—Simple Effects

Because we found a significant Angle ×\times Noise interaction, the logical next step is to examine the simple effects: testing the effect of Angle at each specific level of Noise, and the effect of Noise at each specific level of Angle.

This effectively reduces our two-way design into a series of one-way within-subjects designs. Each simple effect is literally a one-way within-subjects analysis of the subset of the data, which is why filtering and re-running aov() is the whole method.

HideShow
# Simple effect of Angle within Noise == Absent (A within B1)
Data_Noise_Abs <- C12_T1_PP %>% filter(Noise == "Absent")

Simple_Angle_w_Abs <- aov(Reaction_Time ~ Angle + Error(ID/Angle), data = Data_Noise_Abs)

summary(Simple_Angle_w_Abs)
HideShow

Error: ID
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  9 110400   12267               

Error: ID:Angle
          Df Sum Sq Mean Sq F value Pr(>F)  
Angle      2  23280   11640   5.046 0.0182 *
Residuals 18  41520    2307                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> SS = 23,280 for Angle (book p. 652) over an error SS of 41,520 (book p. 653),
#> giving F = 5.05 with 2 and 18 df and p = .018 — matches Table 12.6, book p. 653

We can repeat this process for the other four simple effects of Table 12.6:

HideShow
# Simple effect of Angle within Noise == Present (A within B2)
Data_Noise_Pres <- C12_T1_PP %>% filter(Noise == "Present")
summary(aov(Reaction_Time ~ Angle + Error(ID/Angle), data = Data_Noise_Pres))
HideShow

Error: ID
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  9 257880   28653               

Error: ID:Angle
          Df Sum Sq Mean Sq F value  Pr(>F)    
Angle      2 371760  185880   77.02 1.5e-09 ***
Residuals 18  43440    2413                    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 77.02 with 2 and 18 df — matches Table 12.6, book p. 653

# Simple effect of Noise at each level of Angle (B within A1, A2, A3)
for (deg in c("0", "4", "8")) {
  cat("\n--- Noise effect at Angle =", deg, "degrees ---\n")
  print(summary(aov(Reaction_Time ~ Noise + Error(ID/Noise),
                    data = filter(C12_T1_PP, Angle == deg))))
}
HideShow

--- Noise effect at Angle = 0 degrees ---

Error: ID
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  9  73620    8180               

Error: ID:Noise
          Df Sum Sq Mean Sq F value Pr(>F)
Noise      1   4500    4500   1.552  0.244
Residuals  9  26100    2900               

--- Noise effect at Angle = 4 degrees ---

Error: ID
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  9 123300   13700               

Error: ID:Noise
          Df Sum Sq Mean Sq F value  Pr(>F)   
Noise      1 112500  112500   19.74 0.00162 **
Residuals  9  51300    5700                   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

--- Noise effect at Angle = 8 degrees ---

Error: ID
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  9 159300   17700               

Error: ID:Noise
          Df Sum Sq Mean Sq F value   Pr(>F)    
Noise      1 273780  273780   125.6 1.38e-06 ***
Residuals  9  19620    2180                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 1.55 (p = .244), 19.74 (p = .002), and 125.59 (p = .001), each with 1 and
#> 9 df — matches Table 12.6, book p. 653

As reported in Table 12.6, the effect of Noise is not statistically significant at 0∘0^\circ (F=1.55,p=.244F = 1.55, p = .244), but Angle remains significant across both Noise conditions.

12.2.5 — Interaction Contrasts

Interaction contrasts provide an alternative method for investigating an interaction. In our two-way within-subjects design, we can represent a specific component of the interaction as a contrast among the abab means.

For example, suppose we want to test whether the difference between reaction times for 0∘0^\circ and 8∘8^\circ angles is the same when noise is present as when noise is absent. From Table 12.4 the mean difference is 270 ms when noise is present, but only 66 ms when absent.

The book computes this contrast from Equation 12.10. The quickest way to get both the contrast and its separate error term is to collapse each subject’s six scores into the single number the contrast asks about: the 0∘0^\circ-minus-8∘8^\circ difference under noise present, minus that same difference under noise absent. One number per subject, so the contrast is then a one-sample problem.

HideShow
# One contrast score per subject: (present 8 - present 0) - (absent 8 - absent 0).
psi_i <- with(chapter_12_table_1,
              (Present8 - Present0) - (Absent8 - Absent0))

n_subj  <- length(psi_i)
sum_c2  <- 1^2 + (-1)^2 + 1^2 + (-1)^2    # = 4 (the four nonzero weights)

psi_hat <- mean(psi_i)
psi_hat
HideShow
[1] 204
HideShow
#> 204, i.e. 270 - 66 from the cell means of Table 12.4 — matches book p. 654

SS_psi <- n_subj * psi_hat^2 / sum_c2
SS_psi
HideShow
[1] 104040
HideShow
#> 104,040 — matches book p. 654

# Equation 12.11 pools: it divides by MS_AxBxS from Table 12.5.
MS_ABxS   <- aov_summary$`Error: ID:Angle:Noise`[[1]]["Residuals", "Mean Sq"]
# Equation 12.12 uses a separate error term built from these contrast scores only.
MS_sep    <- var(psi_i) / sum_c2

c(MS_pooled = MS_ABxS, MS_separate = MS_sep)
HideShow
  MS_pooled MS_separate 
       1160        1240 
HideShow
#> 1,160 and 1,240 — matches book p. 654

c(F_pooled = SS_psi / MS_ABxS, F_separate = SS_psi / MS_sep)
HideShow
  F_pooled F_separate 
  89.68966   83.90323 
HideShow
#> F = 89.69 with 1 and 18 df, and F = 83.90 with 1 and 9 df — book p. 654

The mainstream route to the same pooled test is emmeans, which takes the contrast weights against the six cell means and reports a tt ratio rather than an FF. Squaring that tt returns Equation 12.11’s FF exactly, which is the agreement worth seeing:

HideShow
# Estimated marginal means for the six cells.
em_AB <- emmeans(Repeated_Measures_ANOVA, ~ Angle * Noise)
em_AB
HideShow
 Angle Noise   emmean SE   df lower.CL upper.CL
 0     Absent     462 29 19.8      402      522
 4     Absent     510 29 19.8      450      570
 8     Absent     528 29 19.8      468      588
 0     Present    492 29 19.8      432      552
 4     Present    660 29 19.8      600      720
 8     Present    762 29 19.8      702      822

Warning: EMMs are biased unless design is perfectly balanced 
Confidence level used: 0.95 
HideShow
# Weights go in the order the means are listed: abs0, abs4, abs8, pres0, pres4, pres8.
# These are the book's own coefficients: +1 on absent-0 and present-8, -1 on
# absent-8 and present-0, 0 on the two 4-degree cells.
interaction_comp <- list("(0 vs 8) x Noise" = c(1, 0, -1, -1, 0, 1))

ic <- contrast(em_AB, interaction_comp)
ic
HideShow
 contrast         estimate   SE df t.ratio p.value
 (0 vs 8) x Noise      204 21.5 18   9.470 <0.0001
HideShow
# Squaring the t ratio recovers the pooled F of Equation 12.11.
as.data.frame(ic)$t.ratio^2
HideShow
[1] 89.68966
HideShow
#> 89.69 — the same value as the hand calculation and as book p. 654

Note that emmeans gives the pooled test of Equation 12.11, because it draws its error term from the fitted model rather than from the contrast scores. Equation 12.12’s separate error term has to come from the contrast scores, as in the block above.

12.2.7 — Assumptions

The mixed-model approach requires the homogeneity assumption (sphericity). In a factorial design, we don’t just have one covariance matrix to check; we have a different covariance matrix for every omnibus effect we test!

Below, we reconstruct Tables 12.7 through 12.12 using R to evaluate the assumption for the A main effect, the B main effect, and the AB interaction.

Assumption for Factor A (Angle)

First, we average over the Noise condition to isolate the Angle effect (Table 12.7) and calculate its covariance/correlation matrix (Table 12.8).

HideShow
# Average over Noise (Table 12.7)
C12_T1_PP_Angle <- C12_T1_PP %>%
  group_by(ID, Angle) %>%
  summarize(Mean_Reaction_Time = mean(Reaction_Time), .groups = 'drop') %>%
  pivot_wider(names_from = Angle, values_from = Mean_Reaction_Time)
C12_T1_PP_Angle
HideShow
# A tibble: 10 × 4
   ID      `0`   `4`   `8`
   <fct> <dbl> <dbl> <dbl>
 1 1       450   510   630
 2 2       390   480   540
 3 3       570   630   660
 4 4       450   660   720
 5 5       510   660   630
 6 6       360   450   450
 7 7       510   600   720
 8 8       510   660   780
 9 9       510   660   660
10 10      510   540   660
HideShow
#> the ten rows and the column means of 477, 585, 645 match Table 12.7, book p. 656

# Covariance and correlation matrices for Factor A (Table 12.8)
var(C12_T1_PP_Angle[, -1])
HideShow
     0    4    8
0 4090 3950 4350
4 3950 6850 6150
8 4350 6150 8850
HideShow
#> variances 4,090 / 6,850 / 8,850 and covariances 3,950 / 4,350 / 6,150 —
#> matches Table 12.8, book p. 656
cor(C12_T1_PP_Angle[, -1])
HideShow
          0         4         8
0 1.0000000 0.7462600 0.7230294
4 0.7462600 1.0000000 0.7898747
8 0.7230294 0.7898747 1.0000000
HideShow
#> .75, .72, .79 — matches Table 12.8, book p. 656
Assumption for Factor B (Noise)

Next, we average over the Angle condition to isolate the Noise effect (Table 12.9) and calculate its matrices (Table 12.10). Because Noise has only two levels, the homogeneity of treatment-difference variances assumption is automatically met.

HideShow
# Average over Angle (Table 12.9)
C12_T1_PP_Noise <- C12_T1_PP %>%
  group_by(ID, Noise) %>%
  summarize(Mean_Reaction_Time = mean(Reaction_Time), .groups = 'drop') %>%
  pivot_wider(names_from = Noise, values_from = Mean_Reaction_Time)
C12_T1_PP_Noise
HideShow
# A tibble: 10 × 3
   ID    Absent Present
   <fct>  <dbl>   <dbl>
 1 1        440     620
 2 2        460     480
 3 3        500     740
 4 4        500     720
 5 5        580     620
 6 6        380     460
 7 7        520     700
 8 8        580     720
 9 9        560     660
10 10       480     660
HideShow
#> the column means of 500 and 638 match Table 12.9, book p. 657

# Covariance and correlation matrices for Factor B (Table 12.10)
var(C12_T1_PP_Noise[, -1])
HideShow
          Absent  Present
Absent  4088.889 4000.000
Present 4000.000 9551.111
HideShow
#> 4,088.89, 4,000.00, 9,551.11 — matches Table 12.10, book p. 657
cor(C12_T1_PP_Noise[, -1])
HideShow
           Absent   Present
Absent  1.0000000 0.6400743
Present 0.6400743 1.0000000
HideShow
#> .64 — matches Table 12.10, book p. 657
Assumption for the A x B Interaction

Finally, the interaction assesses whether the Noise difference is the same at each level of Angle. We calculate the difference scores (Present – Absent) for each angle (Table 12.11) and view their covariance (Table 12.12).

HideShow
# Calculate Noise effect (Present - Absent) at each Angle
C12_T1_PP_Difference <- chapter_12_table_1 %>%
  mutate(
    Dif_Angle0 = Present0 - Absent0,
    Dif_Angle4 = Present4 - Absent4,
    Dif_Angle8 = Present8 - Absent8
  ) %>%
  select(Dif_Angle0, Dif_Angle4, Dif_Angle8)
C12_T1_PP_Difference
HideShow
   Dif_Angle0 Dif_Angle4 Dif_Angle8
1          60        180        300
2         -60          0        120
3         180        300        240
4          60        240        360
5         -60          0        180
6           0         60        180
7          60        240        240
8          60        120        240
9         -60        120        240
10         60        240        240
HideShow
#> the ten rows and the column means of 30, 150, 234 match Table 12.11,
#> book p. 658

# Covariance and correlation matrices for the Interaction (Table 12.12)
var(C12_T1_PP_Difference)
HideShow
           Dif_Angle0 Dif_Angle4 Dif_Angle8
Dif_Angle0       5800       7000       2600
Dif_Angle4       7000      11400       5000
Dif_Angle8       2600       5000       4360
HideShow
#> variances 5,800 / 11,400 / 4,360 and covariances 7,000 / 2,600 / 5,000 —
#> matches Table 12.12, book p. 658
cor(C12_T1_PP_Difference)
HideShow
           Dif_Angle0 Dif_Angle4 Dif_Angle8
Dif_Angle0  1.0000000  0.8608582  0.5170304
Dif_Angle4  0.8608582  1.0000000  0.7092092
Dif_Angle8  0.5170304  0.7092092  1.0000000
HideShow
#> .86, .52, .71 — matches Table 12.12, book p. 658

12.2.8 — Adjusted Univariate Tests

Because sphericity is often violated in repeated measures designs, it is standard practice to apply ϵ\epsilon-adjustments (Geisser-Greenhouse ϵ̂\hat{\epsilon} or Huynh-Feldt ϵ̃\tilde{\epsilon}) to the degrees of freedom.

While calculating these by hand is tedious, the car package provides the Anova() function, which automatically calculates these adjusted pp-values for factorial within-subjects designs (reproducing Table 12.13).

HideShow
# To use car::Anova for repeated measures, we fit a multivariate linear model (mlm) using the wide-format data
multivariate_model <- lm(cbind(Absent0, Absent4, Absent8,
                               Present0, Present4, Present8) ~ 1,
                         data = chapter_12_table_1)

# Define the within-subjects design structure
idata <- expand.grid(Angle = factor(c(0, 4, 8)), Noise = factor(c("Absent", "Present")))

# Run the repeated measures ANOVA with sphericity corrections
car_anova <- Anova(multivariate_model, idata = idata, idesign = ~ Noise * Angle)

# Display the summary, which includes GG and HF epsilons and adjusted p-values
summary(car_anova, multivariate = FALSE)
HideShow

Univariate Type III Repeated-Measures ANOVA Assuming Sphericity

              Sum Sq num Df Error SS den Df F value    Pr(>F)    
(Intercept) 19425660      1   292140      9 598.449 1.527e-09 ***
Noise         285660      1    76140      9  33.766  0.000256 ***
Angle         289920      2    64080     18  40.719 2.087e-07 ***
Noise:Angle   105120      2    20880     18  45.310 9.424e-08 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


Mauchly Tests for Sphericity

            Test statistic p-value
Angle              0.96011 0.84972
Noise:Angle        0.89378 0.63814


Greenhouse-Geisser and Huynh-Feldt Corrections
 for Departure from Sphericity

             GG eps Pr(>F[GG])    
Angle       0.96164  3.402e-07 ***
Noise:Angle 0.90398  3.454e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

              HF eps   Pr(>F[HF])
Angle       1.217564 2.086763e-07
Noise:Angle 1.117870 9.424093e-08
HideShow
#> unadjusted F = 33.77 (Noise), 40.72 (Angle), 45.31 (interaction) — Table 12.5
#> GG epsilon = .96 (Angle) and .90 (interaction), HF = 1.22 and 1.12 before
#> being shrunk back to 1.00 — matches book p. 660

Notice that ϵ̂\hat{\epsilon} differs from one effect to the next: .96 for Angle and .90 for the interaction (book p. 660). car prints no row for Noise because that factor has only two levels, so there is a single difference score, sphericity holds by construction, and ϵ̂\hat{\epsilon} is necessarily 1.00 — the value the book reports for the BB main effect. The Huynh-Feldt ϵ̃\tilde{\epsilon} values of 1.22 and 1.12 both exceed 1.00 and are therefore shrunk back to 1.00, which is why the Huynh-Feldt and unadjusted pp values coincide. Because the omnibus effects are so strong, every adjusted pp value remains small.

In DMAR: each effect as its own one-way analysis

The book makes a point that is easy to state and easy to lose: each omnibus test in this design is a one-way within-subjects analysis of the right set of derived scores. A one-way analysis of the Table 12.7 scores (each subject’s reaction time at each angle, averaged over noise) returns the AA main effect, and a one-way analysis of the Table 12.11 scores (each subject’s noise effect at each angle) returns the ABAB interaction. DMAR’s anova_within() takes a wide matrix of repeated columns and returns that one-way FF with its ϵ\epsilon-adjusted companions, and mauchly_test() reports the sphericity test on the same matrix.

HideShow
# Table 12.7: the A main effect as a one-way within-subjects analysis.
mauchly_test(chapter_12_table_7[, c("Angle0", "Angle4", "Angle8")])
W statistic df p_value n_subjects n_levels method
0.960 0.326 2 0.8497 10 3 Mauchly’s test of sphericity
HideShow
anova_within(chapter_12_table_7[, c("Angle0", "Angle4", "Angle8")])
adjustment F_value df_1 df_2 p_value epsilon
none 40.719 2 18 < 0.0001 NA
Greenhouse-Geisser 40.719 1.923 17.309 < 0.0001 0.962
Huynh-Feldt 40.719 2 18 < 0.0001 1.000
lower_bound 40.719 1 9 0.0001 0.500
HideShow
#> F = 40.72 with GG epsilon = .962 — the A main effect of Table 12.5, as the
#> book states for these scores on p. 655, with the epsilon of book p. 660
HideShow
# Table 12.11: the AB interaction as a one-way within-subjects analysis.
data(chapter_12_table_11)
mauchly_test(chapter_12_table_11[, c("Angle0", "Angle4", "Angle8")])
W statistic df p_value n_subjects n_levels method
0.894 0.898 2 0.6381 10 3 Mauchly’s test of sphericity
HideShow
anova_within(chapter_12_table_11[, c("Angle0", "Angle4", "Angle8")])
adjustment F_value df_1 df_2 p_value epsilon
none 45.310 2 18 < 0.0001 NA
Greenhouse-Geisser 45.310 1.808 16.272 < 0.0001 0.904
Huynh-Feldt 45.310 2 18 < 0.0001 1.000
lower_bound 45.310 1 9 < 0.0001 0.500
HideShow
#> F = 45.31 with GG epsilon = .904 — the AB interaction of Table 12.5, as the
#> book states for these scores on p. 657, with the epsilon of book p. 660

12.2.9 — Confidence Intervals

Confidence intervals based on the traditional mixed-model approach are extremely sensitive to violations of the sphericity assumption. Because of this, it is generally recommended to use the multivariate approach (discussed in Chapter 14) to construct confidence intervals that do not require sphericity.

12.2.10 — Quasi-FF Ratios

Thus far, we have assumed that both Angle and Noise are fixed-effects factors. If one of our within-subjects factors was considered random (e.g., using different human raters/observers across conditions and wanting to generalize to a broader population of observers), the expected mean squares would change.

In such designs, standard FF-ratios are no longer appropriate for testing the fixed effect. Instead, a Quasi-F ratio (F′F' ) must be constructed by combining multiple mean squares in both the numerator and denominator:

F′=MSA+MSA×B×SMSA×S+MSA×BF' = \frac{MS_A + MS_{A \times B \times S}}{MS_{A \times S} + MS_{A \times B}}

Note: Mixed-effects models (e.g., via the lme4 package in R) provide a much more modern and flexible approach for handling designs with multiple crossed random factors than traditional Quasi-FF ratios.

12.3 — One Within-Subjects Factor and One Between-Subjects Factor in the Same Design

Often in the behavioral sciences, researchers use designs that mix both between-subjects and within-subjects factors. This is frequently called a split-plot design (a holdover from agricultural research) or a mixed design. This compromise offers the economy of a within-subjects design while minimizing problems like differential carryover or excessive participant burden.

To illustrate, we expand our perceptual psychology example. We are now interested in Age differences in task performance. * Factor A (Between-Subjects): Age (Young vs. Old) * Factor B (Within-Subjects): Angle (0∘,4∘,8∘0^\circ, 4^\circ, 8^\circ)

Because we cannot feasibly wait 40 years to test the same subjects longitudinally, Age must be a between-subjects factor. Angle remains a within-subjects factor.

To construct our dataset, we can pull the data directly from the AMCP package. chapter_12_table_15 provides the data for the 10 “Old” participants, and chapter_12_table_7 provides the data for the 10 “Young” participants (which was already averaged over the noise factor as instructed).

R Note: When analyzing mixed designs using base R’s aov() function, Subject IDs must be completely unique across the whole dataset. If Subject 1 in the Young group and Subject 1 in the Old group share the same ID “1”, R will mistakenly think they are the same person measured twice. Therefore, we assign IDs 1-10 to the Young group and 11-20 to the Old group before merging.

HideShow
# Load the datasets
data(chapter_12_table_7)
data(chapter_12_table_15)

# Prepare Data for Young Participants
young_data <- chapter_12_table_7 %>%
  mutate(Subject = factor(1:10),
         Age = factor("Young", levels = c("Young", "Old"))) %>%
  # We use names_prefix to automatically strip the word "Angle" from the column names
  pivot_longer(cols = starts_with("Angle"),
               names_to = "Angle",
               names_prefix = "Angle",
               values_to = "Reaction_Time")

# Prepare Data for Old Participants
old_data <- chapter_12_table_15 %>%
  mutate(Subject = factor(11:20),
         Age = factor("Old", levels = c("Young", "Old"))
  ) %>%
  pivot_longer(cols = starts_with("Angle"),
               names_to = "Angle",
               names_prefix = "Angle",
               values_to = "Reaction_Time")

# Combine into a single split-plot dataset
split_plot_data <- bind_rows(young_data, old_data) %>%
  mutate(Angle = factor(Angle, levels = c("0", "4", "8")))

# View cell and marginal means (Table 12.18)
split_plot_data %>%
  group_by(Age, Angle) %>%
  summarize(Mean_RT = mean(Reaction_Time), .groups = "drop") %>%
  pivot_wider(names_from = Angle, values_from = Mean_RT) %>%
  mutate(`Marginal Means` = (`0` + `4` + `8`) / 3)
HideShow
# A tibble: 2 × 5
  Age     `0`   `4`   `8` `Marginal Means`
  <fct> <dbl> <dbl> <dbl>            <dbl>
1 Young   477   585   645              569
2 Old     543   654   792              663
HideShow
#> 477, 585, 645, 569 (young) and 543, 654, 792, 663 (old) — matches Table 12.18,
#> book p. 668

split_plot_data %>%
  group_by(Angle) %>%
  summarize(Mean_RT = mean(Reaction_Time), .groups = "drop")
HideShow
# A tibble: 3 × 2
  Angle Mean_RT
  <fct>   <dbl>
1 0        510 
2 4        620.
3 8        718.
HideShow
#> 510, 619.5, 718.5 — matches Table 12.18, book p. 668

12.3.1 — Omnibus Tests

Just like in a fully between-subjects or fully within-subjects design, we want to test the two main effects (Age, Angle) and the interaction (Age ×\times Angle). However, because one factor is between and one is within, the full model and corresponding error terms change.

The Subjects factor (SS) is no longer crossed with the Age factor (AA). Instead, Subjects are nested under Age (S/AS/A). As a result, the error terms change:

  • The between-subjects effect (Age) is tested against the variability of Subjects nested within Age: MSS/AMS_{S/A}

  • The within-subjects effect (Angle) and the interaction (Age ×\times Angle) are both tested against the interaction of Angle with the nested subjects: MSB×S/AMS_{B \times S/A}

12.3.1.4 — Numerical Example

We specify this nested error structure in R using Error(Subject/Angle). Because R knows that Age is a between-subjects factor (each subject only has one age in our data), it will automatically assign the appropriate error terms to the appropriate strata.

HideShow
# Run the mixed ANOVA
Mixed_ANOVA <- aov(Reaction_Time ~ Age * Angle + Error(Subject/Angle), data = split_plot_data)

summary(Mixed_ANOVA)
HideShow

Error: Subject
          Df Sum Sq Mean Sq F value Pr(>F)  
Age        1 132540  132540   7.276 0.0147 *
Residuals 18 327900   18217                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: Subject:Angle
          Df Sum Sq Mean Sq F value  Pr(>F)    
Angle      2 435090  217545 143.911 < 2e-16 ***
Age:Angle  2  21090   10545   6.976 0.00275 ** 
Residuals 36  54420    1512                    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> A (Age): SS = 132,540, MS = 132,540, F = 7.28, p = .0147
#> S/A: SS = 327,900, MS = 18,217
#> B (Angle): SS = 435,090, MS = 217,545, F = 143.91
#> A x B: SS = 21,090, MS = 10,545, F = 6.98, p = .0028
#> B x S/A: SS = 54,420, MS = 1,511.67, printed as 1,512 in the book
#> all of the above match Table 12.19, book p. 668

The output shows that both main effects and the interaction are statistically significant at the .05.05 level.

The same split-plot results as an APA-style gt table reproduce Table 12.19. The between-subjects effect (Age) is tested against MSS/AMS_{S/A}, while the within-subjects effect (Angle) and the interaction are tested against MSB×S/AMS_{B \times S/A}; the table keeps each error stratum next to the effects it tests.

HideShow
purrr::imap_dfr(summary(Mixed_ANOVA), function(stratum_tables, stratum) {
  as.data.frame(stratum_tables[[1]]) |>
    tibble::rownames_to_column("Source") |>
    dplyr::mutate(Stratum = stratum)
}) |>
  dplyr::transmute(
    Source = dplyr::if_else(trimws(Source) == "Residuals",
                            paste0("Error (", sub("Error: ", "", Stratum), ")"),
                            trimws(Source)),
    SS = `Sum Sq`, df = Df, MS = `Mean Sq`,
    Fstat = `F value`, p = `Pr(>F)`
  ) |>
  gt() |>
  fmt_number(columns = c(SS, MS), decimals = 0) |>
  fmt_number(columns = Fstat, decimals = 2) |>
  fmt_number(columns = p, decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*")) |>
  tab_header(title = md("**Table 12.19**. ANOVA for the Split-Plot Design")) |>
  cols_align(align = "center", columns = -Source)
Table 12.19. ANOVA for the Split-Plot Design
Source SS df MS F p
Age 132,540 1 132,540 7.28 0.0147
Error (Subject) 327,900 18 18,217

Angle 435,090 2 217,545 143.91 0.0000
Age:Angle 21,090 2 10,545 6.98 0.0028
Error (Subject:Angle) 54,420 36 1,512

To determine the magnitude of these effects, we can calculate partial ω̂2\hat{\omega}^2. For a mixed design, we calculate these values by partialling out all effects except subjects.

The textbook provides specific formulas for the between-subjects main effect (Equation 12.22), the within-subjects main effect (Equation 12.23), and the interaction (Equation 12.24).

Just as we did in Section 12.2, we can dynamically extract the necessary Sums of Squares and Mean Squares directly from our aov() object to calculate these effect sizes reproducibly. Note this is another manual calculation – we will show a more automated way next.

HideShow
# Save the summary object to extract values
mixed_sum <- summary(Mixed_ANOVA)

# Define the number of levels for A (Age) and B (Angle)
a_levels <- 2
b_levels <- 3

# Extract values for Between-Subjects Error Stratum (Subject) ---
SS_S_A <- mixed_sum$`Error: Subject`[[1]]["Residuals", "Sum Sq"]
MS_S_A <- mixed_sum$`Error: Subject`[[1]]["Residuals", "Mean Sq"]

# Extract Main Effect of A (Age)
SS_A <- mixed_sum$`Error: Subject`[[1]]["Age", "Sum Sq"]

# Calculate Omega Squared for Age (Eq 12.22)
omega2_A <- (SS_A - (a_levels - 1) * MS_S_A) / (SS_A + SS_S_A + MS_S_A)

# Extract values for Within-Subjects Error Stratum (Subject:Angle) ---
SS_BxS_A <- mixed_sum$`Error: Subject:Angle`[[1]]["Residuals", "Sum Sq"]
MS_BxS_A <- mixed_sum$`Error: Subject:Angle`[[1]]["Residuals", "Mean Sq"]

# Extract Main Effect of B (Angle)
SS_B <- mixed_sum$`Error: Subject:Angle`[[1]]["Angle", "Sum Sq"]
MS_B <- mixed_sum$`Error: Subject:Angle`[[1]]["Angle", "Mean Sq"]

# Calculate Omega Squared for Angle (Eq 12.23)
omega2_B <- ((b_levels - 1) * (MS_B - MS_BxS_A)) / (SS_B + SS_BxS_A + SS_S_A + MS_S_A)

# Extract Interaction (Age:Angle)
SS_AB <- mixed_sum$`Error: Subject:Angle`[[1]]["Age:Angle", "Sum Sq"]
MS_AB <- mixed_sum$`Error: Subject:Angle`[[1]]["Age:Angle", "Mean Sq"]

# Calculate Omega Squared for Age x Angle (Eq 12.24)
omega2_AB <- ((a_levels - 1) * (b_levels - 1) * (MS_AB - MS_BxS_A)) / (SS_AB + SS_BxS_A + SS_S_A + MS_S_A)

# Results
cat(
  "Partial Omega Squared:\n",
  "  Age (A):", round(omega2_A, 2), "\n",
  "  Angle (B):", round(omega2_B, 2), "\n",
  "  Age x Angle Interaction:", round(omega2_AB, 2), "\n"
)
HideShow
Partial Omega Squared:
   Age (A): 0.24 
   Angle (B): 0.52 
   Age x Angle Interaction: 0.04 
HideShow
#> matches book p. 668: omega-squared = .24 (Age), .52 (Angle), .04 (interaction)

The easiest and most modern way to automate the above calculations in R is by using the effectsize package. The omega_squared() function can take our mixed ANOVA object directly and automatically calculate the partial ω̂2\hat{\omega}^2 for every effect in one line of code.

HideShow
# Calculate partial omega squared for all effects
# Note: partial = TRUE matches the book's logic of partialling out other effects
# effectsize:: is written explicitly because DMAR also exports an omega_squared();
# the qualifier keeps this call pointed at the effectsize version.
effectsize::omega_squared(Mixed_ANOVA, partial = TRUE)
HideShow
# Effect Size for ANOVA (Type I)

Group         | Parameter | Omega2 (partial) |       95% CI
-----------------------------------------------------------
Subject       |       Age |             0.24 | [0.02, 1.00]
Subject:Angle |     Angle |             0.52 | [0.31, 1.00]
Subject:Angle | Age:Angle |             0.04 | [0.00, 1.00]

- One-sided CIs: upper bound fixed at [1.00].
HideShow
#> .24 (Age), .52 (Angle), .04 (Age:Angle) — the same three values, book p. 668

12.3.2 — Further Investigation of Main Effects

12.3.2.1 — Between-Subjects Factor

The meaning of a main effect in a split-plot design is the same as in the other two-way factorial designs we have already discussed. For example, consider the statistically significant main effect we found for Age (p=.0147p = .0147). This implies that the two marginal means (569 for Young, 663 for Old) are significantly different from one another in the population.

Because Age only has two levels, no further post-hoc tests are necessary. However, if our between-subjects factor had more than two levels, we would typically use multiple-comparison procedures.

The text notes a crucial theoretical point: testing the between-subjects main effect in a split-plot design is mathematically identical to averaging each subject’s scores across the within-subjects factor (Angle) and running a simple one-way between-subjects ANOVA.

We can prove this in R. Let’s average each subject’s Reaction Time across the three angles and run a standard aov():

HideShow
# 1. Average over the within-subjects factor (Angle) for each subject
between_data <- split_plot_data %>%
  group_by(Subject, Age) %>%
  summarize(Mean_RT = mean(Reaction_Time), .groups = "drop")

# 2. Run a simple one-way between-subjects ANOVA
simple_between_ANOVA <- aov(Mean_RT ~ Age, data = between_data)
summary(simple_between_ANOVA)
HideShow
            Df Sum Sq Mean Sq F value Pr(>F)  
Age          1  44180   44180   7.276 0.0147 *
Residuals   18 109300    6072                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 7.28 with 1 and 18 df and p = .0147 — the Age main effect of Table 12.19,
#> book p. 668, as the book says on p. 669 it must be

Notice that the FF-value (7.287.28) and pp-value (.0147.0147) are identical to the Age main effect from our Mixed_ANOVA table in the previous section. Thus, the principles of between-subjects contrasts apply here with no modifications whatsoever.

Because this between-subjects test is just a one-way model on the subject means, it can be read as an ordinary regression. The Age coefficient is the Old-minus-Young difference in mean reaction time. modelsummary places the estimate over its standard error (APA style) with the model-fit statistics at the foot:

HideShow
between_lm <- lm(Mean_RT ~ Age, data = between_data)

modelsummary(
  list("Mean RT ~ Age" = between_lm),
  estimate  = "{estimate}",
  statistic = "({std.error})",                 # standard errors in parentheses
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  output    = "gt"
)
Mean RT ~ Age
(Intercept) 569.000
(24.642)
AgeOld 94.000
(34.849)
Num.Obs. 20
AIC 234.9
BIC 237.9
Log.Lik. -114.440
HideShow
#> the Age (Old) coefficient is 94, i.e. 663 - 569 from Table 12.18 (book
#> p. 668); its t^2 reproduces F = 7.28

The same model as a gtsummary regression table, with the confidence interval on the Age difference:

HideShow
tbl_regression(between_lm, intercept = TRUE)
Characteristic Beta 95% CI p-value
(Intercept) 569 517, 621 <0.001
Age


    Young — —
    Old 94 21, 167 0.015
Abbreviation: CI = Confidence Interval

12.3.2.2 — Within-Subjects Factor

In our numerical example, we also obtained a highly significant main effect for Angle. Because Angle has three levels (0∘,4∘,8∘0^\circ, 4^\circ, 8^\circ), we need to test comparisons among these levels to understand the effect. Because Angle is a quantitative variable, we will test the quadratic trend (contrast coefficients: 1,−2,11, -2, 1).

As in previous designs, there are two approaches to testing a within-subjects comparison in a mixed design:

  • Equation 12.25 (Pooled Error Term): Uses the overall MSB×S/AMS_{B \times S/A} as the denominator for all contrasts.

  • Equation 12.26 (Separate Error Term): Uses a specific MSBcomp×S/AMS_{B_{comp} \times S/A} calculated uniquely for that contrast.

In general, the separate error term (Eq 12.26) is preferred because the pooled approach assumes strict homogeneity (sphericity), which is rarely met in repeated measures data.

  1. Approach 1: Pooled Error Term (Equation 12.25)

The emmeans package draws its error term from the fitted model, which here means MSB×S/AMS_{B \times S/A} on 36 degrees of freedom — the 1,511.67 that Table 12.19 prints as 1,512.

HideShow
# Get the estimated marginal means for Angle
em_angle <- emmeans(Mixed_ANOVA, ~ Angle)
em_angle
HideShow
 Angle emmean   SE   df lower.CL upper.CL
 0        510 18.8 24.1      471      549
 4        620 18.8 24.1      581      658
 8        718 18.8 24.1      680      757

Results are averaged over the levels of: Age 
Warning: EMMs are biased unless design is perfectly balanced 
Confidence level used: 0.95 
HideShow
# Test the Quadratic Trend (Weights: 1, -2, 1)
quad_trend <- contrast(em_angle, list("Quadratic Trend" = c(1, -2, 1)))
quad_trend
HideShow
 contrast        estimate   SE df t.ratio p.value
 Quadratic Trend    -10.5 21.3 36  -0.493  0.6250

Results are averaged over the levels of: Age 
HideShow
#> estimate -10.5, i.e. 510 - 2(619.5) + 718.5 — matches book p. 670

# Squaring the t ratio gives Equation 12.25's F.
as.data.frame(quad_trend)$t.ratio^2
HideShow
[1] 0.2431092
HideShow
#> 0.24 with 1 and 36 df — matches book p. 670
  1. Approach 2: Separate Error Term (Equation 12.26)

To obtain the separate error term, we manually apply the contrast weights (1,−2,11, -2, 1) to each subject’s raw data to create a single “Quadratic Score.”

When doing this in R, we must adjust for two default behaviors in lm() to match standard ANOVA formulas:

  1. Effect Coding: We must change the contrast coding for Age to contr.sum. Otherwise, R’s default dummy coding will test the trend only for the reference group (Young participants), rather than the overall Grand Mean.

  2. Variance Inflation: Constructing a manual contrast score inflates the variance. We must divide R’s resulting Sums of Squares by the sum of the squared contrast weights (∑ck2=12+(−2)2+12=6\sum c_k^2 = 1^2 + (-2)^2 + 1^2 = 6).

HideShow
# Create the Quadratic Score per subject
separate_error_data <- split_plot_data %>%
  pivot_wider(names_from = Angle, values_from = Reaction_Time) %>%
  mutate(Quad_Score = 1 * `0` - 2 * `4` + 1 * `8`)

# Force sum-to-zero contrast coding for Age
contrasts(separate_error_data$Age) <- contr.sum

# Run the linear model and get Type III Sums of Squares
quad_model <- lm(Quad_Score ~ Age, data = separate_error_data)
quad_anova <- Anova(quad_model, type = 3)

# Adjust the outputs by dividing by the sum of squared weights (1^2 + -2^2 + 1^2 = 6)
sum_c2 <- 6

# Corrected Contrast Sum of Squares (Intercept)
SS_Quad <- quad_anova["(Intercept)", "Sum Sq"] / sum_c2

# Corrected Separate Error Term (MS Residual)
MS_Error_Separate <- (quad_anova["Residuals", "Sum Sq"] / quad_anova["Residuals", "Df"]) / sum_c2

# Corrected F-value
F_value <- SS_Quad / MS_Error_Separate

# results
cat(
  "  Contrast SS (SS_Bcomp):", SS_Quad, "\n",
  "  Separate Error Term (MS_Bcomp x S/A):", MS_Error_Separate, "\n",
  "  F-value:", round(F_value, 2), "\n"
)
HideShow
  Contrast SS (SS_Bcomp): 367.5 
   Separate Error Term (MS_Bcomp x S/A): 1160.833 
   F-value: 0.32 
HideShow
#> SS = 367.5, MS = 1,160.83, F = 0.32 with 1 and 18 df — matches book p. 670

Applying these adjustments yields the values reported in the textbook. For these data, the quadratic trend for Angle is nonsignificant regardless of which error term is used.

12.3.3 — Further Investigation of an Interaction—Simple Effects

When we find a statistically significant interaction in a split-plot (mixed) design, the most common next step is to test the simple effects. Because one factor is between-subjects and the other is within-subjects, testing simple effects requires two different approaches:

  1. Testing the within-subjects effect at a fixed level of the between-subjects factor (effectively a one-way within-subjects ANOVA).

  2. Testing the between-subjects effect at a fixed level of the within-subjects factor (effectively a one-way between-subjects ANOVA).

12.3.3.1 — Within-Subjects Effects at a Fixed Level of Between-Subjects Factor

First, let’s test the effect of our within-subjects factor (Angle) for just the Young participants. Are the three sample means (477,585,645477, 585, 645) significantly different from each other?

By ignoring the Old participants, this reduces to a standard one-way within-subjects design. As discussed in the text, we have a choice of error terms: * Separate Error Term (MSB×S/AjMS_{B \times S/A_j}): Uses only the variance from the Young participants.

  • Pooled Error Term (MSB×S/AMS_{B \times S/A}): Borrows variance from the overall mixed ANOVA, assuming variances are equal across both age groups.

The separate error term is generally preferred unless samples are very small, as it does not require the strict assumption that variance is equal across groups. To use the separate error term in R, we simply filter our dataset and run a repeated measures ANOVA.

HideShow
# Filter data for only Young participants
young_only_data <- split_plot_data %>%
  filter(Age == "Young")

# Run a one-way within-subjects ANOVA (Separate Error Term)
simple_angle_young <- aov(Reaction_Time ~ Angle + Error(Subject/Angle), data = young_only_data)

summary(simple_angle_young)
HideShow

Error: Subject
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  9 146070   16230               

Error: Subject:Angle
          Df Sum Sq Mean Sq F value   Pr(>F)    
Angle      2 144960   72480   40.72 2.09e-07 ***
Residuals 18  32040    1780                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> SS = 144,960 and MS = 72,480 for Angle over MS_(B x S/A1) = 1,780, giving
#> F = 40.72 with 2 and 18 df — matches book p. 671

In the Error: Subject:Angle stratum, F=40.72F = 40.72, making the simple effect of Angle for Young individuals highly significant (p<.05p < .05).

The pooled alternative divides the same numerator mean square by MSB×S/AMS_{B \times S/A} from the full split-plot table, which the book also reports:

HideShow
MS_B_at_A1 <- summary(simple_angle_young)$`Error: Subject:Angle`[[1]]["Angle", "Mean Sq"]
MS_BxS_A   <- summary(Mixed_ANOVA)$`Error: Subject:Angle`[[1]]["Residuals", "Mean Sq"]

MS_B_at_A1 / MS_BxS_A
HideShow
[1] 47.94708
HideShow
#> 47.95 — matches book p. 672

12.3.3.2 — Between-Subjects Effects at a Fixed Level of Within-Subjects Factor

The other side of the interaction is testing the effect of Age at a fixed level of Angle. For example, is there a significant difference between Young and Old participants specifically at the 0∘0^\circ Angle condition?

By looking only at 0∘0^\circ, we effectively have a standard one-way between-subjects design. Again, we must choose an error term:

  • Separate Error Term (MSS/A at B1MS_{S/A \text{ at } B_1}): Uses the variance within groups only at the 0∘0^\circ condition.

  • Pooled Error Term (MSWCELLMS_{WCELL}): Averages the variance across all three angle conditions.

Because variances often change across repeated measures (e.g., scores becoming more variable over time or across harder conditions), the separate error term is almost always preferred in behavioral research.

We can calculate this in R by filtering the data to the 0∘0^\circ condition and running a standard between-subjects ANOVA:

HideShow
# Filter data for ONLY the 0 degree Angle
angle_0_data <- split_plot_data %>%
  filter(Angle == "0")

# Run a one-way between-subjects ANOVA (Separate Error Term)
simple_age_0 <- aov(Reaction_Time ~ Age, data = angle_0_data)

summary(simple_age_0)
HideShow
            Df Sum Sq Mean Sq F value Pr(>F)  
Age          1  21780   21780   3.161 0.0923 .
Residuals   18 124020    6890                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> MS = 21,780 for Age over MS_(S/A at B1) = 6,890, giving F = 3.16 with 1 and
#> 18 df and p = .092 — matches book p. 673

The Mean Square for Age is 21,78021,780. The Residual Mean Square (our separate error term, MSS/A at B1MS_{S/A \text{ at } B_1}) is 6,8906,890. This results in an FF-value of 3.163.16 with 11 and 1818 degrees of freedom (p=.092p = .092). Thus, the age difference at 0∘0^\circ is nonsignificant.

The pooled alternative here is MSWCELLMS_{WCELL}, which Equation 12.31 builds from the two error sums of squares of Table 12.19:

HideShow
SS_S_A_tbl   <- summary(Mixed_ANOVA)$`Error: Subject`[[1]]["Residuals", "Sum Sq"]
SS_BxS_A_tbl <- summary(Mixed_ANOVA)$`Error: Subject:Angle`[[1]]["Residuals", "Sum Sq"]
b_lev <- 3; N_tot <- 20; a_lev <- 2

MS_WCELL <- (SS_S_A_tbl + SS_BxS_A_tbl) / (b_lev * (N_tot - a_lev))
MS_WCELL
HideShow
[1] 7080
HideShow
#> 7,080 — matches book p. 674

21780 / MS_WCELL
HideShow
[1] 3.076271
HideShow
#> 3.08 with 1 and 54 df — matches book p. 674

12.3.4 — Interaction Contrasts

The quadratic trend for Angle was nonsignificant overall, but that leaves open whether the quadratic trend differs by age. From Table 12.18 the quadratic trend is −48-48 for young subjects and 2727 for old subjects, so the contrast to be tested is 27−(−48)=7527 – (-48) = 75. In terms of the six cell means its coefficients are −1,2,−1,1,−2,1-1, 2, -1, 1, -2, 1.

The quadratic score per subject built in Section 12.3.2.2 is exactly what this contrast needs; the only change is that now the Age term of that model, rather than its intercept, carries the effect of interest.

HideShow
# The two groups' quadratic trends, and their difference.
separate_error_data %>%
  group_by(Age) %>%
  summarize(Quadratic_Trend = mean(Quad_Score), .groups = "drop")
HideShow
# A tibble: 2 × 2
  Age   Quadratic_Trend
  <fct>           <dbl>
1 Young             -48
2 Old                27
HideShow
#> -48 for young and 27 for old, a difference of 75 — matches book p. 674

# The Age row of the model on the quadratic scores, rescaled by the same
# sum_c2 = 6 inflation used above. Because that row already equals n(psi)^2 / 2
# for the two groups, the rescaled value is the book's n(psi)^2 / 12.
SS_AxBquad <- quad_anova["Age", "Sum Sq"] / sum_c2
SS_AxBquad
HideShow
[1] 4687.5
HideShow
#> 4,687.5, i.e. 10(75)^2 / 12 — matches book p. 675

# Equation 12.32 pools: divide by MS_(B x S/A) from Table 12.19.
SS_AxBquad / MS_BxS_A
HideShow
[1] 3.100882
HideShow
#> 3.101 with 1 and 36 df — matches book p. 675

# Equation 12.34 uses the separate error term built from the quadratic scores.
SS_AxBquad / MS_Error_Separate
HideShow
[1] 4.038047
HideShow
#> 4.038 with 1 and 18 df — matches book p. 675

The separate-error test is the Age row of the model already fitted, so car::Anova() reports its FF and pp directly; dividing numerator and denominator by ∑ck2\sum c_k^2 leaves the ratio unchanged.

HideShow
quad_anova
HideShow
Anova Table (Type III tests)

Response: Quad_Score
            Sum Sq Df F value  Pr(>F)  
(Intercept)   2205  1  0.3166 0.58061  
Age          28125  1  4.0380 0.05972 .
Residuals   125370 18                  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 4.038 for Age with p = .0597 — matches book p. 675, so the age difference
#> in the quadratic trend is not significant at the .05 level

To better understand the nature of the Age ×\times Angle interaction, we can plot the cell means. The text notes that younger individuals might show an inverted-U shape, whereas older individuals show a U-shaped trend. We can recreate Figure 12.1 using ggplot2.

The split-plot example crosses a between-subjects factor (Age: young vs. old) with a within-subjects factor (Angle: 0, 4, and 8 degrees of tilt). The 10 young subjects come from Table 12.7 and the 10 old subjects from Table 12.15, each already averaged over the noise factor. The figure plots each age group’s mean reaction time at each angle, so both main effects and the interaction can be read directly off the lines.

HideShow
# Cell means: mean reaction time for each Age x Angle combination.
cell_means <- split_plot_data |>
  group_by(Age, Angle) |>
  summarize(Mean_RT = mean(Reaction_Time), .groups = "drop")
HideShow
ggplot(cell_means, aes(x = Angle, y = Mean_RT,
                       group = Age, color = Age, shape = Age)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  labs(title = "Figure 12.1. Reaction times by age and angle",
       x = "Angle (degrees)", y = "Mean reaction time (ms)",
       color = "Age group", shape = "Age group") +
  theme(legend.position = "top")
Figure 12.1. Mean reaction time for old and young subjects as a function of angle.

Figure 12.1. Mean reaction time for old and young subjects as a function of angle.

Both main effects are visible: old subjects are slower than young subjects at every angle, and reaction time rises with angle for both groups. The lines are not parallel, which is the Age ×\times Angle interaction: the gap between the groups is widest at 8 degrees. The young group traces a flatter, more inverted-U pattern while the old group rises more steeply, consistent with the text’s description on p. 676 — though, as the contrast above showed, that difference in shape is not statistically significant.

12.3.5 — Assumptions

The split-plot design combines between-subjects and within-subjects assumptions, so it inherits both sets. Normality and homogeneity of the covariance matrices across levels of the between-subjects factor are what the between-subjects effects require; the within-subjects effects require sphericity of the covariance matrix for BB, pooled across groups. Table 12.20 of the book (p. 678) lays out which test requires which assumption and how robust each one is. Two practical consequences follow for the analyses above: tests of AA alone need no sphericity assumption at all, and tests of within-subjects contrasts that use a separate error term, as in Equations 12.26 and 12.34, do not either.

12.3.6 — Adjusted Univariate Tests

Because both within-subjects effects — the BB main effect and the A×BA \times B interaction — are tested against the same error term, MSB×S/AMS_{B \times S/A}, there is only one ϵ̂\hat{\epsilon} and one ϵ̃\tilde{\epsilon} to compute for the whole split-plot design, unlike the three of Section 12.2.8. car::Anova() produces them from a multivariate linear model fitted to the wide data, with the between-subjects factor on the right-hand side.

HideShow
# Wide form: one row per subject, one column per angle, with Age as a predictor.
split_plot_wide <- split_plot_data %>%
  pivot_wider(names_from = Angle, values_from = Reaction_Time,
              names_prefix = "Angle")

split_plot_mlm <- lm(cbind(Angle0, Angle4, Angle8) ~ Age, data = split_plot_wide)

# The within-subjects design has a single three-level factor.
idata_split <- data.frame(Angle = factor(c(0, 4, 8)))

summary(Anova(split_plot_mlm, idata = idata_split, idesign = ~ Angle),
        multivariate = FALSE)
HideShow

Univariate Type II Repeated-Measures ANOVA Assuming Sphericity

              Sum Sq num Df Error SS den Df   F value    Pr(>F)    
(Intercept) 22767360      1   327900     18 1249.8093 < 2.2e-16 ***
Age           132540      1   327900     18    7.2758  0.014734 *  
Angle         435090      2    54420     36  143.9107 < 2.2e-16 ***
Age:Angle      21090      2    54420     36    6.9757  0.002752 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


Mauchly Tests for Sphericity

          Test statistic p-value
Angle            0.93684 0.57431
Age:Angle        0.93684 0.57431


Greenhouse-Geisser and Huynh-Feldt Corrections
 for Departure from Sphericity

           GG eps Pr(>F[GG])    
Angle     0.94059  < 2.2e-16 ***
Age:Angle 0.94059   0.003399 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

            HF eps   Pr(>F[HF])
Angle     1.046677 6.728921e-18
Age:Angle 1.046677 2.751523e-03
HideShow
#> unadjusted F = 7.28 (Age), 143.91 (Angle), 6.98 (Age:Angle) — Table 12.19,
#> book p. 668; Greenhouse-Geisser epsilon = .94 for both within-subjects
#> effects — matches book p. 679

The single ϵ̂\hat{\epsilon} of .94 is shared by the Angle and Age ×\times Angle rows, exactly as the book explains it must be (p. 679). Because ϵ̂\hat{\epsilon} is so near 1.00 here, the Greenhouse-Geisser tests barely differ from the unadjusted ones.

The Huynh-Feldt figure needs a word of care, because car and the book report slightly different numbers for it: the book gives ϵ̃=1.11\tilde{\epsilon} = 1.11 (p. 679) where car prints 1.05. Both exceed 1.00, so both are shrunk back to 1.00 and the Huynh-Feldt tests come out identical to the unadjusted ones either way — but the two values come from two circulating forms of the same correction, differing in whether the numerator carries NN or N−a+1N – a + 1.

HideShow
N_tot <- 20; a_lev <- 2; b_lev <- 3
eps_hat <- 0.94059   # the Greenhouse-Geisser value printed above

c(book_form = (N_tot * (b_lev - 1) * eps_hat - 2) /
              ((b_lev - 1) * ((N_tot - a_lev) - (b_lev - 1) * eps_hat)),
  car_form  = ((N_tot - a_lev + 1) * (b_lev - 1) * eps_hat - 2) /
              ((b_lev - 1) * ((N_tot - a_lev) - (b_lev - 1) * eps_hat)))
HideShow
book_form  car_form 
 1.105031  1.046678 
HideShow
#> 1.11 and 1.05: the first reproduces the book's epsilon-tilde on p. 679, the
#> second the value car prints just above. Both exceed 1.00 and are set to 1.00.

12.4 — Power Analysis and Sample Size Planning

This chapter introduced two new designs: a factorial design with two within-subjects factors, and a mixed (split-plot) design with one between-subjects and one within-subjects factor. Power analysis for these designs builds directly on the principles from Chapter 7 (factorial designs) and Chapter 11 (within-subjects designs).

The book’s power values for these designs come from SAS GLMPOWER: Table 12.23 for the first example, Table 12.26 for the second, and the table of required sample sizes on p. 686 for the last. Packages exist that will do this sort of calculation, but on this page we do it by hand in base R, for two reasons. The first is that the entire calculation is about thirty-five lines of linear algebra, so once it is written out there is nothing left to take on faith. The second is that the final example is a place where two perfectly defensible calculations give different answers — a required total sample size of 188, or of 176 — and seeing why means looking at the quantity each one computes. That is hard to see through a function’s defaults and easy to see in the arithmetic.

The one calculation behind every number in this section

Every omnibus test in this section tests a hypothesis of the form 𝑪𝝁𝑼=𝟎\mathbf{C}\boldsymbol{\mu}\mathbf{U} = \mathbf{0}, where 𝝁\boldsymbol{\mu} holds the population cell means with one row per between-subjects group and one column per within-subjects condition, 𝑪\mathbf{C} says which comparison among the groups is at issue, and 𝑼\mathbf{U} which comparison among the repeated measures. When there is no between-subjects factor, 𝑪\mathbf{C} is simply the number 1. In a mixed design the AA main effect has 𝑪\mathbf{C} contrasting the groups and 𝑼\mathbf{U} averaging over the repeated measures, the BB main effect has 𝑪\mathbf{C} averaging over the groups and 𝑼\mathbf{U} contrasting the repeated measures, and the interaction contrasts on both sides.

Let 𝚺*=𝑼′𝚺𝑼\boldsymbol{\Sigma}^{*} = \mathbf{U}'\boldsymbol{\Sigma}\mathbf{U} be the covariance matrix of the transformed scores, with eigenvalues λ1,…,λp\lambda_1, \ldots, \lambda_p; let qq be the number of rows of 𝑪\mathbf{C}, pp the number of columns of 𝑼\mathbf{U}, and νe=N−a\nu_{e} = N – a the error degrees of freedom for aa groups. The two sums of squares that make up the univariate (or “averaged”) FF test are then exactly

SSeffect=∑i=1pλiχq2(ωi),SSerror=∑i=1pλiχνe2,SS_{\text{effect}} = \sum_{i=1}^{p}\lambda_{i}\,\chi^{2}_{q}(\omega_{i}), \qquad SS_{\text{error}} = \sum_{i=1}^{p}\lambda_{i}\,\chi^{2}_{\nu_{e}},

independently of one another, where ωi\omega_{i} is the squared size of the effect along the iith eigenvector of 𝚺*\boldsymbol{\Sigma}^{*} divided by that direction’s variance λi\lambda_{i}. Three cases follow, and they are the whole story.

  1. p=1p = 1. There is one eigenvalue and it cancels between numerator and denominator, leaving an ordinary noncentral FF with qq and νe\nu_{e} degrees of freedom. Every effect with one numerator degree of freedom lands here, which is exactly why such tests need no sphericity correction.
  2. p>1p > 1 with all λi\lambda_{i} equal. The common eigenvalue cancels again, leaving an ordinary noncentral FF with qpqp and pνep\nu_{e} degrees of freedom and noncentrality ∑iωi\sum_{i}\omega_{i}. Equal eigenvalues is sphericity, stated in the contrast space where it actually matters rather than on the raw correlation matrix.
  3. p>1p > 1 with unequal λi\lambda_{i}. The ratio is not an FF at all. The test rejects when SSeffect−(qFcrit/νe)SSerror>0SS_{\text{effect}} – (q F_{\text{crit}}/\nu_{e})\,SS_{\text{error}} > 0, and the left-hand side is a weighted sum of independent chi-squares, some weights positive and some negative. Its characteristic function is available in closed form, so the probability that it is positive comes from inverting that function numerically — one call to integrate(), with no distributional approximation and no simulation (Imhof, 1961).

An ϵ\epsilon correction changes the critical value but not the statistic: the degrees of freedom become qpϵqp\epsilon and pνeϵp\nu_{e}\epsilon. Putting ϵ=1/p\epsilon = 1/p gives the Geisser–Greenhouse lower-bound test, which SAS labels “Box Conservative.”

Three short functions implement all of that. They are the only machinery this section needs.

HideShow
# An orthonormal basis for the contrasts among k levels: k - 1 columns that
# each sum to zero, are mutually orthogonal, and have unit length. Helmert
# contrasts have the first two properties already; dividing each column by its
# own length supplies the third. Any orthonormal basis gives the same test.
contrast_basis <- function(k) {
  helmert <- contr.helmert(k)
  sweep(helmert, MARGIN = 2, STATS = sqrt(colSums(helmert^2)), FUN = "/")
}

# P(Q > 0) for Q = sum_j lambda_j * chi-square(h_j, ncp_j), by numerical
# inversion of Q's characteristic function (Imhof, 1961). Below, theta is that
# function's argument and logrho the logarithm of its modulus. Because the
# cutoff is zero the integrand does not oscillate, so one integrate() does it.
prob_positive <- function(lambda, h, ncp) {
  lambda <- lambda / max(abs(lambda))     # P(Q > 0) does not depend on scale
  integrand <- function(t) {
    lt     <- outer(t, lambda)
    den    <- 1 + 4 * lt^2
    theta  <- rowSums(sweep(atan(2 * lt), 2, h / 2, FUN = "*") +
                      sweep(lt / den,     2, ncp,   FUN = "*"))
    logrho <- rowSums(sweep(log(den),     2, h / 4, FUN = "*") +
                      2 * sweep(lt^2 / den, 2, ncp, FUN = "*"))
    sin(theta) / (t * exp(logrho))
  }
  0.5 + integrate(integrand, lower = 0, upper = Inf, rel.tol = 1e-10)$value / pi
}

# Power of the univariate F test of C %*% Mu %*% U = 0.
#   Mu       population cell means: one row per group, one column per
#            within-subjects condition
#   Sigma    population covariance matrix of the within-subjects conditions
#   n        sample size per group (recycled if a single number)
#   C, U     the between- and within-subjects contrasts defining the effect
#   epsilon  1 for the uncorrected test, 1 / ncol(U) for the
#            Geisser-Greenhouse lower bound; ignored when U has a single
#            column, where the only possible value is 1
rm_power <- function(Mu, Sigma, n, C, U, alpha = 0.05, epsilon = 1) {
  n     <- rep(n, length.out = nrow(Mu))
  nu_e  <- sum(n) - nrow(Mu)          # error df: N minus the number of groups
  q     <- nrow(C)                    # contrasts among groups
  p     <- ncol(U)                    # contrasts among repeated measures
  # One contrast leaves nothing for an epsilon to correct, so epsilon can only
  # be 1 here. Enforcing that keeps the critical value and the distribution it
  # is compared against on the same degrees of freedom.
  if (p == 1) epsilon <- 1
  Minv  <- solve(C %*% diag(1 / n, nrow = length(n)) %*% t(C))
  Theta <- C %*% Mu %*% U             # the effect being tested
  ev    <- eigen(t(U) %*% Sigma %*% U, symmetric = TRUE)   # Sigma-star
  # Signal along each eigenvector, divided by that direction's variance.
  # chol(Minv) is a square root of the inverse of C diag(1/n) C'; only the
  # quadratic form it produces matters, so any square root would do.
  omega <- colSums((chol(Minv) %*% Theta %*% ev$vectors)^2) / ev$values
  Fcrit <- qf(1 - alpha, q * p * epsilon, p * nu_e * epsilon)
  if (p == 1) {
    return(pf(Fcrit, q * p, p * nu_e, ncp = sum(omega), lower.tail = FALSE))
  }
  prob_positive(lambda = c(ev$values, -(q * Fcrit / nu_e) * ev$values),
                h      = c(rep(q, p), rep(nu_e, p)),
                ncp    = c(omega, rep(0, p)))
}

Everything below is a matter of writing down 𝝁\boldsymbol{\mu}, 𝚺\boldsymbol{\Sigma}, 𝑪\mathbf{C}, and 𝑼\mathbf{U} for the effect at hand.

12.4.1 — Designs with Two Within-Subjects Factors

  1. Example 1: A 2×22 \times 2 Within-Subjects Design (Power Calculation)

Imagine a researcher plans a study with N=12N = 12 participants and an α=.05\alpha = .05. The population standard deviation is 1.01.0 in each cell. Because this is a repeated-measures design, the correlation between the cells matters. Instead of assuming compound symmetry, we assume scores sharing a row or column correlate more highly than those that do not.

Every participant is measured in all four cells, so there is a single group: 𝝁\boldsymbol{\mu} has one row, and 𝑪\mathbf{C} is the 1×11 \times 1 matrix holding 1. The cells run A-major (A1B1, A1B2, A2B1, A2B2), so a Kronecker product with the A part on the left lines each contrast up with that ordering.

HideShow
# Table 12.22: the population correlations among the four cells. Every
# population standard deviation is 1.0, so this is the covariance matrix too.
cor_2x2 <- matrix(c(
  1.0, 0.6, 0.4, 0.3,
  0.6, 1.0, 0.3, 0.4,
  0.4, 0.3, 1.0, 0.6,
  0.3, 0.4, 0.6, 1.0
), nrow = 4, byrow = TRUE)
Sigma_2x2 <- 1.0^2 * cor_2x2

mu_2x2 <- matrix(c(0.0, 0.9, 0.7, 0.9), nrow = 1)   # Table 12.21 cell means
C_one  <- matrix(1, nrow = 1, ncol = 1)             # one group: nothing to contrast
avg_2  <- matrix(1 / 2, nrow = 2, ncol = 1)         # average over a 2-level factor

U_A  <- kronecker(contrast_basis(2), avg_2)               # A, averaging over B
U_B  <- kronecker(avg_2, contrast_basis(2))               # B, averaging over A
U_AB <- kronecker(contrast_basis(2), contrast_basis(2))   # the interaction

round(c(A  = rm_power(mu_2x2, Sigma_2x2, n = 12, C = C_one, U = U_A),
        B  = rm_power(mu_2x2, Sigma_2x2, n = 12, C = C_one, U = U_B),
        AB = rm_power(mu_2x2, Sigma_2x2, n = 12, C = C_one, U = U_AB)), 4)
HideShow
     A      B     AB 
0.2152 0.6896 0.5236 
HideShow
#> .2152, .6896, and .5236, i.e. .215 (A), .690 (B), and .524 (A x B) —
#> matches the GLMPOWER output of Table 12.23 on book p. 681

Each of these has one numerator degree of freedom, so each is case 1 above and could have been computed with a single pf() call. It is worth doing that once, by hand, so that nothing about rm_power() is mysterious. The noncentrality of a one-degree-of-freedom within-subjects test is λ=Nψ2/σψ2\lambda = N\psi^{2}/\sigma^{2}_{\psi}: the squared contrast among the population means, divided by the variance of that contrast for a single participant, times the sample size.

HideShow
# The A main effect compares the mean of the two A2 cells with the mean of the
# two A1 cells. Rescaling the contrast changes psi and its variance by the same
# factor, so lambda, and therefore power, is unaffected.
u_A      <- c(-1, -1, 1, 1) / 2
psi_A    <- as.vector(mu_2x2 %*% u_A)              # contrast among the means
var_psi  <- as.vector(t(u_A) %*% Sigma_2x2 %*% u_A) # its variance for one person
lambda_A <- 12 * psi_A^2 / var_psi
round(c(psi = psi_A, variance = var_psi, lambda = lambda_A), 4)
HideShow
     psi variance   lambda 
  0.3500   0.9000   1.6333 
HideShow
#> psi = .35, variance = .90, lambda = 1.6333

pf(qf(0.95, 1, 11), df1 = 1, df2 = 11, ncp = lambda_A, lower.tail = FALSE)
HideShow
[1] 0.2151877
HideShow
#> .2152 again — matches the .215 of Table 12.23 on book p. 681

Notice that for all three effects, the uncorrected test has the exact same power as the ϵ\epsilon-adjusted tests. Why? Because each factor has only 2 levels, meaning the numerator degrees of freedom for every test is 1. Tests with 1 numerator df automatically satisfy the sphericity assumption, even if the overall 4×4 correlation matrix violates compound symmetry. In the language above, 𝑼\mathbf{U} has a single column, so 𝚺*\boldsymbol{\Sigma}^{*} is a single number and there is nothing for an ϵ\epsilon to correct.

  1. Example 2: A 2×3 Within-Subjects Design (Sample Size Planning)

Now suppose a researcher wants to achieve a power of .80 for all effects in a 2×3 design, with a standard deviation of 20 and a custom 6×6 correlation matrix. The B main effect and the interaction now have 2 numerator degrees of freedom apiece, so for the first time 𝑼\mathbf{U} has more than one column and sphericity becomes a live question.

HideShow
# Table 12.25: population correlations among the six cells.
cor_2x3 <- matrix(c(
  1.0, 0.6, 0.6, 0.4, 0.3, 0.3,
  0.6, 1.0, 0.6, 0.3, 0.4, 0.3,
  0.6, 0.6, 1.0, 0.3, 0.3, 0.4,
  0.4, 0.3, 0.3, 1.0, 0.6, 0.6,
  0.3, 0.4, 0.3, 0.6, 1.0, 0.6,
  0.3, 0.3, 0.4, 0.6, 0.6, 1.0
), nrow = 6, byrow = TRUE)
Sigma_2x3 <- 20^2 * cor_2x3

mu_2x3 <- matrix(c(100, 118, 109, 114, 118, 116), nrow = 1)  # Table 12.24
avg_3  <- matrix(1 / 3, nrow = 3, ncol = 1)

U_A3  <- kronecker(contrast_basis(2), avg_3)
U_B3  <- kronecker(avg_2, contrast_basis(3))
U_AB3 <- kronecker(contrast_basis(2), contrast_basis(3))

# Sphericity is a property of the contrast space, not of the correlation
# matrix: it holds exactly when the eigenvalues of U' Sigma U are all equal.
lapply(list(A = U_A3, B = U_B3, AB = U_AB3), function(U)
  zapsmall(eigen(t(U) %*% Sigma_2x3 %*% U, symmetric = TRUE)$values))
HideShow
$A
[1] 160

$B
[1] 100 100

$AB
[1] 120 120
HideShow
#> A: 160 (one column, so nothing to compare); B: 100 and 100; AB: 120 and 120.
#> The B and A x B contrast spaces are exactly spherical — stated for the B
#> main effect in the running text of p. 683 and for both effects in Endnote 22,
#> printed on p. 707 — even though the 6 x 6 matrix itself is plainly not
#> compound symmetric. That endnote gives the B matrix as variances of 280 and
#> covariances of 180, whose contrast eigenvalue is 280 - 180 = 100: the value
#> printed just above

Each contrast space here has either a single dimension or equal eigenvalues, so every test is an ordinary noncentral FF — case 1 for AA, case 2 for BB and the interaction. Sample size planning is then a search: step NN upward until power reaches .80.

HideShow
first_N <- function(U, epsilon = 1, target = 0.80) {
  for (N in 4:400) {
    power <- rm_power(mu_2x3, Sigma_2x3, n = N, C = C_one, U = U,
                      epsilon = epsilon)
    if (power >= target) return(c(N = N, power = round(power, 3)))
  }
}

rbind(`A  uncorrected` = first_N(U_A3),
      `B  uncorrected` = first_N(U_B3),
      `AB uncorrected` = first_N(U_AB3),
      `B  lower bound` = first_N(U_B3,  epsilon = 1 / 2),
      `AB lower bound` = first_N(U_AB3, epsilon = 1 / 2))
HideShow
                N power
A  uncorrected 54 0.806
B  uncorrected 18 0.814
AB uncorrected 26 0.815
B  lower bound 23 0.822
AB lower bound 32 0.808
HideShow
#> 54, 18, and 26 for the uncorrected tests and 23 and 32 for the lower-bound
#> tests, with powers .806, .814, .815, .822, and .808 at those sample sizes —
#> matches the N Total and Actual Power columns of Table 12.26 on book p. 683

Table 12.26 also reports an “Actual Alpha” for the two lower-bound rows: .0197 and .0202 rather than .05. That column is easy to reproduce, because the Type I error rate is just the power when the effect is zero. Setting the cell means to zero turns rm_power() into the test’s true size.

HideShow
mu_null <- matrix(0, nrow = 1, ncol = 6)
round(c(B  = rm_power(mu_null, Sigma_2x3, n = 23, C = C_one, U = U_B3,
                      epsilon = 1 / 2),
        AB = rm_power(mu_null, Sigma_2x3, n = 32, C = C_one, U = U_AB3,
                      epsilon = 1 / 2)), 4)
HideShow
     B     AB 
0.0197 0.0202 
HideShow
#> .0197 and .0202 — matches the Actual Alpha column of Table 12.26 on book
#> p. 683. The lower-bound test is not a .05 test here; it spends less than
#> half the available Type I error rate, which is why it needs more
#> participants.

As the book points out, because Factor A has only 2 levels its required sample size of 54 is the same whether or not an ϵ\epsilon adjustment is applied: with 1 numerator degree of freedom, sphericity holds by construction. The two ϵ̂\hat{\epsilon}-based rows of Table 12.26 — Greenhouse-Geisser and Huynh-Feldt — are not reproduced above, and it is worth saying why. Those tests estimate ϵ̂\hat{\epsilon} from the same data that produce FF, so the degrees of freedom are themselves random; their power is not an exact probability of the kind computed here but an approximation to the behavior of a two-stage procedure. Sphericity holds exactly in both contrast spaces of this example, so neither adjustment buys anything in the population — yet the book’s Table 12.26 shows Greenhouse-Geisser needing 19 participants for the B main effect rather than 18. That single extra participant is the price of estimating ϵ\epsilon: ϵ̂\hat{\epsilon} averages below 1.00 in finite samples even when the population value is exactly 1.00, so the adjusted test is slightly conservative. The book makes the same point and recommends the Greenhouse-Geisser test anyway, on the grounds that one participant is a small price for protection against a sphericity violation that may well be real.

12.4.2 — Designs with One Between-Subjects Factor and One Within-Subjects Factor

When adding a between-subjects factor, the noncentrality parameters (which drive statistical power) change. Specifically, they incorporate a term b1+(b−1)ρ\frac{b}{1 + (b-1)\rho} that acts much like the Spearman-Brown prophecy formula from psychometric theory, adjusting for the correlation among the repeated measures. That term is not a fudge factor, and the framework above shows where it comes from: a purely between-subjects effect is tested on each participant’s average over the bb repeated measures, and under compound symmetry the variance of that average is σ2[1+(b−1)ρ]/b\sigma^{2}[1 + (b-1)\rho]/b. The noncentrality carries the reciprocal of that variance, which is the second parenthesis of Equation 12.35.

  1. Example 1: A 2×2 Mixed Design

Let’s test a design with 1 between-subjects factor (2 groups) and 1 within-subjects factor (2 time points). We have a total N=24N = 24 (so n=12n = 12 per group). The standard deviation is 1.0, and the correlation between the two time points is 0.50. Now 𝝁\boldsymbol{\mu} has one row per group, and 𝑪\mathbf{C} finally has something to do.

HideShow
Sigma_2 <- matrix(c(1.0, 0.5,
                    0.5, 1.0), nrow = 2)          # two time points, r = .50
mu_mixed <- matrix(c(0.0, 0.9,                    # Group 1: Time 1, Time 2
                     0.7, 0.9), nrow = 2, byrow = TRUE)   # Group 2

C_diff <- matrix(c(1, -1), nrow = 1)        # group 1 versus group 2
C_avg  <- matrix(c(1, 1) / 2, nrow = 1)     # averaging over the two groups

round(c(A  = rm_power(mu_mixed, Sigma_2, n = 12, C = C_diff,
                      U = avg_2),
        B  = rm_power(mu_mixed, Sigma_2, n = 12, C = C_avg,
                      U = contrast_basis(2)),
        AB = rm_power(mu_mixed, Sigma_2, n = 12, C = C_diff,
                      U = contrast_basis(2))), 4)
HideShow
     A      B     AB 
0.1574 0.7309 0.3746 
HideShow
#> .1574, .7309, and .3746, i.e. .16 (A), .73 (B), and .37 (A x B) —
#> matches book p. 684, where these are the values several programs agree on

Note that n here is the sample size per group, because the rows of mu_mixed are groups; in Section 12.4.1 the same argument was the total, because there was only one row. The total sample size of 24 is marginally adequate for testing the B main effect and much too small for the A main effect or the interaction.

  1. Example 2: A 2×4 Mixed Design (LEAR Correlation Matrix)

Finally, consider a 2×4 mixed design where the within-subjects factor represents 4 time points. We use a LEAR (Linear Exponent Autoregressive) correlation model, representing a longitudinal design where measurements taken closer together correlate more highly than measurements taken further apart. This is the first example in the section where sphericity genuinely fails, so it is the first that needs case 3.

HideShow
# Table 12.28: the LEAR correlations among the four time points, the same
# within each level of A.
cor_lear <- matrix(c(
  1.00, 0.60, 0.54, 0.49,
  0.60, 1.00, 0.60, 0.54,
  0.54, 0.60, 1.00, 0.60,
  0.49, 0.54, 0.60, 1.00
), nrow = 4, byrow = TRUE)
Sigma_lear <- 10^2 * cor_lear

mu_2x4 <- matrix(c(104, 108, 110, 112,     # Table 12.27 cell means, by group
                   100, 102, 102, 104), nrow = 2, byrow = TRUE)
avg_4  <- matrix(1 / 4, nrow = 4, ncol = 1)
U_B4   <- contrast_basis(4)

Sigma_star <- t(U_B4) %*% Sigma_lear %*% U_B4
round(eigen(Sigma_star, symmetric = TRUE)$values, 3)
HideShow
[1] 53.639 40.500 37.361
HideShow
#> 53.639, 40.500, 37.361 — unequal, so the within-subjects contrast space is
#> not spherical and the uncorrected F statistic is not distributed as an F

round(sum(diag(Sigma_star))^2 / (3 * sum(Sigma_star^2)), 4)
HideShow
[1] 0.9748
HideShow
#> the population epsilon, .9748: the departure from sphericity is mild

Mild is not the same as irrelevant, as the required sample sizes show. The search is the same as before, except that n is per group, so total sample sizes step by two.

HideShow
first_N_total <- function(C, U, epsilon = 1, target = 0.80) {
  for (N in seq(4, 600, by = 2)) {
    power <- rm_power(mu_2x4, Sigma_lear, n = N / 2, C = C, U = U,
                      epsilon = epsilon)
    if (power >= target) return(N)
  }
}

rbind(
  `Uncorrected test` =
    c(A  = first_N_total(C_diff, avg_4),
      B  = first_N_total(C_avg,  U_B4),
      AB = first_N_total(C_diff, U_B4)),
  `Geisser-Greenhouse lower bound` =
    c(A  = first_N_total(C_diff, avg_4),   # p = 1, so epsilon is 1 regardless
      B  = first_N_total(C_avg,  U_B4, epsilon = 1 / 3),
      AB = first_N_total(C_diff, U_B4, epsilon = 1 / 3)))
HideShow
                                A  B  AB
Uncorrected test               52 30 188
Geisser-Greenhouse lower bound 52 42 266
HideShow
#> 52 / 30 / 188 and 52 / 42 / 266 — matches the first two rows of the table of
#> required total sample sizes on book p. 686, cell for cell

The remaining two rows of that table, for the ϵ̂\hat{\epsilon}-adjusted tests, are 52 / 30 / 190 for Greenhouse-Geisser and 52 / 30 / 188 for Huynh-Feldt. They are bracketed by the two rows computed above, and for the same reason given in Section 12.4.1 they are not exact probabilities: estimating ϵ\epsilon from the data makes the degrees of freedom random, and the published values rest on an approximation to the resulting two-stage procedure rather than on a closed-form distribution.

The interaction’s threshold deserves a closer look, because it is a near thing.

HideShow
round(c(`N = 186` = rm_power(mu_2x4, Sigma_lear, n = 93, C = C_diff, U = U_B4),
        `N = 188` = rm_power(mu_2x4, Sigma_lear, n = 94, C = C_diff, U = U_B4)),
      5)
HideShow
N = 186 N = 188 
0.79983 0.80433 
HideShow
#> .79983 and .80433 — the uncorrected test for the interaction crosses .80
#> between 186 and 188, by less than two ten-thousandths. A method that was
#> merely close would answer 186 here; the inversion in prob_positive() lands
#> on the published 188 because it is exact
Where following the book in R is not straightforward

Equations 12.35 through 12.37 give the noncentrality parameters for the three omnibus effects of this design, and a reader who follows them will get a different answer from the table printed beside them. This is worth working through carefully, because both answers are right and they answer slightly different questions.

Write the equations out and evaluate them at the total sample size the book reports for the A main effect.

HideShow
a_lev <- 2; b_lev <- 4; sigma2 <- 10^2; N_total <- 52

# The cell means decomposed into A effects, B effects, and AB effects.
alpha_j   <- rowMeans(mu_2x4) - mean(mu_2x4)
beta_k    <- colMeans(mu_2x4) - mean(mu_2x4)
alphabeta <- mu_2x4 - rowMeans(mu_2x4) -
  rep(colMeans(mu_2x4), each = a_lev) + mean(mu_2x4)

rho_bar <- mean(cor_lear[upper.tri(cor_lear)])
round(rho_bar, 7)
HideShow
[1] 0.5616667
HideShow
#> .5616667, the average of the six off-diagonal correlations of Table 12.28

c(lambda_A  = (N_total * sum(alpha_j^2)   / a_lev / sigma2) *
              (b_lev / (1 + (b_lev - 1) * rho_bar)),            # Equation 12.35
  lambda_B  = (N_total * sum(beta_k^2)    / b_lev / sigma2) *
              (b_lev / (1 - rho_bar)),                          # Equation 12.36
  lambda_AB = (N_total * sum(alphabeta^2) / (a_lev * b_lev) / sigma2) *
              (b_lev / (1 - rho_bar)))                          # Equation 12.37
HideShow
 lambda_A  lambda_B lambda_AB 
 8.182495 22.243346  3.262357 
HideShow
#> 8.182495, 22.243346, and 3.262357 at a total N of 52. The forms are given
#> on book p. 683; the book does not print the values for this example.

Every one of those expressions contains ρ\rho, a single correlation, where Table 12.28 supplies six different ones. The equations are introduced on p. 683 with the words “when the sphericity assumption is met,” and that is precisely the step: they replace the correlation matrix by its average correlation. Feeding the same calculation a compound-symmetric matrix built from ρ‾=.5617\bar{\rho} = .5617 reproduces them exactly, and gives the required sample sizes a reader would get by following the printed equations.

HideShow
Sigma_cs <- sigma2 * ((1 - rho_bar) * diag(4) + rho_bar)   # compound symmetry

first_N_cs <- function(C, U, target = 0.80) {
  for (N in seq(4, 600, by = 2))
    if (rm_power(mu_2x4, Sigma_cs, n = N / 2, C = C, U = U) >= target) return(N)
}
c(A  = first_N_cs(C_diff, avg_4),
  B  = first_N_cs(C_avg,  U_B4),
  AB = first_N_cs(C_diff, U_B4))
HideShow
  A   B  AB 
 52  28 176 
HideShow
#> 52, 28, and 176. The A main effect still agrees with book p. 686, because
#> its numerator has 1 degree of freedom and nothing about sphericity can
#> touch it; the other two no longer agree, and the next block shows why

So the printed equations give 176 for the interaction and the printed table gives 188. The reason is visible in one more line of arithmetic. Under compound symmetry the three eigenvalues of 𝚺*\boldsymbol{\Sigma}^{*} are all equal to σ2(1−ρ‾)=43.83\sigma^{2}(1 – \bar{\rho}) = 43.83, which is the average of the three actual ones, and Equation 12.37 amounts to dividing the whole hypothesis sum of squares by that average. The test that will actually be run divides each piece of the effect by the variance of the direction it falls in.

HideShow
ev_AB    <- eigen(t(U_B4) %*% Sigma_lear %*% U_B4, symmetric = TRUE)
Theta_AB <- C_diff %*% mu_2x4 %*% U_B4
# With C_diff and 26 per group, C diag(1/n) C' is 4 / N, so the square root
# of its inverse is sqrt(N / 4). This is the chol(Minv) step of rm_power().
signal   <- as.vector((sqrt(N_total / 4) * (Theta_AB %*% ev_AB$vectors))^2)

data.frame(error_variance = round(ev_AB$values, 3),
           signal         = round(signal, 3),
           omega          = round(signal / ev_AB$values, 3))
HideShow
  error_variance  signal omega
1         53.639 129.685 2.418
2         40.500  13.000 0.321
3         37.361   0.315 0.008
HideShow
#> nearly all of the interaction lands on the first eigenvector, whose error
#> variance (53.639) is the largest of the three

round(c(`sum of the omegas`        = sum(signal / ev_AB$values),
        `signal / average variance` = sum(signal) / mean(ev_AB$values)), 6)
HideShow
        sum of the omegas signal / average variance 
                 2.747135                  3.262357 
HideShow
#> 2.747135 versus 3.262357, the second being exactly the lambda_AB of
#> Equation 12.37 computed above

That is the whole discrepancy. This interaction is close to a difference in linear trend, and under a LEAR structure the linear-trend direction is the noisiest of the three: the variance of the linear contrast is 53.5, against 40.5 for the quadratic and 37.5 for the cubic. Averaging the three therefore flatters the effect. The three directions contribute 2.75 in total, each judged against its own variance, rather than the 3.26 that Equation 12.37 assigns, and recovering the lost power takes twelve more participants. The lesson generalizes: a mean correlation is a safe summary only when the effect of interest is spread evenly across the contrast space, and nothing guarantees that it is.

HideShow
N_grid <- seq(120, 240, by = 4)
power_curves <- data.frame(
  N     = rep(N_grid, times = 2),
  Route = rep(c("Full matrix (Table 12.28)",
                "Mean correlation (Equation 12.37)"), each = length(N_grid)),
  Power = c(vapply(N_grid, function(N)
              rm_power(mu_2x4, Sigma_lear, n = N / 2, C = C_diff, U = U_B4), 0),
            vapply(N_grid, function(N)
              rm_power(mu_2x4, Sigma_cs,   n = N / 2, C = C_diff, U = U_B4), 0)))

crossings <- data.frame(
  N     = c(176, 188),
  Power = c(rm_power(mu_2x4, Sigma_cs,   n = 88, C = C_diff, U = U_B4),
            rm_power(mu_2x4, Sigma_lear, n = 94, C = C_diff, U = U_B4)))

ggplot(power_curves, aes(x = N, y = Power, linetype = Route)) +
  geom_hline(yintercept = 0.80, colour = "#0C2340", linetype = "dotted") +
  geom_line(linewidth = 0.7) +
  geom_point(data = crossings, mapping = aes(x = N, y = Power),
             inherit.aes = FALSE, colour = "#0C2340", size = 2) +
  scale_x_continuous(breaks = c(120, 140, 160, 176, 188, 200, 220, 240)) +
  labs(x = "Total sample size", y = "Power", linetype = NULL)
Power for the interaction in the 2 × 4 mixed design as a function of total sample size, computed from the full correlation matrix of Table 12.28 and from its mean correlation. The dotted line marks power of .80.

Power for the interaction in the 2 × 4 mixed design as a function of total sample size, computed from the full correlation matrix of Table 12.28 and from its mean correlation. The dotted line marks power of .80.

Which number should a researcher plan with? The one that matches the analysis they intend to run. If Table 12.28 is the researcher’s honest belief about the covariance structure and the analysis will be the uncorrected univariate test, 188 is the required total; 176 is the required total under the compound-symmetric structure that Equations 12.35 through 12.37 presuppose, which is not the structure this example specifies. The book’s larger numbers are therefore the right ones here, not because they are larger but because they answer the question the example poses. More generally, a power calculation inherits every assumption in the covariance matrix it is given, and when an effect has more than one numerator degree of freedom, summarizing that matrix by one correlation is itself an assumption with consequences.

Other software splits on exactly this point. Superpower’s ANOVA_exact() judges the effect against the average error variance across the contrast space, as Equations 12.35 through 12.37 do, and so returns 176 for this interaction rather than the 188 of p. 686; the two agree wherever an effect has one numerator degree of freedom or its contrast space is spherical, which covers both designs of Section 12.4.1.

Key Takeaways for Mixed Designs

  • Sample Size Inputs: Pay attention to whether your software asks for Total N or N per group. Here that distinction is explicit, because the rows of 𝝁\boldsymbol{\mu} are groups: n is per row, so it is the total only when every factor is within-subjects, as in Section 12.4.1.

  • Between-Subjects Effects: The required sample size for a purely between-subjects effect (Factor A) does not depend on sphericity adjustments, which is why every route and every row of the p. 686 table agrees on 52.

  • Differing Power Requirements: Just as in standard factorial designs, the required sample size for main effects and interactions can differ widely depending on the pattern of means. Here, detecting the subtle difference in slopes between the groups (the interaction) takes several times the total sample that detecting the overall group difference takes.

  • Sphericity Is About the Contrast Space: Whether an ϵ\epsilon adjustment matters is settled by the eigenvalues of 𝑼′𝚺𝑼\mathbf{U}'\boldsymbol{\Sigma}\mathbf{U}, not by how compound symmetric the raw correlation matrix looks. The 2×3 matrix of Table 12.25 is visibly not compound symmetric yet is exactly spherical for both multi-degree-of-freedom effects; the near-compound-symmetric LEAR matrix of Table 12.28 is not, and the consequence is twelve participants.

In DMAR: planning a within-subjects polynomial trend

When the within-subjects factor is time and interest centers on a polynomial trend (for instance, a linear rate of change), the DMAR package plans sample size for the trend directly through a polynomial change model. This is the accuracy-in-parameter-estimation (AIPE) counterpart to the power analyses above: instead of targeting a level of power, ss_aipe_pcm() finds the per-group sample size so that the confidence interval on the slope of the change model is no wider than a target width. The example reproduces Kelley and Rausch (2011, Tables 1 and 2), planning a CI on the group-by-time linear slope difference (level-one error variance 0.0262, slope variance 0.003), where duration and frequency together imply M=frequency×duration+1=5M = \text{frequency} \times \text{duration} + 1 = 5 measurement occasions.

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
#> necessary_n_per_group = 278, matches Kelley & Rausch (2011, Table 1, M = 5)

# With 85% assurance the realized CI meets the target width with probability
# 0.85, not merely on average:
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
#> necessary_n_per_group = 295, matches Kelley & Rausch (2011, Table 2, M = 5)

The power-analytic counterpart, ss_power_pcm(), solves instead for the nn that detects a given slope difference with target power, reproducing the Raudenbush and Liu (2001) National Youth Survey illustration:

HideShow
# The effect is given on the standardized scale, so true_std_reg_coef is the
# argument that carries it.
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
#> necessary_n_per_group = 185 and total_N = 370, matching Raudenbush & Liu
#> (2001, p. 393)

12.5 — More Complex Designs

12.5.1 — Designs with Additional Factors

Real designs are not limited to two factors, but the rules for building the FF tests generalize rather than change. Treating every factor except subjects as fixed, the book states them on p. 687: any effect involving only between-subjects factors is tested against MSWMS_W, computed by first averaging each subject’s scores over all within-subjects factors; any effect involving a within-subjects factor is tested against the mean square for the interaction of that effect with subjects within groups, which is Equation 12.5 again; and a between-subjects effect examined at one level of a within-subjects factor uses MSWMS_W computed at just that level. The degrees of freedom are the practical check: N−aN – a for the purely between-subjects tests, and N−aN – a times the degrees of freedom of the within-subjects portion of the effect for the rest.

In R this means that the Error() term, not the formula’s right-hand side, is what encodes the design — exactly as in the two examples worked above.

12.5.2 — Latin Square Designs

When a repeated factor represents a treatment manipulation, order effects are a major concern. A Latin square design controls for these order effects by systematically varying the sequence of treatments. We can analyze this design using the principles of two-way within-subjects ANOVA, treating the two within-subjects factors as Condition (the treatment) and Time (the sequential position).

Let’s recreate the hypothetical aggressiveness study from the textbook in R. We have 6 subjects (nested in 2 squares), 3 Time periods, and 3 Conditions (Drugs A, B, and C). We will load the corresponding dataset from the AMCP package.

HideShow
# This dataset corresponds to Table 12.29 in the text
data("chapter_12_table_29")

# The imported data treats grouping variables as numeric integers. We convert
# them to factors for the ANOVA, spelling out each Condition code before
# setting the level order so the mapping is visible rather than positional.
# Table 12.30 labels the codes 1(A), 2(B), and 3(C).
latin_square_data <- chapter_12_table_29 %>%
  mutate(
    Subject = as.factor(Subject),
    Time = as.factor(Time),
    Square = as.factor(Square),
    Condition = case_when(
      Condition == 1 ~ "A",
      Condition == 2 ~ "B",
      Condition == 3 ~ "C"
    )
  ) %>%
  mutate(Condition = factor(Condition, levels = c("A", "B", "C")))

str(latin_square_data)
HideShow
'data.frame':   18 obs. of  5 variables:
 $ DV       : int  9 3 6 18 6 12 12 15 5 14 ...
 $ Subject  : Factor w/ 6 levels "1","2","3","4",..: 1 1 1 2 2 2 3 3 3 4 ...
 $ Time     : Factor w/ 3 levels "1","2","3": 1 2 3 1 2 3 1 2 3 1 ...
 $ Condition: Factor w/ 3 levels "A","B","C": 2 3 1 1 2 3 3 1 2 3 ...
 $ Square   : Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 2 ...

To find the parameter estimates for our model, the textbook manually calculates the marginal means for Subjects, Conditions, and Time (Table 12.30). We can easily replicate these using dplyr.

HideShow
# Marginal Means for Participants
latin_square_data %>%
  group_by(Subject) %>%
  summarize(Mean_Aggressiveness = mean(DV))
HideShow
# A tibble: 6 × 2
  Subject Mean_Aggressiveness
  <fct>                 <dbl>
1 1                       6  
2 2                      12  
3 3                      10.7
4 4                      11  
5 5                      11.7
6 6                       7  
HideShow
#> 6.00, 12.00, 10.67, 11.00, 11.67, 7.00 — matches Table 12.30, book p. 689

# Marginal Means for Condition
latin_square_data %>%
  group_by(Condition) %>%
  summarize(Mean_Aggressiveness = mean(DV))
HideShow
# A tibble: 3 × 2
  Condition Mean_Aggressiveness
  <fct>                   <dbl>
1 A                       12.3 
2 B                        7.33
3 C                        9.5 
HideShow
#> 12.33 (A), 7.33 (B), 9.50 (C) — matches Table 12.30, book p. 689

# Marginal Means for Time
latin_square_data %>%
  group_by(Time) %>%
  summarize(Mean_Aggressiveness = mean(DV))
HideShow
# A tibble: 3 × 2
  Time  Mean_Aggressiveness
  <fct>               <dbl>
1 1                   12.8 
2 2                    8   
3 3                    8.33
HideShow
#> 12.83, 8.00, 8.33 — matches Table 12.30, book p. 689

# Grand mean
mean(latin_square_data$DV)
HideShow
[1] 9.722222
HideShow
#> 9.72 — matches Table 12.30, book p. 689

Each parameter estimate of Table 12.30 is the corresponding marginal mean minus the grand mean, so the three sets of means above carry the whole of that table.

The textbook defines the full mathematical model for the Latin square (Equation 12.38) as an additive model without interactions:

Yijk=μ+αj+βk+πi+εijkY_{ijk} = \mu + \alpha_j + \beta_k + \pi_i + \varepsilon_{ijk}

Where αj\alpha_j is the Treatment/Condition, βk\beta_k is Time, and πi\pi_i is the Subject. Because the model explicitly restricts interactions (since not all combinations are observed in a Latin square), we can run this in R using a simple additive aov() model.

Notice that we include Subject directly as an additive factor to match the textbook’s calculation of the Restricted and Full Model Sum of Squares (ERE_R and EFE_F).

HideShow
# Fit the additive main-effects model (Eq 12.38)
latin_square_aov <- aov(DV ~ Condition + Time + Subject, data = latin_square_data)

summary(latin_square_aov)
HideShow
            Df Sum Sq Mean Sq F value Pr(>F)  
Condition    2  75.44   37.72   7.462 0.0148 *
Time         2  87.44   43.72   8.648 0.0100 *
Subject      5  98.28   19.66   3.888 0.0438 *
Residuals    8  40.44    5.06                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Condition: SS = 75.44, F = 7.46 with 2 and 8 df, p = .01; Residual SS = 40.44
#> — matches book p. 691

We reject the null hypothesis, concluding that the three drugs have different effects on aggressiveness, even after controlling for sequence timing and individual subject differences.

Because this is a model-comparison text, it is worth getting the treatment sum of squares the way the book gets it: as ER−EFE_R – E_F, the difference in error sums of squares between the full model of Equation 12.38 and the restricted model of Equation 12.39, which drops the αj\alpha_j parameters. anova() on the two fitted models does exactly that comparison.

HideShow
latin_full       <- lm(DV ~ Condition + Time + Subject, data = latin_square_data)
latin_restricted <- lm(DV ~ Time + Subject, data = latin_square_data)

c(E_F = sum(residuals(latin_full)^2),
  E_R = sum(residuals(latin_restricted)^2))
HideShow
      E_F       E_R 
 40.44444 115.88889 
HideShow
#> E_F = 40.44 and E_R = 115.89 — matches book p. 690

anova(latin_restricted, latin_full)
HideShow
Analysis of Variance Table

Model 1: DV ~ Time + Subject
Model 2: DV ~ Condition + Time + Subject
  Res.Df     RSS Df Sum of Sq      F  Pr(>F)  
1     10 115.889                              
2      8  40.444  2    75.444 7.4615 0.01483 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> E_R - E_F = 75.44 with 2 and 8 df, F = 7.46 — matches book pp. 690-691

This single-stratum additive model is an ordinary ANOVA, so it can be shown as an APA-style gt table with sums of squares, df, F, p, and partial η2\eta^2. The Condition row carries the book’s treatment test; the book gives no ANOVA table for this design, so the rest of the table is a companion summary rather than a reproduction of a printed one.

HideShow
ls_tbl  <- broom::tidy(latin_square_aov)
ss_res  <- ls_tbl$sumsq[ls_tbl$term == "Residuals"]   # E_F, for partial eta^2
ls_tbl |>
  transmute(
    Source = term, SS = sumsq, df = df, MS = meansq,
    Fstat  = statistic, p = p.value,
    # Partial eta-squared: each effect's share of effect-plus-error variance.
    peta   = if_else(term == "Residuals", NA_real_, sumsq / (sumsq + ss_res))
  ) |>
  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("Analysis of Variance for the Replicated Latin Square Design")) |>
  cols_align(align = "center", columns = -Source)
Analysis of Variance for the Replicated Latin Square Design
Source SS df MS F p Partial η2
Condition 75.44 2 37.72 7.46 0.0148 0.651
Time 87.44 2 43.72 8.65 0.0100 0.684
Subject 98.28 5 19.66 3.89 0.0438 0.708
Residuals 40.44 8 5.06


HideShow
#> the Condition row's SS = 75.44 and F = 7.46, and the Residual SS of 40.44
#> (= E_F), match book pp. 690-691

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 12: Higher-Order Designs with Within-Subjects Factors: 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