R Code and Instructions
On this page
- 13.3 — A Brief Review of Analysis for Designs with Two Levels
- 13.4 — Multivariate Analysis of Within-Subjects Designs with Three Levels
- 13.4.1 — Need for Multiple D Variables
- 13.4.4 — Matrix Formulation and Determinants
- 13.4.5 — Test Statistic
- 13.5 — Multivariate Analysis of Within-Subjects Designs with a Levels
- 13.5.1 — Forming D Variables
- 13.5.2 — Test Statistic
- 13.5.3 — Numerical Example
- 13.6 — Measures of Effect
- 13.7 — Choice of D Variables
- 13.8 — Tests of Individual Contrasts
- 13.9 — Multiple-Comparison Procedures: Determination of Critical Values
- 13.9.1 — Planned Comparisons
- 13.9.2 — Pairwise Comparisons
- 13.9.3 — Post Hoc Complex Comparisons
- 13.10 — Confidence Intervals for Contrasts
- 13.11 — The Relationship Between the Multivariate Approach and the Mixed-Model Approach
- 13.11.1 — Orthonormal Contrasts
- 13.11.2 — Comparison of the Two Approaches
- 13.12 — Multivariate and Mixed-Model Approaches for Testing Contrasts
- 13.12.1 — Numerical Example
- 13.12.2 — The Difference in Error Terms
- 13.12.3 — Which Error Term Is Better?
- 13.13 — Statistical Power
- How to Cite This Page
- References
Examples follow the book’s section numbers.
HideShow
# Load all of the packages used.
library(AMCP) # the textbook's data sets
library(DMAR) # design, measurement, and analysis
library(tidyverse) # data wrangling and plotting (dplyr, ggplot2, and friends)
library(car) # Anova() for Type II/III tests and regression diagnostics
library(gt) # polished HTML tables
library(gtsummary) # publication-ready regression / comparison tables
library(modelsummary) # side-by-side model-comparison tablesChapter 13 introduces the multivariate approach to analyzing one-way within-subjects designs as a robust alternative to the traditional univariate mixed-model approach. The methodology relies on transforming repeated measures into multiple difference (D) variables, utilizing matrix formulation and determinants to construct models for omnibus hypothesis testing. Beyond the initial test statistic, the chapter outlines the procedures for calculating effect sizes, testing planned or post hoc contrasts, and constructing confidence intervals. A significant portion of the chapter is dedicated to comparing this multivariate approach with the mixed-model approach, emphasizing how they differ in their underlying assumptions, calculation of specific error terms, and reliance on the sphericity assumption. By evaluating statistical power and Type I and Type II error rates across both methods, the chapter equips researchers with the theoretical framework needed to choose the most appropriate analytical strategy for their specific data structures.
Chapter 1 explains how the AMCP package names the
book’s data sets; the conventions described there apply throughout. This
chapter draws on five of them: chapter_13_table_1 (the
two-level design), chapter_13_table_2 (the three-level
design), chapter_13_table_5 (the two hypothetical data sets
that illustrate the determinant), chapter_13_table_6 (the
McCarthy IQ scores), and chapter_13_table_10 (the linear
and quadratic trend variables for the Table 13.2 data).
13.3 — A Brief Review of Analysis for Designs with Two Levels
As we transition into the multivariate approach for within-subjects designs, it is helpful to start with a brief review of the two-level design (e.g., Time 1 and Time 2). For designs with exactly two levels, the mixed-model approach and the multivariate approach are mathematically identical.
The core logic of testing a within-subjects effect with two levels involves creating a difference score () for each subject. The null hypothesis that the population means of Time 1 and Time 2 are equal is equivalent to hypothesizing that the population mean of these difference scores is zero.
Let’s load the data for Table 13.1 and create difference scores.
HideShow
Time1 Time2
1 2 3
2 4 7
3 6 8
4 8 9
5 10 13HideShow
Time1 Time2 Difference
1 2 3 1
2 4 7 3
3 6 8 2
4 8 9 1
5 10 13 3To test if this difference is significant, we can use the difference
score on the left-hand side of the ~ symbol in R’s linear
model function lm(). By placing a 1 on the right side of
the tilde (Difference ~ 1), we are asking R to test an
intercept-only model. This tests whether the grand mean (the intercept)
of the difference scores is significantly different from zero.
HideShow
Call:
lm(formula = Difference ~ 1, data = chapter_13_table_1)
Residuals:
1 2 3 4 5
-1.000e+00 1.000e+00 -1.406e-17 -1.000e+00 1.000e+00
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.0000 0.4472 4.472 0.0111 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 1 on 4 degrees of freedomNotice that the summary returns a value of 4.472. Because for an analysis with 1 numerator degree of freedom, , which is the statistic the book reports for these data (Equation 13.6, p. 711).
We can confirm this directly with the book’s closed form (Equation 13.6), plugging in the actual numbers from Table 13.1.
HideShow
n = 5 Dbar = 2 s^2_D = 1 F = 20 HideShow
[1] 7.708647Finally, the most common way researchers analyze this simple two-level design is by running a traditional paired-samples t-test. The intercept-only linear model we just ran is mathematically equivalent to both a one-sample t-test on the difference scores and a paired t-test on the original variables.
HideShow
One Sample t-test
data: chapter_13_table_1$Difference
t = 4.4721, df = 4, p-value = 0.01106
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
0.758336 3.241664
sample estimates:
mean of x
2 HideShow
Paired t-test
data: chapter_13_table_1$Time2 and chapter_13_table_1$Time1
t = 4.4721, df = 4, p-value = 0.01106
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
0.758336 3.241664
sample estimates:
mean difference
2 All these approaches yield the exact same p-value, demonstrating the underlying equivalence between univariate linear models, paired t-tests, and the foundational logic of the multivariate approach for two-level designs.
13.4 — Multivariate Analysis of Within-Subjects Designs with Three Levels
13.4.1 — Need for Multiple Variables
When a within-subjects factor has three levels, the analysis becomes more complex. With only two levels, a single difference score captures everything. With three levels, there are multiple possible comparisons and contrasts.
To completely capture the pattern of differences across three levels, we must create two difference scores (D variables). The exact comparisons do not matter for the omnibus test, as long as they are linearly independent.
Let’s load the data for a three-level design (Table 13.2) and create two difference variables: (Time 2 minus Time 1) and (Time 3 minus Time 2).
HideShow
Time1 Time2 Time3
1 2 3 5
2 4 7 9
3 6 8 8
4 8 9 8
5 10 13 15
6 3 4 9
7 6 9 8
8 9 11 10HideShow
HideShow
Time1 Time2 Time3 D1 D2
1 2 3 5 1 2
2 4 7 9 3 2
3 6 8 8 2 0
4 8 9 8 1 -1
5 10 13 15 3 2
6 3 4 9 1 5
7 6 9 8 3 -1
8 9 11 10 2 -1HideShow
D1 D2
2 1 13.4.4 — Matrix Formulation and Determinants
In a univariate test, we look at the sum of squared errors (). In a multivariate test, we have multiple variables that might be correlated, so we use a Sum of Squares and Cross-Products (SSCP) matrix.
The SSCP matrix captures the variance of each D variable on the diagonal and the covariance (cross-products) between the D variables off the diagonal. We need to construct this matrix for both the Full Model (where means are freely estimated) and the Restricted Model (where population means are forced to zero).
HideShow
n <- nrow(chapter_13_table_2)
D1_bar <- mean(chapter_13_table_2$D1)
D2_bar <- mean(chapter_13_table_2$D2)
# Full Model SSCP Matrix Elements
E11_F <- sum((chapter_13_table_2$D1 - D1_bar)^2)
E22_F <- sum((chapter_13_table_2$D2 - D2_bar)^2)
E12_F <- sum((chapter_13_table_2$D1 - D1_bar) * (chapter_13_table_2$D2 - D2_bar))
# Assemble the Full Model Matrix E(F)
E_F <- matrix(c(E11_F, E12_F,
E12_F, E22_F), nrow = 2, byrow = TRUE)
# Restricted Model SSCP Matrix Elements (Predicted score is 0)
E11_R <- sum(chapter_13_table_2$D1^2)
E22_R <- sum(chapter_13_table_2$D2^2)
E12_R <- sum(chapter_13_table_2$D1 * chapter_13_table_2$D2)
# Assemble the Restricted Model Matrix E(R)
E_R <- matrix(c(E11_R, E12_R,
E12_R, E22_R), nrow = 2, byrow = TRUE)
print("Full Model Matrix E(F):")HideShow
[1] "Full Model Matrix E(F):"HideShow
[,1] [,2]
[1,] 6 -3
[2,] -3 32HideShow
[1] "Restricted Model Matrix E(R):"HideShow
[,1] [,2]
[1,] 38 13
[2,] 13 40To distill these matrices into a single number representing “generalized variance” across multiple dimensions, we calculate the determinant of each matrix.
The determinant accounts for the variance of , the variance of , and the redundancy (correlation)
between them. We can calculate determinants in R using the
det() function, and then plug them into Equation 13.23 to
find our F-statistic.
HideShow
Determinant of E(F): 183
Determinant of E(R): 1351 HideShow
#> |E(F)| = 183, |E(R)| = 1351 — matches book p. 719
# Calculate the F-statistic (Equation 13.23)
# F = ((det(E_R) - det(E_F)) / 2) / (det(E_F) / (n - 2))
F_stat <- ((det_ER - det_EF) / 2) / (det_EF / (n - 2))
cat("Observed F-statistic:", F_stat,
"\np-value:", pf(F_stat, 2, n - 2, lower.tail = FALSE), "\n")HideShow
Observed F-statistic: 19.14754
p-value: 0.002485348 The determinant of the full model is and that of the restricted model is . The resulting of () says the time periods differ.
13.4.5 — Test Statistic
Until now only a single dependent variable was on the left-hand side
of the ~ symbol. To run this test automatically, we bind
our difference scores into a matrix using cbind() and place
them on the left side of the equation.
HideShow
Analysis of Variance Table
Df Pillai approx F num Df den Df Pr(>F)
(Intercept) 1 0.86454 19.148 2 6 0.002485 **
Residuals 7
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1Notice that the automated MANOVA function returns an of , confirming the determinant calculation done by hand.
In multivariate analysis, there are multiple ways to combine eigenvalues to form a test statistic. R allows you to specify these alternatives. For a one-way within-subjects design testing an intercept, these tests yield the exact same F-statistic, but it is useful to know how to call them.
HideShow
Analysis of Variance Table
Df Wilks approx F num Df den Df Pr(>F)
(Intercept) 1 0.13545 19.148 2 6 0.002485 **
Residuals 7
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1HideShow
Analysis of Variance Table
Df Hotelling-Lawley approx F num Df den Df Pr(>F)
(Intercept) 1 6.3825 19.148 2 6 0.002485 **
Residuals 7
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1HideShow
Analysis of Variance Table
Df Roy approx F num Df den Df Pr(>F)
(Intercept) 1 6.3825 19.148 2 6 0.002485 **
Residuals 7
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1An interval for the dominant eigenvalue
The discriminating power of a multivariate within-subjects test depends on how the difference vectors spread out, and the largest eigenvalue is the single most informative summary of that spread. Start with the point estimates:
HideShow
[1] 4.6202377 0.8083337An asymptotic confidence interval for the population eigenvalue, formed on the log scale under multivariate normality, comes from DMAR. The point estimate it reports is the same largest sample eigenvalue printed above.
| term | value |
|---|---|
| ci_lower | 1.621 |
| eigenvalue | 4.620 |
| ci_upper | 13.172 |
Confidence level: 95%
The point estimate agrees with eigen(), and the interval
conveys how imprecisely that dominant direction of within-subject
variability is pinned down with only eight subjects. The book does not
report this quantity; it is shown here because the width of the interval
is the clearest available statement of how little a sample of eight
fixes the covariance structure that the whole multivariate test rests
on.
Figure 13.2 — the determinant as enclosed area
Before leaving determinants, the book pauses on two hypothetical data sets (Table 13.5) measured on two difference variables, and . The scores are identical across the two sets, and so are the scores; only the pairing differs, and hence only the – correlation. Anything computed one variable at a time is therefore the same in both sets. The determinant is not, and that is the point. AMCP distributes the table, so there is no need to retype it.
HideShow
SetA_D1 SetA_D2 SetB_D1 SetB_D2
1 -3 -3.1 -3 -1.1
2 -3 -2.9 -3 1.2
3 -2 -2.2 -2 -2.9
4 -2 -1.8 -2 2.8
5 -1 -1.1 -1 -3.1
6 -1 -0.9 -1 3.2
7 0 -0.2 0 -1.8
8 0 0.2 0 1.9
9 1 0.8 1 -2.2
10 1 1.2 1 2.1
11 2 1.9 2 -0.9
12 2 2.1 2 0.8
13 3 2.8 3 -0.2
14 3 3.2 3 0.2HideShow
SetA_D1 SetA_D2 SetB_D1 SetB_D2
0.000000e+00 0.000000e+00 0.000000e+00 1.110223e-16 HideShow
SetA_D1 SetA_D2 SetB_D1 SetB_D2
56.00 56.38 56.00 56.38 HideShow
#> Each D1 column sums to 0 with sum of squares 56.00, and each D2 column sums to 0
#> with sum of squares 56.38 — matches Table 13.5, book p. 717
# Sums of cross-products, the one place the two data sets part company.
with(chapter_13_table_5, c(SetA = sum(SetA_D1 * SetA_D2), SetB = sum(SetB_D1 * SetB_D2)))HideShow
SetA SetB
56.0 -0.5 Because the raw scores are deviations from zero, the matrix whose determinant the book takes is simply the cross-product matrix of the two columns.
HideShow
Data set (a) Data set (b)
21.28 3157.03 The book plots the two data sets one above the other and joins the points so the area they enclose is visible. Reproducing that ordering takes one step: the odd-numbered subjects trace the lower edge of each cloud and the even-numbered subjects trace the upper edge, so walking up one and back down the other closes the outline.
HideShow
# Join the two edges to show the spread of each cloud.
hull_order <- function(d) rbind(d[seq(1, nrow(d), by = 2), ],
d[rev(seq(2, nrow(d), by = 2)), ])
label_a <- "Data set (a): nearly collinear"
label_b <- "Data set (b): nearly uncorrelated"
outline <- bind_rows(
data.frame(hull_order(data.frame(D1 = set_a[, 1], D2 = set_a[, 2])), Set = label_a),
data.frame(hull_order(data.frame(D1 = set_b[, 1], D2 = set_b[, 2])), Set = label_b)
)
points_df <- bind_rows(
data.frame(D1 = set_a[, 1], D2 = set_a[, 2], Set = label_a),
data.frame(D1 = set_b[, 1], D2 = set_b[, 2], Set = label_b)
)
det_labels <- data.frame(
Set = c(label_a, label_b),
D1 = -3.4,
D2 = 3.4,
label = sprintf("Determinant = %.2f", c(det_a, det_b))
)HideShow
ggplot(points_df, aes(x = D1, y = D2)) +
geom_polygon(data = outline, fill = NA, color = "#0C2340", linewidth = 0.4) +
geom_point(shape = 21, fill = "white", color = "black", size = 2.4, stroke = 0.7) +
geom_text(data = det_labels, aes(label = label),
color = "#0C2340", fontface = "bold", hjust = 0, size = 3.6) +
facet_wrap(~ Set, ncol = 1) +
coord_fixed(ratio = 1, xlim = c(-3.6, 3.6), ylim = c(-3.6, 3.6)) +
labs(x = expression(italic(D)[1]~"score"), y = expression(italic(D)[2]~"score"))Figure 13.2. Scores on and for the two hypothetical data sets in Table 13.5.
Both panels have the same spread along each axis taken alone, yet the determinant for data set (b) (3157.03) is roughly 150 times that for data set (a) (21.28). The determinant captures what the one-dimensional variances miss: when and are nearly redundant the points hug a line and enclose almost nothing, but when they are nearly uncorrelated the points fill the square. This generalized variance, summarized by the determinant of the error matrix, is what the multivariate test statistic in this chapter is built on.
13.5 — Multivariate Analysis of Within-Subjects Designs with Levels
So far, we have seen how to analyze data from within-subjects designs consisting of either two or three levels. The same logic applies regardless of the number of levels. For a factor with levels, we must form difference () variables.
The null hypothesis that all levels have equal population means is mathematically equivalent to the hypothesis that all difference variables have population means of zero.
13.5.1 — Forming Variables
In the general case, we must construct a sum-of-squares and cross-products (SSCP) matrix for both the full model () and the restricted model (). Because there are difference variables, these matrices have rows and columns, with distinct cross-product terms in each.
13.5.2 — Test Statistic
The test statistic relies on the determinants of these two matrices, using a formula that is remarkably similar to the univariate statistic (Equation 13.24):
This observed is then compared to a critical distribution with numerator degrees of freedom and denominator degrees of freedom.
13.5.3 — Numerical Example
Let’s apply this to a numerical example using the hypothetical McCarthy IQ scores from Chapter 11. We have 12 subjects measured at 4 time points (30, 36, 42, and 48 months). Because , we need to define three variables.
HideShow
data(chapter_13_table_6)
# Create the three difference variables (matching Table 13.7)
chapter_13_table_6$D1 <- chapter_13_table_6$Months36 - chapter_13_table_6$Months30
chapter_13_table_6$D2 <- chapter_13_table_6$Months42 - chapter_13_table_6$Months36
chapter_13_table_6$D3 <- chapter_13_table_6$Months48 - chapter_13_table_6$Months42
# View the first few rows to verify the D variables
head(chapter_13_table_6)HideShow
Months30 Months36 Months42 Months48 D1 D2 D3
1 108 96 110 122 -12 14 12
2 103 117 127 133 14 10 6
3 96 107 106 107 11 -1 1
4 84 85 92 99 1 7 7
5 118 125 125 116 7 0 -9
6 110 107 96 91 -3 -11 -5HideShow
D1 D2 D3
4 3 2 Manual Matrix Construction
To see exactly how the SSCP matrices are formed, we can calculate the
matrices for the Full
and Restricted models. Instead of writing out all 9 elements manually as
we did in the example,
we can use R’s crossprod() function, which automates the
sum of squares and cross-products for a set of columns.
HideShow
n <- nrow(chapter_13_table_6)
a <- 4
# Full Model Matrix E(F): Uses mean-centered variables (deviations from the mean)
e1_F <- chapter_13_table_6$D1 - mean(chapter_13_table_6$D1)
e2_F <- chapter_13_table_6$D2 - mean(chapter_13_table_6$D2)
e3_F <- chapter_13_table_6$D3 - mean(chapter_13_table_6$D3)
E_F <- crossprod(cbind(e1_F, e2_F, e3_F))
# Restricted Model Matrix E(R): Uses the raw scores (deviations from zero)
E_R <- crossprod(cbind(chapter_13_table_6$D1, chapter_13_table_6$D2, chapter_13_table_6$D3))
# Full Model Matrix E(F)
print(E_F)HideShow
e1_F e2_F e3_F
e1_F 878 -329 -440
e2_F -329 1004 399
e3_F -440 399 658HideShow
[,1] [,2] [,3]
[1,] 1070 -185 -344
[2,] -185 1112 471
[3,] -344 471 706These matrices match those in the text.
Now, we extract their determinants and calculate the F-statistic.
HideShow
Determinant of E(F): 290177920
Determinant of E(R): 506853568 HideShow
#> |E(F)| = 290,177,920 and |E(R)| = 506,853,568 — matches book p. 721
# Calculate the F-statistic
num_df <- a - 1
den_df <- n - a + 1
F_stat <- ((det_ER - det_EF) / num_df) / (det_EF / den_df)
p_value <- pf(F_stat, num_df, den_df, lower.tail = FALSE)
cat("Observed F-statistic:", F_stat,
"\nP-value:", p_value, "\n")HideShow
Observed F-statistic: 2.240098
P-value: 0.1528393 The multivariate test yields an of 2.2401 with a value of .1528, so the mean differences across the four time points are nonsignificant at the .05 level. The book notes that this is the same conclusion reached from the – and -adjusted mixed-model tests of Chapter 11, whereas the unadjusted mixed-model test on these same data was significant.
Automated Approach
Statistical software can handle these matrix operations for us in a
single line of code. We bind our three difference scores together and
use them as the dependent variable in a manova().
HideShow
Analysis of Variance Table
Df Pillai approx F num Df den Df Pr(>F)
(Intercept) 1 0.42749 2.2401 3 9 0.1528
Residuals 11 Notice that the automated test gives the same and . We can also request the other standard multivariate test statistics. For a one-way within-subjects design testing an intercept, these statistics all map to the same .
HideShow
Analysis of Variance Table
Df Pillai approx F num Df den Df Pr(>F)
(Intercept) 1 0.42749 2.2401 3 9 0.1528
Residuals 11 HideShow
Analysis of Variance Table
Df Wilks approx F num Df den Df Pr(>F)
(Intercept) 1 0.57251 2.2401 3 9 0.1528
Residuals 11 HideShow
Analysis of Variance Table
Df Hotelling-Lawley approx F num Df den Df Pr(>F)
(Intercept) 1 0.7467 2.2401 3 9 0.1528
Residuals 11 HideShow
Analysis of Variance Table
Df Roy approx F num Df den Df Pr(>F)
(Intercept) 1 0.7467 2.2401 3 9 0.1528
Residuals 11 The four statistics all map to the same approximate for this intercept-only design. A
compact gt table collects them side by side, with the
common , degrees of freedom, and
value:
HideShow
# Pull each multivariate statistic and its approximate F from anova.mlm().
# Each anova() object stores the test value in a column named after the statistic
# (e.g., "Pillai", "Wilks"), so read that column by name; the F, df, and p columns
# are shared across all four.
tests <- c("Pillai", "Wilks", "Hotelling-Lawley", "Roy")
mantab <- lapply(tests, function(tt) {
a <- anova(MANOVA_4DV, test = tt) # row 1 = Intercept term
data.frame(Test = tt, Statistic = a[[tt]][1], Fapprox = a$`approx F`[1],
num_df = a$`num Df`[1], den_df = a$`den Df`[1], p = a$`Pr(>F)`[1])
})
do.call(rbind, mantab) |>
gt() |>
fmt_number(columns = c(Statistic, Fapprox), decimals = 3) |>
fmt_number(columns = p, decimals = 4) |>
cols_label(Fapprox = md("Approx. *F*"), num_df = md("*df*~num~"),
den_df = md("*df*~den~"), p = md("*p*")) |>
tab_header(title = md("**Table 1**. Multivariate Tests of the Omnibus Hypothesis (McCarthy Data)")) |>
cols_align(align = "center", columns = -Test)| Table 1. Multivariate Tests of the Omnibus Hypothesis (McCarthy Data) | |||||
| Test | Statistic | Approx. F | dfnum | dfden | p |
|---|---|---|---|---|---|
| Pillai | 0.427 | 2.240 | 3 | 9 | 0.1528 |
| Wilks | 0.573 | 2.240 | 3 | 9 | 0.1528 |
| Hotelling-Lawley | 0.747 | 2.240 | 3 | 9 | 0.1528 |
| Roy | 0.747 | 2.240 | 3 | 9 | 0.1528 |
Using the car Package for MANOVA
Additionally, the Anova() function from the
car package can be used. This package is particularly
useful because it easily accommodates different types of sums of
squares, which becomes critical when working with unbalanced factorial
designs.
Although Type II and Type III sums of squares are identical for an
intercept-only model like ours, it is useful to become familiar with the
car::Anova() function for more complex multivariate linear
models.
HideShow
Type III MANOVA Tests: Pillai test statistic
Df test stat approx F num Df den Df Pr(>F)
(Intercept) 1 0.42749 2.2401 3 9 0.1528HideShow
Type III MANOVA Tests: Pillai test statistic
Df test stat approx F num Df den Df Pr(>F)
(Intercept) 1 0.42749 2.2401 3 9 0.1528One detail worth not stumbling over: both calls print the heading
“Type III MANOVA Tests.” That is not a mistake in the call. With only an
intercept in the model there is nothing for the two types to disagree
about, so car::Anova() takes the Type III path either way
and labels it accordingly. The identical test statistics underneath are
the substance.
13.6 — Measures of Effect
Just as in between-subjects designs, researchers using within-subjects designs should report measures of effect size alongside their -values. However, because there are two fundamentally different approaches to analyzing within-subjects data (the mixed-model approach of Chapter 11 and the multivariate approach of Chapter 13), there are two different ways to calculate association strength (omega squared, ).
The mixed-model includes individual differences (subject variability) in the conceptualization of “total variance.” The multivariate , on the other hand, excludes this subject variability from the denominator.
The formula for multivariate omega squared relies on Wilks’s Lambda (), which is the ratio of the determinants we calculated earlier: .
Let’s calculate this using the McCarthy IQ data from Table 13.6. Recall that we had subjects, time points, and . We also found the determinants for the full and restricted models.
HideShow
Wilks's Lambda: 0.5725084 HideShow
Multivariate Omega Squared: 0.2823093 The multivariate is approximately .28, meaning age accounts for roughly 28% of the variance once individual differences are excluded from total variance. The mixed-model the book reports for these same data is only .04 — about one seventh as large.
The multivariate version is almost always larger precisely because it removes subject variability from the definition of total variance. The book does not read this as an advantage: it is a correct answer to a question we usually do not want answered, and so the mixed-model version of omega squared is the one the book generally recommends reporting.
13.7 — Choice of Variables
When we analyzed the three-level data in Section 13.4, we chose to create difference scores representing adjacent time periods: and .
Does the specific choice of variables matter? As the text notes, the answer is no. As long as you create linearly independent contrasts, the omnibus multivariate test will yield the exact same F-statistic and -value.
To prove this, let’s re-analyze the data from Table 13.2. Because “Time” is a quantitative factor, we might prefer to create difference variables representing linear and quadratic trends instead of adjacent differences.
HideShow
[1] "Time1" "Time2" "Time3"HideShow
# Create Linear and Quadratic D variables
# Linear trend coefficients for a=3: -1, 0, 1
chapter_13_table_2$D_lin <- chapter_13_table_2$Time3 - chapter_13_table_2$Time1
# Quadratic trend coefficients for a=3: -1, 2, -1
chapter_13_table_2$D_quad <- 2 * chapter_13_table_2$Time2 - chapter_13_table_2$Time1 - chapter_13_table_2$Time3
# Create a Subject column so the output matches Table 13.10
chapter_13_table_2$Subject <- 1:nrow(chapter_13_table_2)
# View the new variables
chapter_13_table_2[, c("Subject", "D_lin", "D_quad")]HideShow
Subject D_lin D_quad
1 1 3 -1
2 2 5 1
3 3 2 2
4 4 0 2
5 5 5 1
6 6 6 -4
7 7 2 4
8 8 1 3Now, let’s run the exact same manova() function we used
in Section 13.4, but using our new trend variables.
HideShow
Analysis of Variance Table
Df Pillai approx F num Df den Df Pr(>F)
(Intercept) 1 0.86454 19.148 2 6 0.002485 **
Residuals 7
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1The statistic is , the same value obtained earlier with the adjacent-difference variables. The internal matrix numbers, however, are not the same at all. Rather than assert that, we can compute both error matrices for the trend variables and watch the determinants change while their ratio does not.
HideShow
D_lin D_quad
D_lin 32 -26
D_quad -26 44HideShow
D_lin D_quad
D_lin 104 -2
D_quad -2 52HideShow
|E(F)| |E(R)|
732 5404 HideShow
[1] 19.14754The determinants are entirely different from the and found in Section 13.4, and yet Equation 13.23 returns the identical . The choice of variables alters the matrix entries; what it leaves alone is the ratio of generalized variances on which the omnibus test depends.
In AMCP
The AMCP package distributes the linear and quadratic trend variables
for this example already tabulated, as chapter_13_table_10
(Table 13.10), so we can verify the same conclusion without recomputing
the contrasts by hand. Loading that table and binding its two columns
into a manova() reproduces the omnibus test, and a
one-sample test on each column
reproduces the individual trend tests.
HideShow
Linear Quadratic
1 3 -1
2 5 1
3 2 2
4 0 2
5 5 1
6 6 -4
7 2 4
8 1 3HideShow
# Omnibus multivariate test that the Linear and Quadratic trends jointly differ from 0.
# Note intercept = TRUE: summary() for a manova object drops the intercept row by
# default, and the intercept IS the hypothesis of interest here, so without it the
# table comes back empty.
fit_poly <- manova(as.matrix(poly) ~ 1)
summary(fit_poly, test = "Hotelling-Lawley", intercept = TRUE)HideShow
Df Hotelling-Lawley approx F num Df den Df Pr(>F)
(Intercept) 1 6.3825 19.148 2 6 0.002485 **
Residuals 7
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1HideShow
One Sample t-test
data: poly$Linear
t = 3.9686, df = 7, p-value = 0.005402
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
1.212512 4.787488
sample estimates:
mean of x
3 HideShow
One Sample t-test
data: poly$Quadratic
t = 1.1282, df = 7, p-value = 0.2964
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
-1.096015 3.096015
sample estimates:
mean of x
1 The book does not print a for these contrasts; it prints an . The two are the same test, because a contrast has 1 numerator degree of freedom:
HideShow
t t_squared
3.968627 15.750000 The linear-trend of is the same contrast tested in Section 13.8 directly from the raw scores, and is the the book reports there.
13.8 — Tests of Individual Contrasts
While the choice of variables does not matter for the omnibus test, different variables provide different information about specific hypotheses. A significant omnibus MANOVA only tells us that a difference exists somewhere. To pinpoint the difference, we must test individual contrasts.
Testing an individual contrast in the multivariate approach is incredibly straightforward: it is simply a univariate test on a single variable.
Let’s test the hypothesis that the linear trend in our three-level design is zero. We already created the linear trend variable (D_lin). The Full Model estimates the mean of this variable freely, and the Restricted Model forces it to zero.
The sums of squared errors for this single variable are and — the entries in the first row and first column of the two matrices computed in Section 13.7, which is exactly the book’s point that a contrast test reuses part of the omnibus computation. Because this is a single variable, no matrices or determinants are needed; the standard univariate formula (Equation 13.28) applies:
HideShow
E_F E_R
32 104 HideShow
F-statistic for the Linear Contrast: 15.75 To automate this in R, we apply the same intercept-only
lm() or t.test() approach from Section
13.3.
HideShow
Call:
lm(formula = D_lin ~ 1, data = chapter_13_table_2)
Residuals:
Min 1Q Median 3Q Max
-3.00 -1.25 -0.50 2.00 3.00
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.0000 0.7559 3.969 0.0054 **
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 2.138 on 7 degrees of freedomThe lm() output gives a of . Because for an analysis with 1 numerator
degree of freedom, ,
the value computed from and
just above and the value the
book reports on p. 728.
We can conclude that there is a statistically significant linear
trend over time. We could follow this exact same procedure to test the
quadratic trend (using D_quad) or any other specific
contrast of interest.
13.9 — Multiple-Comparison Procedures: Determination of Critical Values
We have now seen how to calculate the observed statistic for an individual contrast. The second step is determining the appropriate critical value. If we plan only a single comparison, the per-comparison alpha level applies directly, with 1 numerator and denominator degrees of freedom.
HideShow
[1] 5.591448However, if we are testing multiple contrasts, we must adjust our critical values to maintain our familywise error rate ().
13.9.1 — Planned Comparisons
If we plan our comparisons in advance, we use the Bonferroni approach: instead of a per-comparison alpha of .05, we use , where is the number of planned comparisons.
To implement the Bonferroni approach in R, we simply calculate the exact value for our univariate contrast and compare it to .
HideShow
Raw p-value for the Linear Trend: 0.005401769 HideShow
Bonferroni Critical p-value: 0.025 Because the raw value (.0054) is smaller than the Bonferroni critical value (.025), the linear trend remains statistically significant after adjusting for the two planned tests.
R also provides tools for automating these adjustments.
Automating Bonferroni Adjustments with p.adjust()
Instead of manually dividing our alpha level () and comparing it to our raw
-values, we can use the
p.adjust() function. You provide it with a vector of your
raw -values, and it multiplies
them by (capping at 1.0). You can
then compare these adjusted -values directly to your standard .
HideShow
[1] 0.01080354Because this adjusted value remains below our standard threshold, we can confidently conclude the contrast is statistically significant while safely maintaining our familywise error rate.
Note that this adjusted value
differs from the raw one. The two are distinct arithmetic routes to the
same conclusion: the book’s route divides the alpha threshold () and leaves the value alone, whereas
p.adjust() does the reverse, multiplying the raw value () so it can be
compared against the familiar .
Both are equivalent; R’s version spares the reader from remembering a
custom alpha level.
13.9.2 — Pairwise Comparisons
For all pairwise comparisons the recommendation is again Bonferroni, with , the number of distinct pairs. This is where the within-subjects design parts company with the between-subjects design: the book explicitly recommends against Tukey’s HSD here, because the HSD’s homogeneity-of-variance requirement is violated unless sphericity holds, whereas Bonferroni requires no such assumption.
HideShow
C alpha_per_comparison
3.00000000 0.01666667 13.9.3 — Post Hoc Complex Comparisons
If we decide after looking at the data to test a complex comparison, we must use the Roy–Bose critical value, the multivariate extension of Scheffé’s method.
The book’s example asks, for the Table 13.2 data, whether level 1 differs from the average of levels 2 and 3 — a contrast chosen after noticing that levels 2 and 3 have similar means. The variable is , and the observed comes from Equation 13.6 exactly as before.
HideShow
[1] -2.0 -4.0 -2.0 -0.5 -4.0 -3.5 -2.5 -1.5HideShow
Dbar = -2.5 s^2_D = 1.571429 F = 31.81818 Now for the critical value. Equation 13.29 scales the omnibus critical up by .
HideShow
a <- 3
n <- 8
alpha_FW <- 0.05
# Find the critical F for the omnibus test (df1 = a-1, df2 = n-a+1)
F_crit_omnibus <- qf(alpha_FW, df1 = a - 1, df2 = n - a + 1, lower.tail = FALSE)
# Calculate the Roy-Bose Critical Value (Equation 13.29)
CV_RB <- ((n - 1) * (a - 1) * F_crit_omnibus) / (n - a + 1)
cat("Omnibus Critical F:", F_crit_omnibus, "\n")HideShow
Omnibus Critical F: 5.143253 HideShow
Roy-Bose Critical Value: 12.00092 Two small points about these numbers. The omnibus critical is 5.1433; the book reads 5.14 from Appendix Table A.2 (p. 730). Carrying that rounded 5.14 through Equation 13.29 gives the 11.99 the book prints, whereas carrying R’s unrounded value through gives 12.0009. The difference is entirely the rounding of the tabled critical value, and it changes nothing here: the observed of 31.818 clears either threshold, so even after having looked at the data we can conclude that the population mean of level 1 differs from the average of levels 2 and 3.
HideShow
[1] 11.99333The omnibus critical and the Roy–Bose critical value are linked by construction: the omnibus test is significant if and only if some complex contrast exceeds the Roy–Bose threshold.
13.10 — Confidence Intervals for Contrasts
A confidence interval for a within-subjects contrast uses the formula:
Where is the critical value (a -value or the square root of an -value). The choice of dictates how we control the error rate (Unadjusted, Bonferroni, or Roy-Bose).
Let’s use the McCarthy IQ data (Table 13.6) to build confidence intervals for the mean difference between 36 months and 30 months.
HideShow
Sample Mean Difference: 4 HideShow
Standard Error of Difference: 2.579053 Unadjusted Confidence Interval
First, let’s form an unadjusted 95% confidence interval, assuming this was our only planned comparison.
HideShow
n <- length(D1)
df <- n - 1
# Critical t-value for unadjusted alpha = .05 (two-tailed). Equivalently, the square
# root of the critical F with 1 and n - 1 degrees of freedom, which is how the book
# writes w in Equation 13.30.
t_crit_unadj <- qt(0.025, df, lower.tail = FALSE)
c(t_crit = t_crit_unadj, sqrt_F_crit = sqrt(qf(0.05, 1, df, lower.tail = FALSE)))HideShow
t_crit sqrt_F_crit
2.200985 2.200985 HideShow
Margin of error: 5.676458 HideShow
Unadjusted 95% CI: [ -1.676458 , 9.676458 ]Bonferroni Adjusted Confidence Interval
Now, suppose we regard this contrast as one of a family of three adjacent-wave differences (36 minus 30, 42 minus 36, and 48 minus 42, so ). We need to widen the interval to hold familywise alpha at .05.
HideShow
F_crit w
7.952590 2.820034 HideShow
Margin of error: 7.273017 HideShow
Bonferroni Adjusted 95% CI: [ -3.273017 , 11.27302 ]HideShow
[1] 1.28126Both intervals are centered at 4.00, but the Bonferroni interval is roughly 28% wider because it buys 95% confidence for all three intervals simultaneously. Both contain zero, so there is no significant difference between IQ at 30 and 36 months either way.
Scaling Contrasts for Meaningful Slopes
Finally, the textbook emphasizes that when you create confidence intervals for trends (like a linear trend), the specific coefficients you choose will change the numerical bounds of the interval. If you want the interval to reflect a meaningful metric, such as the “average change per month,” you must scale the contrast coefficients properly.
Let’s use the textbook’s formula to scale the coefficients for a linear slope across the four time points (30, 36, 42, and 48 months).
HideShow
Deviations: -9 -3 3 9 Sum of squares: 180 HideShow
Scaled Slope Coefficients: -0.05 -0.01666667 0.01666667 0.05 HideShow
#> -9/180, -3/180, 3/180, 9/180 — matches book p. 733
# Create the D variable representing the slope
chapter_13_table_6$D_slope <-
slope_coefs[1] * chapter_13_table_6$Months30 +
slope_coefs[2] * chapter_13_table_6$Months36 +
slope_coefs[3] * chapter_13_table_6$Months42 +
slope_coefs[4] * chapter_13_table_6$Months48
# Run an intercept-only model to get the confidence interval
lm_slope <- lm(D_slope ~ 1, data = chapter_13_table_6)
# Output the estimated slope
summary(lm_slope)$coefficientsHideShow
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.5 0.2230792 2.241357 0.04659037HideShow
2.5 % 97.5 %
(Intercept) 0.009006088 0.9909939The output reproduces the book’s last line of Table 13.12: the average slope is 0.50 IQ points per month, with a 95% confidence interval running from 0.009 to 0.991. Because the interval excludes zero, the population mean rate of change can be inferred to be positive; because it is nearly a full IQ point wide, the rate itself remains poorly pinned down, which the book attributes squarely to the small sample.
A Publication-Quality Table of the Contrasts
Each contrast above is an intercept-only model on its own variable, so the estimate, standard error, and confidence interval the book lists in Table 13.12 are just the intercepts of those models. Fitting them as a set lets us present them in one polished table. We build the four variables (three adjacent differences, plus the 48-vs-30 difference) and the linear-slope variable, then fit one intercept-only model to each.
HideShow
mc <- chapter_13_table_6
mc$D_36_30 <- mc$Months36 - mc$Months30
mc$D_42_36 <- mc$Months42 - mc$Months36
mc$D_48_42 <- mc$Months48 - mc$Months42
mc$D_48_30 <- mc$Months48 - mc$Months30 # the one significant pairwise difference
fit_36_30 <- lm(D_36_30 ~ 1, data = mc)
fit_42_36 <- lm(D_42_36 ~ 1, data = mc)
fit_48_42 <- lm(D_48_42 ~ 1, data = mc)
fit_48_30 <- lm(D_48_30 ~ 1, data = mc)
fit_slope <- lm(D_slope ~ 1, data = mc) # D_slope built in the previous chunkWith modelsummary, each contrast is a column, the intercept is the estimated mean difference, its standard error is in parentheses, and the fit statistics line the foot of the table:
HideShow
modelsummary(
list("36 - 30" = fit_36_30, "42 - 36" = fit_42_36, "48 - 42" = fit_48_42,
"48 - 30" = fit_48_30, "Mean linear" = fit_slope),
estimate = "{estimate}",
statistic = "({std.error})", # standard errors in parentheses, APA style
gof_map = c("nobs", "aic", "bic", "logLik"),
stars = TRUE,
output = "gt" # gt backend, to match the gtsummary table below
)| 36 – 30 | 42 – 36 | 48 – 42 | 48 – 30 | Mean linear | |
|---|---|---|---|---|---|
| (Intercept) | 4.000 | 3.000 | 2.000 | 9.000 | 0.500 |
| (2.579) | (2.758) | (2.233) | (3.693) | (0.223) | |
| Num.Obs. | 12 | 12 | 12 | 12 | 12 |
| AIC | 89.6 | 91.2 | 86.1 | 98.2 | 30.8 |
| BIC | 90.5 | 92.1 | 87.1 | 99.2 | 31.8 |
| Log.Lik. | -42.784 | -43.588 | -41.053 | -47.091 | -13.412 |
| + p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001 | |||||
The same contrasts as a gtsummary table, each under its own spanning header, with the 95% confidence intervals shown alongside the estimates:
| Characteristic |
36 – 30
|
48 – 30
|
Mean linear
|
||||||
|---|---|---|---|---|---|---|---|---|---|
| Beta | 95% CI | p-value | Beta | 95% CI | p-value | Beta | 95% CI | p-value | |
| (Intercept) | 4.0 | -1.7, 9.7 | 0.15 | 9.0 | 0.87, 17 | 0.033 | 0.50 | 0.01, 0.99 | 0.047 |
| Abbreviation: CI = Confidence Interval | |||||||||
Of the five contrasts, only “48 minus 30” and the mean linear slope exclude zero. The book draws the moral directly: all three adjacent differences contain zero, which might suggest the four population means are equal, yet the linear trend across the full 30-to-48-month span is clearly positive. Neither an omnibus test nor a scan of adjacent means is necessarily the most powerful way to look at a quantitative within-subjects factor.
13.11 — The Relationship Between the Multivariate Approach and the Mixed-Model Approach
At first glance, the multivariate approach (which uses determinants of error matrices) and the mixed-model approach (which uses standard mean squares, like ) appear entirely different. However, we can use orthonormal contrasts to reveal the mathematical connection between them.
An orthonormal contrast meets two conditions:
Orthogonal: The sum of the cross-products of the coefficients equals zero.
Normalized: The sum of the squared coefficients equals exactly 1.0.
13.11.1 — Orthonormal Contrasts
Let’s return to the data in Table 13.2. We previously defined our linear and quadratic trend variables ( and ). We know they are orthogonal, but they are not normalized.
We can normalize them by dividing each coefficient by the square root of the sum of the squared coefficients for that contrast. Let’s do this in R to create and .
HideShow
data(chapter_13_table_2)
# Define the original unnormalized coefficients
coef_lin <- c(-1, 0, 1)
coef_quad <- c(-1, 2, -1)
# Normalization step: Divide by the square root of the sum of squared coefficients
norm_lin <- coef_lin / sqrt(sum(coef_lin^2))
norm_quad <- coef_quad / sqrt(sum(coef_quad^2))
cat("Normalized Linear Coefficients:", norm_lin, "\n")HideShow
Normalized Linear Coefficients: -0.7071068 0 0.7071068 HideShow
Normalized Quadratic Coefficients: -0.4082483 0.8164966 -0.4082483 HideShow
Sum of cross-products: 0 HideShow
Sums of squared coefficients: 1 1 HideShow
# Apply the normalized coefficients to create D*_1 and D*_2
chapter_13_table_2$D_star_1 <-
norm_lin[1] * chapter_13_table_2$Time1 +
norm_lin[2] * chapter_13_table_2$Time2 +
norm_lin[3] * chapter_13_table_2$Time3
chapter_13_table_2$D_star_2 <-
norm_quad[1] * chapter_13_table_2$Time1 +
norm_quad[2] * chapter_13_table_2$Time2 +
norm_quad[3] * chapter_13_table_2$Time3
# View the normalized D variables
chapter_13_table_2[, c("Time1", "Time2", "Time3", "D_star_1", "D_star_2")]HideShow
Time1 Time2 Time3 D_star_1 D_star_2
1 2 3 5 2.1213203 -0.4082483
2 4 7 9 3.5355339 0.4082483
3 6 8 8 1.4142136 0.8164966
4 8 9 8 0.0000000 0.8164966
5 10 13 15 3.5355339 0.4082483
6 3 4 9 4.2426407 -1.6329932
7 6 9 8 1.4142136 1.6329932
8 9 11 10 0.7071068 1.2247449One call for the orthogonality check
The two hand checks above are the whole definition, and they are
worth doing once by hand. For a larger contrast set, writing them out
pair by pair gets tedious, and is_orthogonal_set() performs
the same checks for every pair at once, reporting each pairwise dot
product alongside the overall verdict and confirming that each
contrast’s coefficients sum to zero. Its contrasts argument
takes a matrix whose columns are contrasts and whose rows are
levels.
| term | value |
|---|---|
| all_orthogonal | 1 |
| all_contrasts_sum_to_zero | 1 |
| n_contrasts | 2 |
| dot[linear . quadratic] | 0 |
The verdict agrees with the hand computation: both contrasts sum to zero and their dot product is zero, so the set is orthogonal — and, since each column’s squared coefficients sum to 1, orthonormal.
Now, we can compute the sum of squares and cross-products matrices for the full model () and the restricted model (), using our normalized variables. We will use the same intercept-only regression trick from earlier in the chapter.
HideShow
# Run intercept-only models on the normalized variables
model_D1_star <- lm(D_star_1 ~ 1, data = chapter_13_table_2)
model_D2_star <- lm(D_star_2 ~ 1, data = chapter_13_table_2)
# Combine the residuals into a matrix
resid_matrix_star <- cbind(model_D1_star$residuals, model_D2_star$residuals)
# Calculate the Full Model Error Matrix E*(F)
E_star_F <- t(resid_matrix_star) %*% resid_matrix_star
# Calculate the Restricted Model Error Matrix E*(R)
Y_matrix_star <- cbind(chapter_13_table_2$D_star_1, chapter_13_table_2$D_star_2)
E_star_R <- t(Y_matrix_star) %*% Y_matrix_star
# Full Model Error Matrix E*(F)
print(E_star_F)HideShow
[,1] [,2]
[1,] 16.000000 -7.505553
[2,] -7.505553 7.333333HideShow
[,1] [,2]
[1,] 52.0000000 -0.5773503
[2,] -0.5773503 8.6666667These matrices are only a change of metric, so the omnibus test should be untouched. Rather than assert that, compute it:
HideShow
|E*(F)| |E*(R)|
61.0000 450.3333 HideShow
[1] 19.1475413.11.2 — Comparison of the Two Approaches
So, why go through the trouble of normalizing? Because the resulting and matrices allow us to easily extract the mixed-model ANOVA results.
Consider the trace of our matrix. The trace is simply the sum of the diagonal elements.
- Trace of .
Similarly, let’s look at the trace of the matrix:
- Trace of .
If we subtract the trace of the full model from the trace of the restricted model:
- .
37.3333 is exactly the sum of squares for the Time main effect in the mixed-model ANOVA.
HideShow
# Extract the traces and compute the Mixed-Model SS
trace_E_star_F <- sum(diag(E_star_F))
trace_E_star_R <- sum(diag(E_star_R))
SS_interaction <- trace_E_star_F
SS_time <- trace_E_star_R - trace_E_star_F
cat(
"Trace of E*(F) [SS Interaction / Error]:", SS_interaction, "\n",
"Trace of E*(R):", trace_E_star_R, "\n",
"Trace of E*(R) - Trace of E*(F) [SS Time Effect]:", SS_time, "\n"
)HideShow
Trace of E*(F) [SS Interaction / Error]: 23.33333
Trace of E*(R): 60.66667
Trace of E*(R) - Trace of E*(F) [SS Time Effect]: 37.33333 These same numbers are the cells of the mixed-model ANOVA the book
reports as Table 13.13. We can assemble that table in an APA-style
gt layout directly from the traces, dividing each sum of
squares by its degrees of freedom to get the mean squares and the :
HideShow
# Mixed-model ANOVA for the Table 13.2 data (a = 3 levels, n = 8 subjects),
# built from the traces of the orthonormal error matrices computed above.
a_lev <- 3
n_sub <- 8
df_time <- a_lev - 1 # 2
df_axs <- (a_lev - 1) * (n_sub - 1) # 14
ms_time <- SS_time / df_time
ms_axs <- SS_interaction / df_axs
F_time <- ms_time / ms_axs
p_time <- pf(F_time, df_time, df_axs, lower.tail = FALSE)
tibble::tibble(
Source = c("Time", "Subjects × Time"),
SS = c(SS_time, SS_interaction),
df = c(df_time, df_axs),
MS = c(ms_time, ms_axs),
Fstat = c(F_time, NA_real_),
p = c(p_time, NA_real_)
) |>
gt() |>
fmt_number(columns = c(SS, MS, Fstat), decimals = 4) |>
fmt_number(columns = p, decimals = 4) |>
sub_missing(missing_text = "") |>
cols_label(Fstat = md("*F*"), p = md("*p*")) |>
tab_header(title = md("**Table 2**. Mixed-Model Analysis of the Data in Table 13.2")) |>
cols_align(align = "center", columns = -Source)| Table 2. Mixed-Model Analysis of the Data in Table 13.2 | |||||
| Source | SS | df | MS | F | p |
|---|---|---|---|---|---|
| Time | 37.3333 | 2 | 18.6667 | 11.2000 | 0.0012 |
| Subjects × Time | 23.3333 | 14 | 1.6667 | ||
The same table from the raw scores
Everything above was built from the orthonormal error matrices, which
is the point of the section. It is worth seeing the same table arrive by
the ordinary route, from the raw repeated measures, as a check that the
trace identity really did reproduce the mixed-model analysis and not
something that merely resembles it. anova_within() takes
the wide data directly and reports the adjustments the mixed-model
approach needs when sphericity is in doubt.
| adjustment | F_value | df_1 | df_2 | p_value | epsilon |
|---|---|---|---|---|---|
| none | 11.200 | 2 | 14 | 0.0012 | NA |
| Greenhouse-Geisser | 11.200 | 1.289 | 9.022 | 0.0063 | 0.644 |
| Huynh-Feldt | 11.200 | 1.455 | 10.186 | 0.0043 | 0.728 |
| lower_bound | 11.200 | 1 | 7 | 0.0123 | 0.500 |
The unadjusted row is identical to the table assembled from the traces. The remaining rows are the and adjustments of Chapter 11: they leave alone and shrink the degrees of freedom, which is precisely the behavior Section 13.12 goes on to criticize for contrasts.
This mathematical relationship (Equation 13.34) highlights a fundamental difference between the two approaches:
The Multivariate Approach uses the determinant of the error matrices, meaning it uses all the information, including the off-diagonal covariance elements.
The Mixed-Model Approach uses only the trace (the diagonals) of the error matrices, meaning it entirely ignores the off-diagonal covariance elements.
13.12 — Multivariate and Mixed-Model Approaches for Testing Contrasts
The central question for testing individual contrasts comes down to which error term to use.
The multivariate approach (separate error term) uses an error term specific to the exact contrast being tested, . This is the variance of that particular variable.
The mixed-model approach (pooled error term) uses a single error term that averages the variances of all orthonormal contrasts. That pooled term is .
13.12.1 — Numerical Example
Let’s look at the linear trend from Table 13.2. Earlier in the chapter, using the multivariate approach, we found an observed . Let’s recreate both the multivariate and mixed-model statistics to see exactly how they differ.
HideShow
data(chapter_13_table_2)
# Create the normalized Linear Trend D variable (from previous section)
coef_lin <- c(-1, 0, 1)
norm_lin <- coef_lin / sqrt(sum(coef_lin^2))
chapter_13_table_2$D_star_1 <-
norm_lin[1] * chapter_13_table_2$Time1 +
norm_lin[2] * chapter_13_table_2$Time2 +
norm_lin[3] * chapter_13_table_2$Time3
# Calculate values for the formulas
n <- 8
a <- 3
# E*(F) is the sum of squared deviations from the mean for our normalized variable
E_star_F <- sum((chapter_13_table_2$D_star_1 - mean(chapter_13_table_2$D_star_1))^2)
# The numerator is the difference in errors between restricted and full models
# E*(R) - E*(F) = n * (mean of D*_1)^2
numerator <- n * (mean(chapter_13_table_2$D_star_1))^2
# Multivariate F (Uses Separate Error Term)
# Denominator is simply the variance of the D*_1 variable
multi_denom <- E_star_F / (n - 1)
F_multi <- numerator / multi_denom
# Mixed-Model F (Uses Pooled Error Term)
# Denominator is MS_AxS, the trace of E*(F) divided by its degrees of freedom. We
# recompute it here rather than retyping 1.6667, so the page stands on its own.
MS_AxS <- SS_interaction / ((a - 1) * (n - 1))
F_mixed <- numerator / MS_AxS
cat(
"Numerator (n * mean^2):", numerator, "\n",
"MS_AxS (pooled error term):", MS_AxS, "\n",
"Multivariate F (Separate Error Term):", F_multi, "\n",
"Mixed-Model F (Pooled Error Term):", F_mixed, "\n"
)HideShow
Numerator (n * mean^2): 36
MS_AxS (pooled error term): 1.666667
Multivariate F (Separate Error Term): 15.75
Mixed-Model F (Pooled Error Term): 21.6 For the linear trend, the mixed-model of 21.6 is nearly 40% larger than the multivariate of 15.75. Does that make the mixed-model approach better? Not necessarily. The mixed-model is larger here only because its denominator, , is smaller than the variance specific to the linear trend, . A larger can arise for just two reasons: sampling error, which is as likely to shrink an as to swell it, or a violated homogeneity assumption, in which case the mixed-model error term is simply too small and the Type I error rate exceeds .05. Neither is an advantage.
13.12.2 — The Difference in Error Terms
Writing the two statistics side by side shows that there is exactly one difference between them (Equations 13.38 and 13.39): the multivariate approach divides by , the variance of the contrast actually being tested, while the mixed-model approach divides by , the average variance across all orthonormal contrasts.
HideShow
separate_error_term pooled_error_term
2.285714 1.666667 13.12.3 — Which Error Term Is Better?
When the contrast’s own variance happens to be larger than the pooled average, as the linear trend’s is, the mixed-model approach gains. The reverse case is just as easy to produce. Let’s look at another contrast: the simple difference between Time 1 and Time 2.
HideShow
# Create the normalized D variable for Time 2 - Time 1
coef_t1_t2 <- c(-1, 1, 0)
norm_t1_t2 <- coef_t1_t2 / sqrt(sum(coef_t1_t2^2))
chapter_13_table_2$D_star_T1_T2 <-
norm_t1_t2[1] * chapter_13_table_2$Time1 +
norm_t1_t2[2] * chapter_13_table_2$Time2 +
norm_t1_t2[3] * chapter_13_table_2$Time3
# E*(F) for this specific contrast
E_star_F_T1_T2 <- sum((chapter_13_table_2$D_star_T1_T2 - mean(chapter_13_table_2$D_star_T1_T2))^2)
# Numerator
numerator_T1_T2 <- n * (mean(chapter_13_table_2$D_star_T1_T2))^2
# Multivariate F
multi_denom_T1_T2 <- E_star_F_T1_T2 / (n - 1)
F_multi_T1_T2 <- numerator_T1_T2 / multi_denom_T1_T2
# Mixed-Model F
# Uses the same pooled error term as before!
F_mixed_T1_T2 <- numerator_T1_T2 / MS_AxS
cat(
"Numerator (n * mean^2):", numerator_T1_T2, "\n",
"Separate error term:", multi_denom_T1_T2, "\n",
"Multivariate F (Separate Error Term):", F_multi_T1_T2, "\n",
"Mixed-Model F (Pooled Error Term):", F_mixed_T1_T2, "\n"
)HideShow
Numerator (n * mean^2): 16
Separate error term: 0.4285714
Multivariate F (Separate Error Term): 37.33333
Mixed-Model F (Pooled Error Term): 9.6 Notice how things have flipped. The multivariate of 37.33 is now almost four times the mixed-model of 9.6 — the book puts it the other way round, that the mixed-model is “only slightly more than one-quarter as large.” The reason is the same mechanism running in the opposite direction: the variance specific to the difference score, , is far smaller than the pooled of 1.6667.
The pair of examples makes the book’s point better than either does alone. When homogeneity of the variances fails, the pooled error term is too small for some contrasts and too large for others. It is not that the mixed-model approach is uniformly liberal or uniformly conservative; it is wrong in both directions at once, on different contrasts in the same analysis, and no adjustment repairs that, because an adjustment changes only the critical value and leaves in the denominator.
Is the assumption met here? A sphericity check
The book’s recommendation rests on how unlikely the homogeneity
assumption is to hold. Base R tests it directly on the multivariate
linear model with mauchly.test():
HideShow
# Mauchly's test of sphericity, from base R's stats package, on the Table 13.2 data.
wide_13_2 <- as.matrix(chapter_13_table_2[, c("Time1", "Time2", "Time3")])
mlm_13_2 <- lm(wide_13_2 ~ 1)
idata <- data.frame(Time = factor(c("Time1", "Time2", "Time3")))
mauchly.test(mlm_13_2, X = ~ 1, idata = idata)HideShow
Mauchly's test of sphericity
Contrasts orthogonal to
~1
data: SSD matrix from lm(formula = wide_13_2 ~ 1)
W = 0.44816, p-value = 0.09001In DMAR the same test arrives alongside the estimated that the adjustment itself uses:
| W | statistic | df | p_value | n_subjects | n_levels | method |
|---|---|---|---|---|---|---|
| 0.448 | 4.816 | 2 | 0.0900 | 8 | 3 | Mauchly’s test of sphericity |
| epsilon_method | epsilon |
|---|---|
| Greenhouse-Geisser | 0.644 |
| Huynh-Feldt | 0.728 |
| lower_bound | 0.500 |
With eight subjects, Mauchly’s test does not reject sphericity, yet is a long way from 1. That gap is exactly the situation the book warns about: Mauchly’s test has little power at this sample size, so failing to reject it is no evidence that the assumption holds. The book’s conclusion is that contrasts in within-subjects designs should routinely be tested with the multivariate approach and a separate error term, rather than conditioned on a sphericity test. These values are companion additions; the book does not report them for these data.
13.13 — Statistical Power
We now turn to power analysis and sample size planning for the multivariate approach to the one-way within-subjects design.
The role of the noncentrality parameter
As always, power depends on the alpha level, the numerator degrees of freedom, the denominator degrees of freedom, and the noncentrality parameter ().
For the multivariate approach, Equation 13.40 gives in matrix form:
Its three ingredients are:
: a vector of the population means for each condition.
: the population covariance matrix, holding the variances of the conditions and the correlations between them.
: a contrast matrix (or vector) that defines exactly what hypothesis is being tested.
If has rows, Equation 13.40 returns the
noncentrality parameter for the omnibus test. If is a single row vector (e.g.,
-1 0 1), it returns the parameter for that one contrast.
Nothing here needs a package: solve() inverts the matrix
and pf() supplies the noncentral probability.
HideShow
# Equation 13.40, written out. Sigma is built from a correlation matrix and a common
# variance; C has a - 1 rows for the omnibus test or 1 row for a single contrast.
ncp_multivariate <- function(mu, R, variance, C, n) {
Sigma <- variance * R
Cmu <- C %*% mu
n * as.numeric(t(Cmu) %*% solve(C %*% Sigma %*% t(C)) %*% Cmu)
}
# Power of the multivariate omnibus test: df1 = a - 1, df2 = n - a + 1.
power_multivariate <- function(mu, R, variance, C, n, a, alpha = 0.05) {
lambda <- ncp_multivariate(mu, R, variance, C, n)
df1 <- nrow(C)
df2 <- if (df1 == 1) n - 1 else n - a + 1
pf(qf(1 - alpha, df1, df2), df1, df2, ncp = lambda, lower.tail = FALSE)
}Comparing the power of the approaches
When planning a study, you might wonder whether to use the univariate mixed-model approach (with the Greenhouse–Geisser adjustment) or the multivariate approach.
The book shows there is no universal winner: which one is more powerful depends on how the pattern of the population means lines up against the population correlation matrix. It works two scenarios, both with means that span the same range and the same population variance of 96, and both violating sphericity.
Scenario 1 has a pure linear trend in the means (), but the most disparate means ( and ) have the lowest correlation () while adjacent means have the highest (). Scenario 2 reorders the means to so that the two most disparate means are the pair with the highest correlation. The first pattern favors the univariate approach, the second the multivariate.
HideShow
variance_pop <- 96 # the book's population variance; sd = 9.79796
C_omnibus <- rbind(c(-1, 1, 0),
c(0, -1, 1))
mu_scenario_1 <- c(10, 13, 16)
cor_matrix_1 <- matrix(c(1.0, 0.6, 0.3,
0.6, 1.0, 0.6,
0.3, 0.6, 1.0), nrow = 3)
mu_scenario_2 <- c(10, 16, 13)
cor_matrix_2 <- matrix(c(1.0, 0.6, 0.3,
0.6, 1.0, 0.3,
0.3, 0.3, 1.0), nrow = 3)
sample_sizes <- c(10, 15, 20, 25, 30)
mv_power_table <- data.frame(
n = sample_sizes,
Scenario_1 = sapply(sample_sizes, function(nn)
power_multivariate(mu_scenario_1, cor_matrix_1, variance_pop, C_omnibus, nn, a = 3)),
Scenario_2 = sapply(sample_sizes, function(nn)
power_multivariate(mu_scenario_2, cor_matrix_2, variance_pop, C_omnibus, nn, a = 3))
)
round(mv_power_table, 3)HideShow
n Scenario_1 Scenario_2
1 10 0.212 0.343
2 15 0.340 0.550
3 20 0.463 0.712
4 25 0.574 0.826
5 30 0.669 0.899Equation 13.40, implemented in five lines of base R, reproduces the book’s multivariate power column exactly at every sample size in both scenarios. The two columns also make the book’s qualitative point plain: with the same means spanning the same range and the same variance, moving the high correlation onto the most disparate pair of means raises the multivariate test’s power at from .669 to .899.
Power of a planned contrast
The book then introduces a third option: skip the omnibus test and test a planned contrast. The same equation does this — the only change is that becomes a single row.
Return to Scenario 1, where the means describe a perfect linear trend and where the multivariate omnibus test was the weaker of the two omnibus options.
HideShow
n Linear_trend
1 10 0.310
2 15 0.463
3 20 0.594
4 25 0.700
5 30 0.782At , testing the linear trend alone gives .782, against .669 for the multivariate omnibus test on the same data. Concentrating the test into a single degree of freedom pays off when the anticipated pattern is right. The book is careful about the size of that payoff, though: against the Greenhouse–Geisser -adjusted omnibus test, which it reports at .763 for and which the next section computes from scratch, the linear trend’s advantage is modest. The contrast wins at every sample size in this scenario, but it wins by a little over the univariate route and by a lot over the multivariate one.
The Greenhouse–Geisser column, computed from scratch
Every table so far has quoted the book’s Greenhouse–Geisser column rather than computing it, and that gap is the one place in this section where the book is genuinely hard to follow along with in R. The multivariate column falls straight out of Equation 13.40, which the book writes down and which took five lines above. For the -adjusted column the book prints SAS PROC GLMPOWER code instead of a formula, so a reader working in R has nothing to translate. This section supplies what is missing.
The obstacle is not the arithmetic. It is deciding which test to compute the power of. At least three distinct quantities travel under the name “the power of the Greenhouse–Geisser test”:
- The power of an test whose critical value is set from the population . Nobody can run that test, because nobody knows .
- The power of the test a researcher actually runs, in which is computed from the very same sample that produces , so the critical value is itself a random variable.
- The power of the unadjusted test, which is right only under sphericity.
GLMPOWER’s mtest = gg targets the second — by a
closed-form approximation to it, as the next two subsections will make
explicit — and the second is what the book prints. Reaching it in R
takes two pieces of machinery that the book, reasonably enough, leaves
inside the SAS procedure. Both are worth meeting on their own terms.
Piece one: two different epsilons
Box’s is a feature of alone. Write for an orthonormal basis of the -dimensional space of within-subjects contrasts, let , and let be the eigenvalues of . Then
so exactly when all the eigenvalues are equal, which is what sphericity means.
The orthonormality matters here in a way it did not for Equation
13.40, and this is an easy place to go wrong in R. The multivariate
statistic is invariant to the choice of as long as its rows span the
contrast space, which is why C_omnibus above could be
written with convenient
rows. The univariate route’s is not invariant: it
is built from the eigenvalues of , so a whose rows are not orthonormal
gives the wrong number. contr.helmert() supplies an
orthogonal basis; dividing each row by its own length makes it
orthonormal.
substitutes the sample covariance matrix for in that same formula. Because the ratio is a nonlinear function of the , the substitution is biased, and biased downward — tends to report more departure from sphericity than there really is, which makes the corrected test conservative. Muller and Barton (1989) give a closed-form approximation to built from the same eigenvalues, and it is that approximation, not , that the SAS calculation uses.
It is worth being exact about what that closed form is, because it is easy to mistake for the expectation it stands in for. is a ratio, and the formula replaces the expectation of the ratio with a ratio of expectations: over , where is the Wishart matrix on degrees of freedom built from the sample contrast covariance (the cancels, since the ratio is scale-free). Those two are not the same number, and at these sample sizes they are not close. itself has no comparably simple closed form, but it can be simulated directly, so all three quantities fit in one table:
HideShow
# Two closed-form epsilons, both functions of the eigenvalues of E* = U Sigma U',
# where U is an ORTHONORMAL basis for the (a - 1)-dimensional space of
# within-subjects contrasts.
epsilon_unirep <- function(mu, R, variance, n) {
a <- length(mu)
rM <- a - 1 # dimension of the contrast space
nu <- n - 1 # error degrees of freedom
# An orthonormal U: Helmert contrasts, each row rescaled to unit length.
U <- t(apply(t(contr.helmert(a)), 1, function(r) r / sqrt(sum(r^2))))
Estar <- U %*% (variance * R) %*% t(U)
phi <- eigen(Estar, symmetric = TRUE)$values
# Box's epsilon: a fixed feature of Sigma, with no n in it.
eps_pop <- sum(phi)^2 / (rM * sum(phi^2))
# Muller and Barton's (1989) closed-form APPROXIMATION to E(epsilon-hat), and
# the quantity SAS uses: num is E[tr(W)^2] and den is E[tr(W^2)] for W
# Wishart on nu degrees of freedom, so this is a ratio of expectations
# standing in for the expectation of the ratio that epsilon-hat is.
num <- 2 * nu * sum(phi^2) + nu^2 * sum(phi)^2
den <- nu * (nu + 2) * sum(phi^2) +
2 * nu * sum(outer(phi, phi)[lower.tri(diag(rM))])
c(epsilon_population = eps_pop, epsilon_MB = num / (rM * den))
}
# E(epsilon-hat) itself, by direct simulation. Epsilon-hat is a function of the
# sample covariance matrix alone, so the means play no part here: each replicate
# draws n subjects' contrast scores, forms their covariance, and applies Box's
# formula to it. 113 is the seed used throughout these notes.
E_eps_hat_sim <- function(mu, R, variance, n, reps = 50000, seed = 113) {
set.seed(seed)
a <- length(mu); b <- a - 1
U <- t(apply(t(contr.helmert(a)), 1, function(r) r / sqrt(sum(r^2))))
Estar <- U %*% (variance * R) %*% t(U)
L <- t(chol(Estar)) # to give the contrasts their covariance
id <- rep(seq_len(reps), each = n)
D <- matrix(rnorm(n * reps * b), n * reps, b) %*% t(L)
M <- rowsum(D, id) / n # contrast means, one row per replicate
tr <- numeric(reps); tr_sq <- numeric(reps)
for (j in seq_len(b)) for (k in seq_len(b)) {
s <- (rowsum(D[, j] * D[, k], id)[, 1] - n * M[, j] * M[, k]) / (n - 1)
if (j == k) tr <- tr + s
tr_sq <- tr_sq + s^2
}
mean(tr^2 / (b * tr_sq)) # average of Box's epsilon-hat
}
eps_table <- data.frame(
n = sample_sizes,
t(sapply(sample_sizes, function(nn)
epsilon_unirep(mu_scenario_1, cor_matrix_1, variance_pop, nn))),
S1_sim = sapply(sample_sizes, function(nn)
E_eps_hat_sim(mu_scenario_1, cor_matrix_1, variance_pop, nn)),
t(sapply(sample_sizes, function(nn)
epsilon_unirep(mu_scenario_2, cor_matrix_2, variance_pop, nn))),
S2_sim = sapply(sample_sizes, function(nn)
E_eps_hat_sim(mu_scenario_2, cor_matrix_2, variance_pop, nn))
)
names(eps_table) <- c("n", "S1_epsilon", "S1_MB_approx", "S1_E_eps_hat",
"S2_epsilon", "S2_MB_approx", "S2_E_eps_hat")
round(eps_table, 3)HideShow
n S1_epsilon S1_MB_approx S1_E_eps_hat S2_epsilon S2_MB_approx S2_E_eps_hat
1 10 0.862 0.747 0.787 0.9 0.771 0.806
2 15 0.862 0.781 0.812 0.9 0.810 0.836
3 20 0.862 0.800 0.827 0.9 0.830 0.852
4 25 0.862 0.812 0.833 0.9 0.843 0.861
5 30 0.862 0.820 0.839 0.9 0.852 0.868Read that table across. The population does not move with — it is 0.862 in Scenario 1 and 0.900 in Scenario 2, whatever the sample size, because it describes the covariance matrix and nothing else. The other two columns do move with , and they say the same thing at different magnitudes.
The bias in is real. In Scenario 1 at ten subjects its expectation is 0.787 against a population of 0.862, so the statistic a researcher computes is expected to understate by about .075; in Scenario 2 the understatement is about .094. Both scenarios violate sphericity only mildly in population terms, and the bias shrinks steadily as the sample grows, so it is largest exactly where power analysis matters most. (Those simulated figures are 50,000-replication averages, so each carries a Monte Carlo standard error of about .0005 — enough to pin the third decimal but not the fourth.)
The Muller–Barton column tracks that bias and overstates it, which is the price of a ratio of expectations: 0.747 where the expectation is 0.787, putting the apparent understatement at .115 rather than .075 in Scenario 1 and at .129 rather than .094 in Scenario 2. Keeping the two apart matters for what follows, because it is the Muller–Barton value, not , that sets the critical value in the book’s calculation — and the fact that it sits low leaves a visible trace in the result.
Piece two: the distribution of the statistic
Under non-sphericity the numerator and denominator sums of squares are no longer scaled chi-squares. Each is a weighted sum of chi-squares, with the as weights and, in the numerator, noncentralities carrying the contrast means. The UNIREP approximation of Muller and Barton (1989), refined by Muller, Edwards, Simpson, and Taylor (2007), matches the first two moments of each weighted sum with a single scaled chi-square — a Satterthwaite argument, the same device that gives the Welch test its fractional degrees of freedom — and the ratio of the two becomes an approximating noncentral with degrees of freedom and and noncentrality . Power is then the probability that this approximating exceeds a critical value built on -adjusted degrees of freedom — in the book’s calculation, adjusted by the Muller–Barton value from the table above. The whole calculation is short enough to read:
HideShow
# Power of the Greenhouse-Geisser-corrected univariate test, by the UNIREP
# approximation of Muller and Barton (1989) and Muller, Edwards, Simpson, and
# Taylor (2007) -- the calculation PROC GLMPOWER performs for mtest = gg.
power_unirep_gg <- function(mu, R, variance, n, alpha = 0.05,
epsilon = c("muller_barton", "population",
"simulated")) {
epsilon <- match.arg(epsilon)
a <- length(mu); rM <- a - 1; nu <- n - 1
U <- t(apply(t(contr.helmert(a)), 1, function(r) r / sqrt(sum(r^2))))
Estar <- U %*% (variance * R) %*% t(U)
ev <- eigen(Estar, symmetric = TRUE)
phi <- ev$values # weights of the chi-squares
gamma <- ev$vectors
theta <- as.numeric(U %*% mu) # contrast means
omega <- n * diag(t(gamma) %*% outer(theta, theta) %*% gamma) / phi
# Two-moment (Satterthwaite) match to the two weighted sums of chi-squares.
s1 <- sum(phi); s2 <- sum(phi * omega)
s3 <- sum(phi^2); s4 <- sum(phi^2 * omega)
ratio_hyp <- (s3 + 2 * s4) / (s1 + 2 * s2)
ratio_err <- s3 / s1
df1_star <- s1 / ratio_hyp
df2_star <- nu * s1 / ratio_err
lambda <- s2 / ratio_hyp
# Which epsilon sets the critical value: Muller and Barton's closed form, as
# the book's calculation does it; the population value an idealized test
# would know; or E(epsilon-hat) itself, simulated.
eps <- epsilon_unirep(mu, R, variance, n)
e <- switch(epsilon,
muller_barton = eps[["epsilon_MB"]],
population = eps[["epsilon_population"]],
simulated = E_eps_hat_sim(mu, R, variance, n))
crit <- qf(1 - alpha, rM * e, rM * nu * e)
pf(crit, df1_star, df2_star, ncp = lambda, lower.tail = FALSE)
}
gg_power_table <- data.frame(
n = sample_sizes,
Scenario_1 = sapply(sample_sizes, function(nn)
power_unirep_gg(mu_scenario_1, cor_matrix_1, variance_pop, nn)),
Scenario_2 = sapply(sample_sizes, function(nn)
power_unirep_gg(mu_scenario_2, cor_matrix_2, variance_pop, nn))
)
round(gg_power_table, 3)HideShow
n Scenario_1 Scenario_2
1 10 0.282 0.233
2 15 0.437 0.398
3 20 0.569 0.555
4 25 0.677 0.688
5 30 0.763 0.791All ten values reproduce the book’s Greenhouse–Geisser column at three decimals, which is as many as the book prints. Carried to four decimals the agreement is .2821, .4367, .5690, .6773, .7629 against the book’s five figures in Scenario 1, so the largest discrepancy anywhere in the table is 5 in the fourth decimal. Nothing was tuned to make that happen: the function has no free parameters, and every ingredient comes from , , , and .
A simulation check
A closed-form approximation deserves a check that does not share its assumptions, and here one is available. The test a researcher actually runs can simply be simulated: draw a sample, compute from that sample, compare to the critical value that implies, and count rejections. Nothing is approximated anywhere, and the only error is Monte Carlo error, which is known and can be made as small as patience allows.
HideShow
# The test a researcher actually runs, simulated. Each replicate draws its own
# sample, computes its own epsilon-hat, and is judged against its own critical
# value. 113 is the seed used throughout these notes.
power_gg_sim <- function(mu, R, variance, n, alpha = 0.05, reps = 20000,
chunk = 5000, seed = 113) {
set.seed(seed)
a <- length(mu); b <- a - 1
U <- t(apply(t(contr.helmert(a)), 1, function(r) r / sqrt(sum(r^2))))
Estar <- U %*% (variance * R) %*% t(U)
theta <- as.numeric(U %*% mu)
L <- t(chol(Estar)) # to give the contrasts their covariance
rejections <- 0; done <- 0
while (done < reps) { # in chunks, to keep memory modest
this <- min(chunk, reps - done)
id <- rep(seq_len(this), each = n)
D <- matrix(rnorm(n * this * b), n * this, b) %*% t(L)
D <- sweep(D, 2, theta, "+") # this * n subjects, b contrast scores
Mean <- rowsum(D, id) / n # contrast means, one row per replicate
S <- array(0, c(this, b, b)) # contrast covariance, per replicate
for (j in seq_len(b)) for (k in j:b) {
s <- (rowsum(D[, j] * D[, k], id)[, 1] - n * Mean[, j] * Mean[, k]) / (n - 1)
S[, j, k] <- s; S[, k, j] <- s
}
tr <- numeric(this); tr_sq <- numeric(this)
for (j in seq_len(b)) tr <- tr + S[, j, j]
for (j in seq_len(b)) for (k in seq_len(b)) tr_sq <- tr_sq + S[, j, k]^2
F_stat <- n * rowSums(Mean^2) / tr
eps_hat <- tr^2 / (b * tr_sq) # Greenhouse-Geisser, from this sample
rejections <- rejections +
sum(F_stat > qf(1 - alpha, b * eps_hat, b * (n - 1) * eps_hat))
done <- done + this
}
rejections / reps
}
gg_check <- data.frame(
n = sample_sizes,
Book_S1 = c(.282, .437, .569, .677, .763),
Closed_form_S1 = gg_power_table$Scenario_1,
Simulated_S1 = sapply(sample_sizes, function(nn)
power_gg_sim(mu_scenario_1, cor_matrix_1, variance_pop, nn)),
Book_S2 = c(.233, .398, .555, .688, .791),
Closed_form_S2 = gg_power_table$Scenario_2,
Simulated_S2 = sapply(sample_sizes, function(nn)
power_gg_sim(mu_scenario_2, cor_matrix_2, variance_pop, nn))
)
round(gg_check, 3)HideShow
n Book_S1 Closed_form_S1 Simulated_S1 Book_S2 Closed_form_S2 Simulated_S2
1 10 0.282 0.282 0.284 0.233 0.233 0.241
2 15 0.437 0.437 0.436 0.398 0.398 0.408
3 20 0.569 0.569 0.567 0.555 0.555 0.556
4 25 0.677 0.677 0.673 0.688 0.688 0.684
5 30 0.763 0.763 0.760 0.791 0.791 0.788HideShow
[1] 0.0035HideShow
[1] 0.0032 0.0035 0.0035 0.0033 0.0030Twenty thousand replications is ample for a demonstration and costs a fraction of a second, but it does set a floor on what can be concluded: the Monte Carlo standard error is , at most .0035 and between .0030 and .0035 at the powers in this table, so differences smaller than about .007 are not resolvable here. Within that resolution, the simulation agrees with the book and with the closed form everywhere in Scenario 1 — the largest gap is .004, about one standard error.
Scenario 2 shows something more interesting at the two smallest
sample sizes, where the simulation runs .008 and .010 above the book.
That is about three standard errors, so it is worth pushing further
rather than waving away. Raising reps to 200,000 drops the
Monte Carlo standard error to .001:
power_gg_sim(mu_scenario_2, cor_matrix_2, variance_pop, 10, reps = 200000)
returns .242, and the same call at returns .405, against the book’s .233 and .398. The gap is
real, and a good part of it can be named rather than shrugged at.
The suspect is the epsilon that sets the critical value. Muller and
Barton’s closed form runs below — 0.771 against
0.806 at in Scenario 2 — and
too small an epsilon means too few degrees of freedom, too large a
critical value, and too little power. Substituting the simulated
expectation is one argument to power_unirep_gg(); nothing
else in the calculation changes:
HideShow
eps_source_table <- data.frame(
n = sample_sizes,
MB_S1 = gg_power_table$Scenario_1,
Sim_eps_S1 = sapply(sample_sizes, function(nn)
power_unirep_gg(mu_scenario_1, cor_matrix_1, variance_pop, nn,
epsilon = "simulated")),
MB_S2 = gg_power_table$Scenario_2,
Sim_eps_S2 = sapply(sample_sizes, function(nn)
power_unirep_gg(mu_scenario_2, cor_matrix_2, variance_pop, nn,
epsilon = "simulated"))
)
round(eps_source_table, 3)HideShow
n MB_S1 Sim_eps_S1 MB_S2 Sim_eps_S2
1 10 0.282 0.292 0.233 0.243
2 15 0.437 0.444 0.398 0.406
3 20 0.569 0.575 0.555 0.561
4 25 0.677 0.682 0.688 0.693
5 30 0.763 0.766 0.791 0.794In Scenario 2 that one change lands on the 200,000-replication
simulation almost exactly — .243 against .242 at and .406 against .405 at , both inside the simulation’s own
.001 standard error — so there the epsilon approximation accounts for
essentially the whole gap. In Scenario 1 it overshoots by about as much
as the Muller–Barton value undershoots:
power_gg_sim(mu_scenario_1, cor_matrix_1, variance_pop, 10, reps = 200000)
returns .287, between the closed form’s .282 and the substituted .292.
So the epsilon is part of the story and not all of it, which is what one
should expect: any fixed epsilon stands in for a that is random and
computed from the same sample as ,
so the two are not independent, and the Satterthwaite match to the
distribution of is an
approximation in its own right.
What matters for planning is the size of all of it together, and that is small and shrinking. Against 200,000-replication simulations the closed form is conservative by .005 in Scenario 1 and .009 in Scenario 2 at , and by .001 or less in both by . That is excellent accuracy for a method designed when 200,000 replications were not something one did while waiting, and it is well inside the precision at which anyone plans a study. The reassuring conclusion is the one that matters: the book’s column answers the question it claims to answer, and an independent simulation of the real test confirms it.
What if were known?
The epsilon argument makes the first of the three
quantities listed earlier available for comparison. Substituting the
population into the
critical value, and changing nothing else, gives the power of an
idealized test that knows how far from sphericity the population really
is:
HideShow
known_eps_table <- data.frame(
n = sample_sizes,
Book_S1 = c(.282, .437, .569, .677, .763),
Known_epsilon_S1 = sapply(sample_sizes, function(nn)
power_unirep_gg(mu_scenario_1, cor_matrix_1, variance_pop, nn,
epsilon = "population")),
Book_S2 = c(.233, .398, .555, .688, .791),
Known_epsilon_S2 = sapply(sample_sizes, function(nn)
power_unirep_gg(mu_scenario_2, cor_matrix_2, variance_pop, nn,
epsilon = "population"))
)
round(known_eps_table, 3)HideShow
n Book_S1 Known_epsilon_S1 Book_S2 Known_epsilon_S2
1 10 0.282 0.309 0.233 0.266
2 15 0.437 0.456 0.398 0.424
3 20 0.569 0.583 0.555 0.575
4 25 0.677 0.687 0.688 0.702
5 30 0.763 0.770 0.791 0.801The idealized test is more powerful than the real one at every sample size, by .027 down to .007 in Scenario 1 and by .033 down to .010 in Scenario 2. The margin shrinks as grows, exactly as the epsilon table predicted: the Muller–Barton value closes on , so the real test’s extra conservatism fades. This is not an academic distinction. Planning a study at on the idealized figure would overstate the power of the analysis actually intended by about .03, and the overstatement is in the optimistic direction.
Where other software lands
A reader who reaches for a package here may land on a different
number, and the difference is in the question rather than the
arithmetic. Superpower
offers both quantities:
ANOVA_exact(design, correction = "GG") corrects with the
population , the
idealized test of the previous subsection, while
ANOVA_power(design, correction = "GG", nsims = ...)
simulates data sets and fits each with afex, which estimates
from every
sample, as power_gg_sim() above does. The book’s column is
the second of those, and the known-epsilon table measures the distance
between them: .007 to .033 of power here, widest at the smallest
samples. Superpower’s multivariate power comes from Pillai’s trace,
converted back into a noncentrality by a step that in this design runs a
little low — .011 to .034 of power — while
power_multivariate() goes straight from Equation 13.40 to
the exact noncentral . The rule
worth carrying away: plan with the quantity you will actually
analyze.
The three approaches side by side
With the Greenhouse–Geisser column now computed rather than quoted, the summary table the book gives for Scenario 1 can be assembled entirely in R — all three columns, from three calculations on the same and :
HideShow
n GG_adjusted Multivariate Linear_trend
1 10 0.282 0.212 0.310
2 15 0.437 0.340 0.463
3 20 0.569 0.463 0.594
4 25 0.677 0.574 0.700
5 30 0.763 0.669 0.782That is the book’s table, reproduced in full. Two things are worth
noticing about how it was built. All three columns rest on the same two
population inputs, so the comparison is genuinely about the analysis and
not about differing assumptions. And the two multivariate columns differ
only in the number of rows in : the same
power_multivariate() call, handed a two-row , gives the omnibus test, and
handed the single row ,
gives the linear trend. The book makes this point in words around
Equations 13.40 through 13.42; in R it is one argument.
Everything the book draws from these tables is now readable off a reproduction rather than taken on trust. In Scenario 1 the Greenhouse–Geisser approach beats the multivariate approach at every sample size, by as much as .106 at . In Scenario 2 the ordering reverses and the multivariate margin is the larger of the two, reaching .157 at . And in Scenario 1 a correctly anticipated planned contrast beats both omnibus tests at every sample size — though, as the book is careful to say, by a modest margin over the univariate route (.019 at ) and a wide one over the multivariate (.113).
The broader lesson is the one the book closes on: the most powerful analysis depends jointly on the covariance structure and on the hypothesis actually being asked. There is no single best way to analyze a within-subjects design when sphericity is violated.
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 13: One-Way Within-Subjects Designs: Multivariate Approach (R code and instructions). Companion materials for Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). https://DesigningExperiments.com
These examples use DMAR 1.2.0. The printed book predates DMAR.
References
Arel-Bundock V (2026). modelsummary: Summary Tables and Plots for Statistical Models and Data: Beautiful, Customizable, and Publication-Ready. doi:10.32614/CRAN.package.modelsummary https://doi.org/10.32614/CRAN.package.modelsummary. R package version 2.6.0, https://CRAN.R-project.org/package=modelsummary.
Fox J, Weisberg S, Price B (2026). car: Companion to Applied Regression. doi:10.32614/CRAN.package.car https://doi.org/10.32614/CRAN.package.car. R package version 3.1-5, https://CRAN.R-project.org/package=car.
Iannone R, Cheng J, Schloerke B, Haughton S, Hughes E, Lauer A, François R, Seo J, Brevoort K, Roy O (2026). gt: Easily Create Presentation-Ready Display Tables. doi:10.32614/CRAN.package.gt https://doi.org/10.32614/CRAN.package.gt. R package version 1.3.0, https://CRAN.R-project.org/package=gt.
Kelley K (2026). DMAR: Design, Measurement, and Analysis in R (DMAR). R package version 1.2.0, https://kenkelley.org.
Maxwell S, Delaney H, Kelley K (2026). AMCP: Data Sets to Accompany Designing Experiments and Analyzing Data: A Model Comparison Perspective (Maxwell, Delaney, and Kelley, 2027, 4th Edition). doi:10.32614/CRAN.package.AMCP https://doi.org/10.32614/CRAN.package.AMCP. R package version 2.0.0, https://CRAN.R-project.org/package=AMCP.
Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.
R Core Team (2026). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria. doi:10.32614/R.manuals https://doi.org/10.32614/R.manuals. https://www.R-project.org/.
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.