R Code and Instructions
On this page
- 12.2 — Designs with Two Within-Subjects Factors
- 12.2.1 — Omnibus Tests
- 12.2.2 — Numerical Example
- 12.2.3 — Further Investigation of Main Effects
- 12.2.4 — Further Investigation of an Interaction—Simple Effects
- 12.2.5 — Interaction Contrasts
- 12.2.7 — Assumptions
- 12.2.8 — Adjusted Univariate Tests
- 12.2.9 — Confidence Intervals
- 12.2.10 — Quasi-F Ratios
- 12.3 — One Within-Subjects Factor and One Between-Subjects Factor in the Same Design
- 12.3.1 — Omnibus Tests
- 12.3.1.4 — Numerical Example
- 12.3.2 — Further Investigation of Main Effects
- 12.3.2.1 — Between-Subjects Factor
- 12.3.2.2 — Within-Subjects Factor
- 12.3.3 — Further Investigation of an Interaction—Simple Effects
- 12.3.3.1 — Within-Subjects Effects at a Fixed Level of Between-Subjects Factor
- 12.3.3.2 — Between-Subjects Effects at a Fixed Level of Within-Subjects Factor
- 12.3.4 — Interaction Contrasts
- 12.3.5 — Assumptions
- 12.3.6 — Adjusted Univariate Tests
- 12.4 — Power Analysis and Sample Size Planning
- 12.4.1 — Designs with Two Within-Subjects Factors
- 12.4.2 — Designs with One Between-Subjects Factor and One Within-Subjects Factor
- 12.5 — More Complex Designs
- 12.5.1 — Designs with Additional Factors
- 12.5.2 — Latin Square Designs
- How to Cite This Page
- References
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 tables12.2 — Designs with Two Within-Subjects Factors
Load the data for Table 12.1 from the AMCP package.
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
[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 780HideShow
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 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 () factor. This is Equation 12.5 of the book (p. 649):
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
# 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 645HideShow
# A tibble: 2 × 2
Noise Mean_RT
<fct> <dbl>
1 Absent 500
2 Present 638HideShow
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 ' ' 1Notice from the output that both main effects (Angle and Noise) and the Angle Noise interaction are highly statistically significant ().
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
While the -values are large, we want to calculate the partial 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:
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 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
# 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].In DMAR: the sphericity bookkeeping in one call
With the base-R analysis in hand, the DMAR package supplies
the -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 value. The unadjusted 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.
| 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 |
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.
| 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%
| 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 , and shows that the choice of error term matters: Equation 12.7 divides by the pooled , 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] -48HideShow
[1] 7680HideShow
MS_pooled MS_separate
3560 2880 HideShow
F_pooled F_separate
2.157303 2.666667 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 returns the corresponding .
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
[1] 2.157303HideShow
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
t
2.666667 Because the separate-error route is an ordinary test, it also hands back a confidence interval on the quadratic trend itself, which neither ratio gives.
12.2.4 — Further Investigation of an Interaction—Simple Effects
Because we found a significant Angle 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
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 ' ' 1We can repeat this process for the other four simple effects of Table 12.6:
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 ' ' 1HideShow
#> 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 ' ' 1As reported in Table 12.6, the effect of Noise is not statistically significant at (), 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 means.
For example, suppose we want to test whether the difference between reaction times for and 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 -minus- 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
[1] 204HideShow
[1] 104040HideShow
#> 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
F_pooled F_separate
89.68966 83.90323 The mainstream route to the same pooled test is emmeans,
which takes the contrast weights against the six cell means and reports
a ratio rather than an . Squaring that returns Equation 12.11’s exactly, which is the agreement worth
seeing:
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)
icHideShow
contrast estimate SE df t.ratio p.value
(0 vs 8) x Noise 204 21.5 18 9.470 <0.0001HideShow
[1] 89.68966Note 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
# 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 660HideShow
0 4 8
0 4090 3950 4350
4 3950 6850 6150
8 4350 6150 8850HideShow
0 4 8
0 1.0000000 0.7462600 0.7230294
4 0.7462600 1.0000000 0.7898747
8 0.7230294 0.7898747 1.0000000Assumption 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
# 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 660HideShow
Absent Present
Absent 4088.889 4000.000
Present 4000.000 9551.111HideShow
Absent Present
Absent 1.0000000 0.6400743
Present 0.6400743 1.0000000Assumption 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
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 240HideShow
Dif_Angle0 Dif_Angle4 Dif_Angle8
Dif_Angle0 5800 7000 2600
Dif_Angle4 7000 11400 5000
Dif_Angle8 2600 5000 4360HideShow
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.000000012.2.8 — Adjusted Univariate Tests
Because sphericity is often violated in repeated measures designs, it is standard practice to apply -adjustments (Geisser-Greenhouse or Huynh-Feldt ) to the degrees of freedom.
While calculating these by hand is tedious, the car
package provides the Anova() function, which automatically
calculates these adjusted -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-08Notice that
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 is necessarily 1.00 — the
value the book reports for the
main effect. The Huynh-Feldt 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 values
coincide. Because the omnibus effects are so strong, every adjusted
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 main
effect, and a one-way analysis of the Table 12.11 scores (each subject’s
noise effect at each angle) returns the interaction. DMAR’s
anova_within() takes a wide matrix of repeated columns and
returns that one-way with its
-adjusted companions, and
mauchly_test() reports the sphericity test on the same
matrix.
| W | statistic | df | p_value | n_subjects | n_levels | method |
|---|---|---|---|---|---|---|
| 0.960 | 0.326 | 2 | 0.8497 | 10 | 3 | Mauchly’s test of sphericity |
| 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 |
| W | statistic | df | p_value | n_subjects | n_levels | method |
|---|---|---|---|---|---|---|
| 0.894 | 0.898 | 2 | 0.6381 | 10 | 3 | Mauchly’s test of sphericity |
| 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 |
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- 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 -ratios are no longer appropriate for testing the fixed effect. Instead, a Quasi-F ratio ( ) must be constructed by combining multiple mean squares in both the numerator and denominator:
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- 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 ()
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 663HideShow
# A tibble: 3 × 2
Angle Mean_RT
<fct> <dbl>
1 0 510
2 4 620.
3 8 718.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 Angle). However, because one factor is between and one is within, the full model and corresponding error terms change.
The Subjects factor () is no longer crossed with the Age factor (). Instead, Subjects are nested under Age (). As a result, the error terms change:
The between-subjects effect (Age) is tested against the variability of Subjects nested within Age:
The within-subjects effect (Angle) and the interaction (Age Angle) are both tested against the interaction of Angle with the nested subjects:
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
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 ' ' 1HideShow
#> 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. 668The output shows that both main effects and the interaction are statistically significant at the level.
The same split-plot results as an APA-style gt table reproduce Table 12.19. The between-subjects effect (Age) is tested against , while the within-subjects effect (Angle) and the interaction are tested against ; 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 . 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 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 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].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 (). 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 ' ' 1Notice that the -value () and -value () 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:
| 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 |
The same model as a gtsummary regression table, with the confidence interval on the Age difference:
| 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 (), 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: ).
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 as the denominator for all contrasts.
Equation 12.26 (Separate Error Term): Uses a specific 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.
- Approach 1: Pooled Error Term (Equation 12.25)
The emmeans package draws its error term from the fitted
model, which here means on 36 degrees of freedom — the 1,511.67 that Table 12.19
prints as 1,512.
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
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
[1] 0.2431092- Approach 2: Separate Error Term (Equation 12.26)
To obtain the separate error term, we manually apply the contrast weights () 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:
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.
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 ().
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 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:
Testing the within-subjects effect at a fixed level of the between-subjects factor (effectively a one-way within-subjects ANOVA).
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 () 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 (): Uses only the variance from the Young participants.
- Pooled Error Term (): 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
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 ' ' 1In the Error: Subject:Angle stratum, , making the simple effect of
Angle for Young individuals highly significant ().
The pooled alternative divides the same numerator mean square by from the full split-plot table, which the book also reports:
HideShow
[1] 47.9470812.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 Angle condition?
By looking only at , we effectively have a standard one-way between-subjects design. Again, we must choose an error term:
Separate Error Term (): Uses the variance within groups only at the condition.
Pooled Error Term (): 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 condition and running a standard between-subjects ANOVA:
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 ' ' 1The Mean Square for Age is . The Residual Mean Square (our separate error term, ) is . This results in an -value of with and degrees of freedom (). Thus, the age difference at is nonsignificant.
The pooled alternative here is , which Equation 12.31 builds from the two error sums of squares of Table 12.19:
HideShow
[1] 7080HideShow
[1] 3.07627112.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 for young subjects and for old subjects, so the contrast to be tested is . In terms of the six cell means its coefficients are .
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
# A tibble: 2 × 2
Age Quadratic_Trend
<fct> <dbl>
1 Young -48
2 Old 27HideShow
#> -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_AxBquadHideShow
[1] 4687.5HideShow
[1] 3.100882HideShow
[1] 4.038047The separate-error test is the Age row of the model
already fitted, so car::Anova() reports its and directly; dividing numerator and
denominator by leaves
the ratio unchanged.
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 ' ' 1To better understand the nature of the Age 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
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.
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 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 , 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 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 main effect and the interaction — are tested
against the same error term, , there is only one and one 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-03The single of .94 is shared by the Angle and Age Angle rows, exactly as the book explains it must be (p. 679). Because 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
(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 or .
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 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 , where holds the population cell means with one row per between-subjects group and one column per within-subjects condition, says which comparison among the groups is at issue, and which comparison among the repeated measures. When there is no between-subjects factor, is simply the number 1. In a mixed design the main effect has contrasting the groups and averaging over the repeated measures, the main effect has averaging over the groups and contrasting the repeated measures, and the interaction contrasts on both sides.
Let be the covariance matrix of the transformed scores, with eigenvalues ; let be the number of rows of , the number of columns of , and the error degrees of freedom for groups. The two sums of squares that make up the univariate (or “averaged”) test are then exactly
independently of one another, where is the squared size of the effect along the th eigenvector of divided by that direction’s variance . Three cases follow, and they are the whole story.
- . There is one eigenvalue and it cancels between numerator and denominator, leaving an ordinary noncentral with and degrees of freedom. Every effect with one numerator degree of freedom lands here, which is exactly why such tests need no sphericity correction.
- with all equal. The common eigenvalue cancels again, leaving an ordinary noncentral with and degrees of freedom and noncentrality . Equal eigenvalues is sphericity, stated in the contrast space where it actually matters rather than on the raw correlation matrix.
- with unequal
. The ratio is
not an at all. The test rejects
when , 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 correction changes the critical value but not the statistic: the degrees of freedom become and . Putting 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 , , , and for the effect at hand.
12.4.1 — Designs with Two Within-Subjects Factors
- Example 1: A Within-Subjects Design (Power Calculation)
Imagine a researcher plans a study with participants and an . The population standard deviation is 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: has one row, and is the 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 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 :
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
[1] 0.2151877Notice that for all three effects, the uncorrected test has the exact same power as the -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, has a single column, so is a single number and there is nothing for an to correct.
- 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 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 120HideShow
#> 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 aboveEach contrast space here has either a single dimension or equal eigenvalues, so every test is an ordinary noncentral — case 1 for , case 2 for and the interaction. Sample size planning is then a search: step 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.808Table 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
B AB
0.0197 0.0202 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 adjustment is applied: with 1 numerator degree of freedom, sphericity holds by construction. The two -based rows of Table 12.26 — Greenhouse-Geisser and Huynh-Feldt — are not reproduced above, and it is worth saying why. Those tests estimate from the same data that produce , 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 : 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 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 repeated measures, and under compound symmetry the variance of that average is . The noncentrality carries the reciprocal of that variance, which is the second parenthesis of Equation 12.35.
- 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 (so per group). The standard deviation is 1.0, and the correlation between the two time points is 0.50. Now has one row per group, and 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 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.
- 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.361HideShow
[1] 0.9748Mild 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 266The remaining two rows of that table, for the -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 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
N = 186 N = 188
0.79983 0.80433 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.5616667HideShow
#> .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.37HideShow
lambda_A lambda_B lambda_AB
8.182495 22.243346 3.262357 Every one of those expressions contains , 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 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 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 are all equal to , 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.008HideShow
sum of the omegas signal / average variance
2.747135 3.262357 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.
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 are groups:
nis 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 adjustment matters is settled by the eigenvalues of , 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 measurement occasions.
| 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%
The power-analytic counterpart, ss_power_pcm(), solves
instead for the that detects a
given slope difference with target power, reproducing the Raudenbush and
Liu (2001) National Youth Survey illustration:
| 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 |
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 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 , 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 computed at just that level. The degrees of freedom are the practical check: for the purely between-subjects tests, and 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
# 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
# A tibble: 3 × 2
Condition Mean_Aggressiveness
<fct> <dbl>
1 A 12.3
2 B 7.33
3 C 9.5 HideShow
# A tibble: 3 × 2
Time Mean_Aggressiveness
<fct> <dbl>
1 1 12.8
2 2 8
3 3 8.33HideShow
[1] 9.722222Each 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:
Where is the
Treatment/Condition, is
Time, and 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 ( and ).
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 ' ' 1We 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 , 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 parameters. anova()
on the two fitted models does exactly that comparison.
HideShow
E_F E_R
40.44444 115.88889 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 ' ' 1This 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 . 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 η<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 | |||
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
Arel-Bundock V (2026). modelsummary: Summary Tables and Plots for Statistical Models and Data: Beautiful, Customizable, and Publication-Ready. doi:10.32614/CRAN.package.modelsummary https://doi.org/10.32614/CRAN.package.modelsummary. R package version 2.6.0, https://CRAN.R-project.org/package=modelsummary.
Ben-Shachar M, Makowski D, Lüdecke D, Patil I, Wiernik B, Thériault R, Waggoner P (2026). effectsize: Indices of Effect Size. doi:10.32614/CRAN.package.effectsize https://doi.org/10.32614/CRAN.package.effectsize. R package version 1.0.3, https://CRAN.R-project.org/package=effectsize.
Fox J, Weisberg S, Price B (2026). car: Companion to Applied Regression. doi:10.32614/CRAN.package.car https://doi.org/10.32614/CRAN.package.car. R package version 3.1-5, https://CRAN.R-project.org/package=car.
Iannone R, Cheng J, Schloerke B, Haughton S, Hughes E, Lauer A, François R, Seo J, Brevoort K, Roy O (2026). gt: Easily Create Presentation-Ready Display Tables. doi:10.32614/CRAN.package.gt https://doi.org/10.32614/CRAN.package.gt. R package version 1.3.0, https://CRAN.R-project.org/package=gt.
Kelley K (2026). DMAR: Design, Measurement, and Analysis in R (DMAR). R package version 1.2.0, https://kenkelley.org.
Lenth R, Piaskowski J (2026). emmeans: Estimated Marginal Means, aka Least-Squares Means. doi:10.32614/CRAN.package.emmeans https://doi.org/10.32614/CRAN.package.emmeans. R package version 2.0.4, https://CRAN.R-project.org/package=emmeans.
Maxwell S, Delaney H, Kelley K (2026). AMCP: Data Sets to Accompany Designing Experiments and Analyzing Data: A Model Comparison Perspective (Maxwell, Delaney, and Kelley, 2027, 4th Edition). doi:10.32614/CRAN.package.AMCP https://doi.org/10.32614/CRAN.package.AMCP. R package version 2.0.0, https://CRAN.R-project.org/package=AMCP.
Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.
R Core Team (2026). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria. doi:10.32614/R.manuals https://doi.org/10.32614/R.manuals. https://www.R-project.org/.
Robinson D, Hayes A, Couch S, Hvitfeldt E (2026). broom: Convert Statistical Objects into Tidy Tibbles. doi:10.32614/CRAN.package.broom https://doi.org/10.32614/CRAN.package.broom. R package version 1.0.13, https://CRAN.R-project.org/package=broom.
Sjoberg D, Larmarange J, Curry M, de la Rua E, Lavery J, Whiting K, Zabor E (2026). gtsummary: Presentation-Ready Data Summary and Analytic Result Tables. doi:10.32614/CRAN.package.gtsummary https://doi.org/10.32614/CRAN.package.gtsummary. R package version 2.5.1, https://CRAN.R-project.org/package=gtsummary.
Wickham H (2023). tidyverse: Easily Install and Load the ‘Tidyverse’. doi:10.32614/CRAN.package.tidyverse https://doi.org/10.32614/CRAN.package.tidyverse. R package version 2.0.0, https://CRAN.R-project.org/package=tidyverse.