Examples follow the book’s section numbers.

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

Chapter 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 (DD) 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.

data(chapter_13_table_1)
chapter_13_table_1
  Time1 Time2
1     2     3
2     4     7
3     6     8
4     8     9
5    10    13
# Create difference score
chapter_13_table_1$Difference <- chapter_13_table_1$Time2 - chapter_13_table_1$Time1
chapter_13_table_1
  Time1 Time2 Difference
1     2     3          1
2     4     7          3
3     6     8          2
4     8     9          1
5    10    13          3
#> Time 1 means 6, Time 2 means 8, and D means 2 — matches Table 13.1, book p. 710

To 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.

# Fit an intercept-only model on the difference scores
RM_2DV <- lm(Difference ~ 1, data=chapter_13_table_1)

# Note: unlike manova(), summary() here returns a standard univariate model. This distinction
# becomes important when we have multiple D variables.
summary(RM_2DV)

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 freedom

Notice that the summary returns a tt value of 4.472. Because t2=Ft^2 = F for an analysis with 1 numerator degree of freedom, 4.4722=204.472^2 = 20, which is the FF statistic the book reports for these data (Equation 13.6, p. 711).

We can confirm this directly with the book’s closed form F=nD‾2/sD2F = n\bar{D}^2 / s^2_D (Equation 13.6), plugging in the actual numbers from Table 13.1.

# Equation 13.6: F = n * Dbar^2 / s_D^2
n      <- nrow(chapter_13_table_1)
D_bar  <- mean(chapter_13_table_1$Difference)
s2_D   <- var(chapter_13_table_1$Difference)
F_136  <- n * D_bar^2 / s2_D
cat("n =", n, " Dbar =", D_bar, " s^2_D =", s2_D, " F =", F_136, "\n")
n = 5  Dbar = 2  s^2_D = 1  F = 20 
#> Dbar = 2, s^2_D = 1, n = 5, so F = 20 — matches book p. 711, Eq. 13.6

# The observed F is referred to a critical F with 1 and n - 1 degrees of freedom.
qf(0.05, df1 = 1, df2 = n - 1, lower.tail = FALSE)
[1] 7.708647
#> 7.709 — the book reads 7.71 from Appendix Table A.2 (p. 711), and 20 > 7.71

Finally, 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.

# Option 1: A one-sample t-test on the difference scores testing against mu = 0
t.test(
  x           = chapter_13_table_1$Difference,
  mu          = 0,
  alternative = "two.sided",
  paired      = FALSE,
  conf.level  = 0.95
)

    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 
# Option 2: A paired-samples t-test on the original Time 1 and Time 2 variables
t.test(
  x           = chapter_13_table_1$Time2,
  y           = chapter_13_table_1$Time1,
  mu          = 0,
  alternative = "two.sided",
  paired      = TRUE,
  conf.level  = 0.95
)

    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 
#> Both give t = 4.472 on 4 df, so t^2 = 20 — matches book p. 711

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 DD 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: D1D_1 (Time 2 minus Time 1) and D2D_2 (Time 3 minus Time 2).

data(chapter_13_table_2)
chapter_13_table_2
  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    10
#> Time means 6, 8, 9 — matches Table 13.2, book p. 712

# Define difference scores to include in the multivariate analysis.
chapter_13_table_2$D1 <- chapter_13_table_2$Time2-chapter_13_table_2$Time1
chapter_13_table_2$D2 <- chapter_13_table_2$Time3-chapter_13_table_2$Time2
chapter_13_table_2
  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 -1
colMeans(chapter_13_table_2[, c("D1", "D2")])
D1 D2 
 2  1 
#> D1 means 2 and D2 means 1 — matches Table 13.3, book p. 712

13.4.4 — Matrix Formulation and Determinants

In a univariate test, we look at the sum of squared errors (SSerrorSS_{error}). 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).

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):")
[1] "Full Model Matrix E(F):"
print(E_F)
     [,1] [,2]
[1,]    6   -3
[2,]   -3   32
#> rows (6, -3) and (-3, 32) — matches book p. 719

print("Restricted Model Matrix E(R):")
[1] "Restricted Model Matrix E(R):"
print(E_R)
     [,1] [,2]
[1,]   38   13
[2,]   13   40
#> rows (38, 13) and (13, 40) — matches book p. 719

To 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 D1D_1, the variance of D2D_2, 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.

# Calculate Determinants
det_EF <- det(E_F)
det_ER <- det(E_R)

cat("Determinant of E(F):", det_EF,
    "\nDeterminant of E(R):", det_ER, "\n")
Determinant of E(F): 183 
Determinant of E(R): 1351 
#> |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")
Observed F-statistic: 19.14754 
p-value: 0.002485348 
#> F = 19.148, p = .0025 — matches book p. 719, Eq. 13.23

The determinant of the full model is 183183 and that of the restricted model is 1,3511{,}351. The resulting FF of 19.14819.148 (p=.0025p = .0025) 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.

# Bind the two difference scores into a single outcome matrix
MANOVA_Diff_3DV <- manova(cbind(D1, D2) ~ 1, data=chapter_13_table_2)

# The default test statistic is Pillai's Trace, which R converts to an approximate F
anova(MANOVA_Diff_3DV)
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 ' ' 1
#> approx F = 19.148 on (2, 6) df, p = .0025 — matches book p. 719

Notice that the automated MANOVA function returns an FF of 19.14819.148, 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.

# Alternative MANOVA tests.
anova(MANOVA_Diff_3DV, test="Wilks")
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 ' ' 1
anova(MANOVA_Diff_3DV, test="Hotelling-Lawley")
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 ' ' 1
anova(MANOVA_Diff_3DV, test="Roy")
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 ' ' 1

An 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:

# Rebuild the two difference vectors as a matrix and take the eigenvalues of their
# covariance: base R gives the point estimates and nothing more.
D_mat <- with(chapter_13_table_2, cbind(D1 = Time2 - Time1, D2 = Time3 - Time2))
eigen(cov(D_mat))$values
[1] 4.6202377 0.8083337

An 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.

ci_eigenvalue(cov_matrix = cov(D_mat), N = nrow(D_mat), which_eigenvalue = 1)
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, D1D_1 and D2D_2. The D1D_1 scores are identical across the two sets, and so are the D2D_2 scores; only the pairing differs, and hence only the D1D_1–D2D_2 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.

data(chapter_13_table_5)
chapter_13_table_5
   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.2
# Every one-dimensional summary is identical across the two data sets.
colSums(chapter_13_table_5)
     SetA_D1      SetA_D2      SetB_D1      SetB_D2 
0.000000e+00 0.000000e+00 0.000000e+00 1.110223e-16 
colSums(chapter_13_table_5^2)
SetA_D1 SetA_D2 SetB_D1 SetB_D2 
  56.00   56.38   56.00   56.38 
#> 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)))
SetA SetB 
56.0 -0.5 
#> 56.00 for set (a) and -0.50 for set (b) — matches Table 13.5, book p. 717

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.

set_a <- as.matrix(chapter_13_table_5[, c("SetA_D1", "SetA_D2")])
set_b <- as.matrix(chapter_13_table_5[, c("SetB_D1", "SetB_D2")])

det_a <- det(crossprod(set_a))
det_b <- det(crossprod(set_b))
c("Data set (a)" = det_a, "Data set (b)" = det_b)
Data set (a) Data set (b) 
       21.28      3157.03 
#> 21.28 for set (a) and 3157.03 for set (b) — matches book p. 719

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.

# 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))
)
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 \(D_1\) and \(D_2\) for the two hypothetical data sets in Table 13.5.

Figure 13.2. Scores on D1D_1 and D2D_2 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 D1D_1 and D2D_2 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 aa 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 aa levels, we must form a−1a-1 difference (DD) variables.

The null hypothesis that all aa levels have equal population means is mathematically equivalent to the hypothesis that all a−1a-1 difference variables have population means of zero.

13.5.1 — Forming DD Variables

In the general case, we must construct a sum-of-squares and cross-products (SSCP) matrix for both the full model (E(F)E(F)) and the restricted model (E(R)E(R)). Because there are a−1a-1 difference variables, these matrices have a−1a-1 rows and a−1a-1 columns, with (a−1)(a−2)/2(a-1)(a-2)/2 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 FF statistic (Equation 13.24):

F=(|E(R)|−|E(F)|)/(a−1)|E(F)|/(n−a+1)F = \frac{(|E(R)| - |E(F)|) / (a - 1)}{|E(F)| / (n - a + 1)}

This observed FF is then compared to a critical FF distribution with a−1a-1 numerator degrees of freedom and n−a+1n-a+1 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 a=4a = 4, we need to define three DD variables.

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)
  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 -5
colMeans(chapter_13_table_6[, c("D1", "D2", "D3")])
D1 D2 D3 
 4  3  2 
#> D1 means 4, D2 means 3, D3 means 2 — matches Table 13.7, book p. 722

Manual Matrix Construction

To see exactly how the SSCP matrices are formed, we can calculate the 3×33 \times 3 matrices for the Full and Restricted models. Instead of writing out all 9 elements manually as we did in the 2×22 \times 2 example, we can use R’s crossprod() function, which automates the sum of squares and cross-products for a set of columns.

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)
     e1_F e2_F e3_F
e1_F  878 -329 -440
e2_F -329 1004  399
e3_F -440  399  658
#> rows (878, -329, -440), (-329, 1004, 399), (-440, 399, 658) — matches book p. 721,
#> whose entries are the column sums of Table 13.8, p. 723

# Restricted Model Matrix E(R)
print(E_R)
     [,1] [,2] [,3]
[1,] 1070 -185 -344
[2,] -185 1112  471
[3,] -344  471  706
#> rows (1070, -185, -344), (-185, 1112, 471), (-344, 471, 706) — matches book p. 721,
#> whose entries are the column sums of Table 13.9, p. 723

These matrices match those in the text.

Now, we extract their determinants and calculate the F-statistic.

# Calculate determinants
det_EF <- det(E_F)
det_ER <- det(E_R)

cat("Determinant of E(F):", format(det_EF, scientific = FALSE),
    "\nDeterminant of E(R):", format(det_ER, scientific = FALSE), "\n")
Determinant of E(F): 290177920 
Determinant of E(R): 506853568 
#> |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")
Observed F-statistic: 2.240098 
P-value: 0.1528393 
#> F = 2.2401, p = .1528 — matches book p. 722

The multivariate test yields an FF of 2.2401 with a pp 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 ε̂\hat{\varepsilon}- and ε̃\tilde{\varepsilon}-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().

# Bind the three D variables and predict them with an intercept
MANOVA_4DV <- manova(cbind(D1, D2, D3) ~ 1, data=chapter_13_table_6)

# The default test in R corresponds to Pillai's Trace
anova(MANOVA_4DV)
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                                      
#> approx F = 2.2401 on (3, 9) df, p = .1528 — matches book p. 722

Notice that the automated test gives the same F=2.2401F = 2.2401 and p=.1528p = .1528. 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 FF.

anova(MANOVA_4DV, test="Pillai")
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                                      
anova(MANOVA_4DV, test="Wilks")
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                                      
anova(MANOVA_4DV, test="Hotelling-Lawley")
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                                               
anova(MANOVA_4DV, test="Roy")
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 FF for this intercept-only design. A compact gt table collects them side by side, with the common FF, degrees of freedom, and pp value:

# 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
#> All four tests give approx F = 2.240 on (3, 9) df, p = .1528 — matches book p. 722

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.

# Type III Sums of Squares
Anova(MANOVA_4DV, type=c("III"))

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.1528
# Type II Sums of Squares
Anova(MANOVA_4DV, type=c("II"))

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.1528
#> Both give approx F = 2.2401 on (3, 9) df, p = .1528 — matches book p. 722

One 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 pp-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, ω2\omega^2).

The mixed-model ω2\omega^2 includes individual differences (subject variability) in the conceptualization of “total variance.” The multivariate ω2\omega^2, on the other hand, excludes this subject variability from the denominator.

The formula for multivariate omega squared relies on Wilks’s Lambda (Λ\Lambda), which is the ratio of the determinants we calculated earlier: Λ=|E(F)|/|E(R)|\Lambda = |E(F)| / |E(R)|.

ωmulti2=1−nΛdferror+Λ\omega^2_{multi} = 1 - \frac{n\Lambda}{df_{error} + \Lambda}

Let’s calculate this using the McCarthy IQ data from Table 13.6. Recall that we had n=12n = 12 subjects, a=4a = 4 time points, and dferror=n−a+1=9df_{error} = n - a + 1 = 9. We also found the determinants for the full and restricted models.

# Define the parameters from the McCarthy dataset
n <- 12
df_error <- 9

# det_EF and det_ER carry over from the McCarthy determinants computed in 13.5.3.

# Calculate Wilks's Lambda (Equation 13.26)
Lambda <- det_EF / det_ER
cat("Wilks's Lambda:", Lambda, "\n")
Wilks's Lambda: 0.5725084 
#> Lambda = 0.5725 — matches book p. 724

# Calculate Multivariate Omega Squared (Equation 13.25)
omega2_multi <- 1 - (n * Lambda) / (df_error + Lambda)
cat("Multivariate Omega Squared:", omega2_multi, "\n")
Multivariate Omega Squared: 0.2823093 
#> omega^2_multi = .28 — matches book p. 724; the mixed-model omega^2 reported there
#> for these same data is .04

The multivariate ω2\omega^2 is approximately .28, meaning age accounts for roughly 28% of the variance once individual differences are excluded from total variance. The mixed-model ω2\omega^2 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 DD Variables

When we analyzed the three-level data in Section 13.4, we chose to create difference scores representing adjacent time periods: D1=Time2−Time1D_1 = Time 2 - Time 1 and D2=Time3−Time2D_2 = Time 3 - Time 2.

Does the specific choice of DD variables matter? As the text notes, the answer is no. As long as you create a−1a - 1 linearly independent contrasts, the omnibus multivariate test will yield the exact same F-statistic and pp-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.

data(chapter_13_table_2)

names(chapter_13_table_2)
[1] "Time1" "Time2" "Time3"
# 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")]
  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      3
#> Linear scores 3, 5, 2, 0, 5, 6, 2, 1 (mean 3) and quadratic scores -1, 1, 2, 2, 1,
#> -4, 4, 3 (mean 1) — matches Table 13.10, book p. 725

Now, let’s run the exact same manova() function we used in Section 13.4, but using our new trend variables.

# Run the MANOVA using the linear and quadratic trend variables
manova_trend <- manova(cbind(D_lin, D_quad) ~ 1, data=chapter_13_table_2)

# View the results
anova(manova_trend)
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 ' ' 1
#> approx F = 19.148 on (2, 6) df — matches book p. 726, which reruns Eq. 13.23 on
#> the trend variables; the accompanying p = .0025 is printed on p. 725

The FF statistic is 19.14819.148, 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.

trend <- as.matrix(chapter_13_table_2[, c("D_lin", "D_quad")])

# Full model: deviations from each variable's mean. Restricted model: raw scores.
E_F_trend <- crossprod(sweep(trend, 2, colMeans(trend)))
E_R_trend <- crossprod(trend)

E_F_trend
       D_lin D_quad
D_lin     32    -26
D_quad   -26     44
#> rows (32, -26) and (-26, 44) — matches book p. 726
E_R_trend
       D_lin D_quad
D_lin    104     -2
D_quad    -2     52
#> rows (104, -2) and (-2, 52) — matches book p. 726

c("|E(F)|" = det(E_F_trend), "|E(R)|" = det(E_R_trend))
|E(F)| |E(R)| 
   732   5404 
#> 732 and 5404 — matches book p. 726

# Equation 13.23 applied to the new determinants
((det(E_R_trend) - det(E_F_trend)) / 2) / (det(E_F_trend) / (8 - 2))
[1] 19.14754
#> 19.148 — matches book p. 726

The determinants are entirely different from the 183183 and 1,3511{,}351 found in Section 13.4, and yet Equation 13.23 returns the identical FF. The choice of DD 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 tt test on each column reproduces the individual trend tests.

data(chapter_13_table_10)
poly <- chapter_13_table_10
poly
  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         3
# 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)
            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 ' ' 1
#> approx F = 19.148 on (2, 6) df — matches book p. 726; the p of .0025 is the one
#> the book prints for this F on p. 725

# Each trend separately (one-sample t test that the mean of the D variable is 0):
t.test(x = poly$Linear, mu = 0, alternative = "two.sided", conf.level = 0.95)

    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 
t.test(x = poly$Quadratic, mu = 0, alternative = "two.sided", conf.level = 0.95)

    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 tt for these contrasts; it prints an FF. The two are the same test, because a contrast has 1 numerator degree of freedom:

t_linear <- t.test(x = poly$Linear, mu = 0,
                   alternative = "two.sided", conf.level = 0.95)$statistic
c(t = unname(t_linear), t_squared = unname(t_linear^2))
        t t_squared 
 3.968627 15.750000 
#> t = 3.969, so t^2 = 15.75 — matches the F the book reports for the linear
#> contrast on p. 728

The linear-trend tt of 3.9693.969 is the same contrast tested in Section 13.8 directly from the raw scores, and t2=15.75t^2 = 15.75 is the FF the book reports there.

13.8 — Tests of Individual Contrasts

While the choice of DD variables does not matter for the omnibus test, different DD 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 DD 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 EF=32E_F = 32 and ER=104E_R = 104 — 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 FF formula (Equation 13.28) applies:

# Read E_F and E_R off the trend matrices rather than retyping them.
E_F <- E_F_trend[1, 1]
E_R <- E_R_trend[1, 1]
n_sub <- 8
c(E_F = E_F, E_R = E_R)
E_F E_R 
 32 104 
#> 32 and 104 — matches book p. 728

# F = (ER - EF) / (EF / (n - 1))
F_contrast <- (E_R - E_F) / (E_F / (n_sub - 1))
cat("F-statistic for the Linear Contrast:", F_contrast, "\n")
F-statistic for the Linear Contrast: 15.75 
#> F = 15.75 — matches book p. 728

To automate this in R, we apply the same intercept-only lm() or t.test() approach from Section 13.3.

# Intercept-only model on the single D_lin variable
lm_lin <- lm(D_lin ~ 1, data=chapter_13_table_2)
summary(lm_lin)

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 freedom

The lm() output gives a tt of 3.9693.969. Because t2=Ft^2 = F for an analysis with 1 numerator degree of freedom, 3.9692=15.753.969^2 = 15.75, the value computed from EFE_F and ERE_R 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 FF 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 n−1n-1 denominator degrees of freedom.

# Per-comparison critical F for the linear trend in the Table 13.2 data (n = 8)
qf(0.05, df1 = 1, df2 = 8 - 1, lower.tail = FALSE)
[1] 5.591448
#> 5.591 — the book reads 5.59 from Appendix Table A.2 (p. 729), and 15.75 > 5.59

However, if we are testing multiple contrasts, we must adjust our critical values to maintain our familywise error rate (αFW\alpha_{FW}).

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 .05/C.05/C, where CC is the number of planned comparisons.

To implement the Bonferroni approach in R, we simply calculate the exact pp value for our univariate contrast and compare it to α/C\alpha / C.

# Example from Section 13.8: Linear Trend F = 15.75, n = 8
F_obs <- 15.75
n <- 8
df_num <- 1
df_den <- n - 1

# Calculate the exact p-value
p_val <- pf(F_obs, df_num, df_den, lower.tail = FALSE)
cat("Raw p-value for the Linear Trend:", p_val, "\n")
Raw p-value for the Linear Trend: 0.005401769 
#> p = .0054 — matches book p. 729

# Suppose we planned 2 comparisons (Linear and Quadratic, C = 2)
C <- 2
alpha_FW <- 0.05
alpha_PC <- alpha_FW / C

cat("Bonferroni Critical p-value:", alpha_PC, "\n")
Bonferroni Critical p-value: 0.025 
#> .025 — the critical p value the book compares against on p. 729

Because the raw pp 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 (α/C\alpha / C) and comparing it to our raw pp-values, we can use the p.adjust() function. You provide it with a vector of your raw pp-values, and it multiplies them by CC (capping at 1.0). You can then compare these adjusted pp-values directly to your standard α=.05\alpha = .05.

# We can tell p.adjust() that there are 2 comparisons total by setting n = 2
C <- 2
p_val <- pf(F_obs, df_num, df_den, lower.tail = FALSE)
adjusted_p <- p.adjust(p_val, method = "bonferroni", n = C)

# Bonferroni Adjusted p-value:
adjusted_p
[1] 0.01080354

Because this adjusted value remains below our standard α=.05\alpha = .05 threshold, we can confidently conclude the contrast is statistically significant while safely maintaining our familywise error rate.

Note that this adjusted pp value differs from the raw one. The two are distinct arithmetic routes to the same conclusion: the book’s route divides the alpha threshold (.05/2=.025.05 / 2 = .025) and leaves the pp value alone, whereas p.adjust() does the reverse, multiplying the raw pp value (.0054×2=.0108.0054 \times 2 = .0108) so it can be compared against the familiar .05.05. 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 C=a(a−1)/2C = a(a-1)/2, 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.

# Number of pairwise contrasts among a = 3 levels, and the Bonferroni per-comparison
# alpha that goes with treating them as one family.
a_lev <- 3
C_pairs <- a_lev * (a_lev - 1) / 2
c(C = C_pairs, alpha_per_comparison = 0.05 / C_pairs)
                   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 DD variable is D=Y1−12(Y2+Y3)D = Y_1 - \tfrac{1}{2}(Y_2 + Y_3), and the observed FF comes from Equation 13.6 exactly as before.

data(chapter_13_table_2)

# D = Y1 - (1/2)(Y2 + Y3), the post hoc complex comparison
D_complex <- with(chapter_13_table_2, Time1 - 0.5 * (Time2 + Time3))
D_complex
[1] -2.0 -4.0 -2.0 -0.5 -4.0 -3.5 -2.5 -1.5
# Equation 13.6 again: F = n * Dbar^2 / s^2_D
n <- length(D_complex)
F_complex <- n * mean(D_complex)^2 / var(D_complex)
cat("Dbar =", mean(D_complex), " s^2_D =", var(D_complex),
    " F =", F_complex, "\n")
Dbar = -2.5  s^2_D = 1.571429  F = 31.81818 
#> F = 31.818 — matches book p. 730

Now for the critical value. Equation 13.29 scales the omnibus critical FF up by (n−1)(a−1)/(n−a+1)(n-1)(a-1)/(n-a+1).

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")
Omnibus Critical F: 5.143253 
cat("Roy-Bose Critical Value:", CV_RB, "\n")
Roy-Bose Critical Value: 12.00092 

Two small points about these numbers. The omnibus critical FF 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 FF 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.

# The book's arithmetic, using the rounded tabled value
((n - 1) * (a - 1) * 5.14) / (n - a + 1)
[1] 11.99333
#> 11.99 — matches book p. 730; R's unrounded 5.1433 gives 12.0009 instead

The omnibus critical FF 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:D‾±wsD2/n\bar{D} \pm w \sqrt{s^2_D / n}

Where ww is the critical value (a tt-value or the square root of an FF-value). The choice of ww 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.

data(chapter_13_table_6)

# Create the difference variable
D1 <- chapter_13_table_6$Months36 - chapter_13_table_6$Months30

# Calculate the mean and standard error of the difference
mean_D1 <- mean(D1)
se_D1 <- sd(D1) / sqrt(length(D1))

cat("Sample Mean Difference:", mean_D1, "\n")
Sample Mean Difference: 4 
cat("Standard Error of Difference:", se_D1, "\n")
Standard Error of Difference: 2.579053 
#> Dbar = 4.00 and the standard error is 2.58 — matches book p. 731, which gets the
#> same standard error from 878/11 = 79.82, sqrt(79.82) = 8.93, 8.93/sqrt(12) = 2.58

Unadjusted Confidence Interval

First, let’s form an unadjusted 95% confidence interval, assuming this was our only planned comparison.

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)))
     t_crit sqrt_F_crit 
   2.200985    2.200985 
#> Both equal 2.20 — the book reads critical F = 4.84 and takes its square root,
#> 2.20, on p. 731

# Calculate the Margin of Error and limits
moe_unadj <- t_crit_unadj * se_D1
CI_unadj <- c(mean_D1 - moe_unadj, mean_D1 + moe_unadj)

cat("Margin of error:", moe_unadj, "\n")
Margin of error: 5.676458 
cat("Unadjusted 95% CI: [", CI_unadj[1], ",", CI_unadj[2], "]\n")
Unadjusted 95% CI: [ -1.676458 , 9.676458 ]
#> 4.00 +/- 5.68, so [-1.676, 9.676] — matches book p. 731 and the "36 minus 30"
#> row of Table 13.12, p. 731

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 C=3C = 3). We need to widen the interval to hold familywise alpha at .05.

C <- 3

# Critical t-value for Bonferroni adjusted alpha = .05 / 3
t_crit_bonf <- qt(0.025 / C, df, lower.tail = FALSE)
c(F_crit = qf(0.05 / C, 1, df, lower.tail = FALSE), w = t_crit_bonf)
  F_crit        w 
7.952590 2.820034 
#> Critical F = 7.95 and w = 2.82 — matches book p. 732

# Calculate the Margin of Error and limits
moe_bonf <- t_crit_bonf * se_D1
CI_bonf <- c(mean_D1 - moe_bonf, mean_D1 + moe_bonf)

cat("Margin of error:", moe_bonf, "\n")
Margin of error: 7.273017 
cat("Bonferroni Adjusted 95% CI: [", CI_bonf[1], ",", CI_bonf[2], "]\n")
Bonferroni Adjusted 95% CI: [ -3.273017 , 11.27302 ]
#> 4.00 +/- 7.27 — matches book p. 732

# How much wider the Bonferroni interval is
moe_bonf / moe_unadj
[1] 1.28126
#> 1.28, i.e. roughly 28% wider — matches book p. 732

Both 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).

# Define the age values
X <- c(30, 36, 42, 48)

# Calculate deviations from the mean and sum of squares
X_dev <- X - mean(X)
SS_X <- sum(X_dev^2)

cat("Deviations:", X_dev, " Sum of squares:", SS_X, "\n")
Deviations: -9 -3 3 9  Sum of squares: 180 
#> Deviations -9, -3, 3, 9 with sum of squares 180 — matches book p. 733

# Create the appropriately scaled coefficients
slope_coefs <- X_dev / SS_X
cat("Scaled Slope Coefficients:", slope_coefs, "\n")
Scaled Slope Coefficients: -0.05 -0.01666667 0.01666667 0.05 
#> -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)$coefficients
            Estimate Std. Error  t value   Pr(>|t|)
(Intercept)      0.5  0.2230792 2.241357 0.04659037
# the 95% CI
confint(lm_slope)
                  2.5 %    97.5 %
(Intercept) 0.009006088 0.9909939
#> slope = 0.50 (SE 0.223, t = 2.24, p = .0466), 95% CI [0.0090, 0.9910] — matches
#> the "Mean linear" row of Table 13.12, book p. 731

The 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 DD 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 DD variables (three adjacent differences, plus the 48-vs-30 difference) and the linear-slope variable, then fit one intercept-only model to each.

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 chunk

With 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:

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
#> Intercepts 4.00 (SE 2.579), 3.00 (SE 2.758), 2.00 (SE 2.233), 9.00 (SE 3.693),
#> and 0.50 (SE 0.223) — all five match Table 13.12, book p. 731

The same contrasts as a gtsummary table, each under its own spanning header, with the 95% confidence intervals shown alongside the estimates:

t_36_30 <- tbl_regression(fit_36_30, intercept = TRUE)
t_48_30 <- tbl_regression(fit_48_30, intercept = TRUE)
t_slope <- tbl_regression(fit_slope, intercept = TRUE)
tbl_merge(list(t_36_30, t_48_30, t_slope),
          tab_spanner = c("**36 - 30**", "**48 - 30**", "**Mean linear**"))
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
#> Confidence limits -1.68 to 9.68, 0.87 to 17.13, and 0.009 to 0.991 — match the
#> corresponding rows of Table 13.12, book p. 731

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 MSA/MSA×SMS_A / MS_{A \times S}) appear entirely different. However, we can use orthonormal contrasts to reveal the mathematical connection between them.

An orthonormal contrast meets two conditions:

  1. Orthogonal: The sum of the cross-products of the coefficients equals zero.

  2. 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 (D1D_1 and D2D_2). 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 D1*D^*_1 and D2*D^*_2.

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")
Normalized Linear Coefficients: -0.7071068 0 0.7071068 
cat("Normalized Quadratic Coefficients:", norm_quad, "\n\n")
Normalized Quadratic Coefficients: -0.4082483 0.8164966 -0.4082483 
#> -0.70711, 0, 0.70711 and -0.40825, 0.81650, -0.40825 — matches book p. 734

# Check both orthonormality conditions by hand: cross-products sum to zero, and each
# set of squared coefficients sums to one.
cat("Sum of cross-products:", sum(norm_lin * norm_quad), "\n")
Sum of cross-products: 0 
cat("Sums of squared coefficients:", sum(norm_lin^2), sum(norm_quad^2), "\n")
Sums of squared coefficients: 1 1 
# 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")]
  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.2247449

One 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.

is_orthogonal_set(cbind(linear = norm_lin, quadratic = norm_quad))
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 (E*(F)E^*(F)) and the restricted model (E*(R)E^*(R)), using our normalized variables. We will use the same intercept-only regression trick from earlier in the chapter.

# 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)
          [,1]      [,2]
[1,] 16.000000 -7.505553
[2,] -7.505553  7.333333
#> rows (16.0000, -7.5056) and (-7.5056, 7.3333) — matches book p. 735, which prints
#> the off-diagonal as -7.5055 (the exact value is -7.50555, so the book truncates
#> where R rounds)

# Restricted Model Error Matrix E*(R)
print(E_star_R)
           [,1]       [,2]
[1,] 52.0000000 -0.5773503
[2,] -0.5773503  8.6666667
#> rows (52.0000, -0.5774) and (-0.5774, 8.6667) — matches book p. 735

These matrices are only a change of metric, so the omnibus test should be untouched. Rather than assert that, compute it:

det_star_F <- det(E_star_F)
det_star_R <- det(E_star_R)
c("|E*(F)|" = det_star_F, "|E*(R)|" = det_star_R)
 |E*(F)|  |E*(R)| 
 61.0000 450.3333 
#> 61.0000 and 450.3333 — matches book p. 735

# Equation 13.22 with df_F = 6 and df_R = 8
((det_star_R - det_star_F) / 2) / (det_star_F / 6)
[1] 19.14754
#> 19.148 — the same omnibus F found in Section 13.4 with the unnormalized
#> variables, matching book p. 735

13.11.2 — Comparison of the Two Approaches

So, why go through the trouble of normalizing? Because the resulting E*(F)E^*(F) and E*(R)E^*(R) matrices allow us to easily extract the mixed-model ANOVA results.

Consider the trace of our E*(F)E^*(F) matrix. The trace is simply the sum of the diagonal elements.

  • Trace of E*(F)=16.0000+7.3333=23.3333E^*(F) = 16.0000 + 7.3333 = 23.3333.

Similarly, let’s look at the trace of the E*(R)E^*(R) matrix:

  • Trace of E*(R)=52.0000+8.6667=60.6667E^*(R) = 52.0000 + 8.6667 = 60.6667.

If we subtract the trace of the full model from the trace of the restricted model:

  • 60.6667−23.3333=37.333360.6667 - 23.3333 = 37.3333.

37.3333 is exactly the sum of squares for the Time main effect in the mixed-model ANOVA.

# 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"
)
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 
#> tr(E*(F)) = 23.3333, tr(E*(R)) = 60.6667, difference 37.3333 — matches book p. 736
#> and the SS column of Table 13.13 there

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 F=MSTime/MSA×SF = MS_{Time} / MS_{A \times S}:

# 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

#> Time: SS = 37.3333, df = 2, MS = 18.6667, F = 11.2, p = .0012;
#> Subjects x Time: SS = 23.3333, df = 14, MS = 1.6667
#> — every cell matches Table 13.13, book p. 736

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 ε\varepsilon adjustments the mixed-model approach needs when sphericity is in doubt.

anova_within(chapter_13_table_2[, c("Time1", "Time2", "Time3")])
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
#> Unadjusted row: F = 11.200 on (2, 14) df, p = .0012 — the same F, df, and p as
#> the table built from the traces above, and as Table 13.13, book p. 736

The unadjusted row is identical to the table assembled from the traces. The remaining rows are the ε̂\hat{\varepsilon} and ε̃\tilde{\varepsilon} adjustments of Chapter 11: they leave FF 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:

  1. The Multivariate Approach uses the determinant of the error matrices, meaning it uses all the information, including the off-diagonal covariance elements.

  2. 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, E11*(F)/(n−1)E^*_{11}(F) / (n-1). This is the variance of that particular D*D^* variable.

  • The mixed-model approach (pooled error term) uses a single error term that averages the variances of all a−1a-1 orthonormal contrasts. That pooled term is MSA×SMS_{A \times S}.

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 F=15.75F = 15.75. Let’s recreate both the multivariate and mixed-model FF statistics to see exactly how they differ.

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"
)
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 
#> E*_11(R) - E*_11(F) = 36, multivariate F = 15.75, mixed-model F = 21.6
#> — matches book p. 739

For the linear trend, the mixed-model FF of 21.6 is nearly 40% larger than the multivariate FF of 15.75. Does that make the mixed-model approach better? Not necessarily. The mixed-model FF is larger here only because its denominator, MSA×S=1.6667MS_{A \times S} = 1.6667, is smaller than the variance specific to the linear trend, E11*(F)/7=16/7=2.29E^*_{11}(F)/7 = 16/7 = 2.29. A larger FF can arise for just two reasons: sampling error, which is as likely to shrink an FF 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 sD1*2s^2_{D^*_1}, the variance of the contrast actually being tested, while the mixed-model approach divides by s‾D*2\bar{s}^2_{D^*}, the average variance across all a−1a-1 orthonormal contrasts.

# Numerator is shared; only the denominator differs.
c(separate_error_term = E_star_F / (n - 1),
  pooled_error_term   = MS_AxS)
separate_error_term   pooled_error_term 
           2.285714            1.666667 
#> 16/7 = 2.286 against 1.6667: the pooled term is the average of the two D* variances,
#> (16 + 7.3333)/2/7, which is why it differs from the linear trend's own variance

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.

# 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"
)
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 
#> E*_11(F) = 3, E*_11(R) = 19, multivariate F = 37.3333, mixed-model F = 9.6
#> — matches book p. 742

Notice how things have flipped. The multivariate FF of 37.33 is now almost four times the mixed-model FF of 9.6 — the book puts it the other way round, that the mixed-model FF 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 T2−T1T_2 - T_1 difference score, 3/7=0.433/7 = 0.43, is far smaller than the pooled MSA×SMS_{A \times S} of 1.6667.

The pair of examples makes the book’s point better than either does alone. When homogeneity of the D*D^* 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 ε\varepsilon adjustment repairs that, because an ε\varepsilon adjustment changes only the critical value and leaves MSA×SMS_{A \times S} 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():

# 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)

    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.09001

In DMAR the same test arrives alongside the estimated ε\varepsilon that the adjustment itself uses:

mauchly_test(chapter_13_table_2[, c("Time1", "Time2", "Time3")])
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_corrections(chapter_13_table_2[, c("Time1", "Time2", "Time3")])
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 ε̂=0.644\hat{\varepsilon} = 0.644 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 (λ\lambda).

For the multivariate approach, Equation 13.40 gives λ\lambda in matrix form:

λ=N(𝑪𝝁)′(𝑪𝚺𝑪′)−1(𝑪𝝁)\lambda = N(\mathbf{C}\boldsymbol{\mu})' \left(\mathbf{C}\boldsymbol{\Sigma}\mathbf{C}'\right)^{-1} (\mathbf{C}\boldsymbol{\mu})

Its three ingredients are:

  • 𝝁\boldsymbol{\mu}: a vector of the population means for each condition.

  • 𝚺\boldsymbol{\Sigma}: the population covariance matrix, holding the variances of the conditions and the correlations between them.

  • 𝑪\mathbf{C}: a contrast matrix (or vector) that defines exactly what hypothesis is being tested.

If 𝑪\mathbf{C} has a−1a-1 rows, Equation 13.40 returns the noncentrality parameter for the omnibus test. If 𝑪\mathbf{C} 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 FF probability.

# 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 ε̂\hat{\varepsilon} 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 (10,13,1610, 13, 16), but the most disparate means (1010 and 1616) have the lowest correlation (0.30.3) while adjacent means have the highest (0.60.6). Scenario 2 reorders the means to 10,16,1310, 16, 13 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.

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)
   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.899
#> Scenario 1: .212 .340 .463 .574 .669 — matches book p. 747
#> Scenario 2: .343 .550 .712 .826 .899 — matches book p. 747

Equation 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 n=30n = 30 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 𝑪\mathbf{C} becomes a single row.

Return to Scenario 1, where the means 10,13,1610, 13, 16 describe a perfect linear trend and where the multivariate omnibus test was the weaker of the two omnibus options.

C_linear <- matrix(c(-1, 0, 1), nrow = 1)   # one row: the linear trend

linear_power <- sapply(sample_sizes, function(nn)
  power_multivariate(mu_scenario_1, cor_matrix_1, variance_pop, C_linear, nn, a = 3))

data.frame(n = sample_sizes, Linear_trend = round(linear_power, 3))
   n Linear_trend
1 10        0.310
2 15        0.463
3 20        0.594
4 25        0.700
5 30        0.782
#> .310 .463 .594 .700 .782 — matches book p. 749

At n=30n = 30, 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 ε̂\hat{\varepsilon}-adjusted omnibus test, which it reports at .763 for n=30n = 30 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 ε̂\hat{\varepsilon}-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”:

  1. The power of an FF test whose critical value is set from the population ε\varepsilon. Nobody can run that test, because nobody knows ε\varepsilon.
  2. The power of the test a researcher actually runs, in which ε̂\hat{\varepsilon} is computed from the very same sample that produces FF, so the critical value is itself a random variable.
  3. 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 ε\varepsilon is a feature of 𝚺\boldsymbol{\Sigma} alone. Write 𝑼\mathbf{U} for an orthonormal basis of the (a−1)(a-1)-dimensional space of within-subjects contrasts, let 𝑬*=𝑼𝚺𝑼′\mathbf{E}^{*} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{U}', and let ϕ1,…,ϕa−1\phi_1, \ldots, \phi_{a-1} be the eigenvalues of 𝑬*\mathbf{E}^{*}. Then

ε=(∑iϕi)2(a−1)∑iϕi2\varepsilon = \frac{\left(\sum_i \phi_i\right)^{2}}{(a-1)\sum_i \phi_i^{2}}

so ε=1\varepsilon = 1 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 𝑪\mathbf{C} as long as its rows span the contrast space, which is why C_omnibus above could be written with convenient −1,1,0-1, 1, 0 rows. The univariate route’s ε\varepsilon is not invariant: it is built from the eigenvalues of 𝑬*\mathbf{E}^{*}, so a 𝑼\mathbf{U} 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.

ε̂\hat{\varepsilon} substitutes the sample covariance matrix for 𝚺\boldsymbol{\Sigma} in that same formula. Because the ratio is a nonlinear function of the ϕi\phi_i, the substitution is biased, and biased downward — ε̂\hat{\varepsilon} 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 E(ε̂)E(\hat{\varepsilon}) built from the same eigenvalues, and it is that approximation, not ε\varepsilon, 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. ε̂\hat{\varepsilon} is a ratio, and the formula replaces the expectation of the ratio with a ratio of expectations: E[(tr𝑾)2]E[(\mathrm{tr}\,\mathbf{W})^{2}] over (a−1)E[tr𝑾2](a-1)\,E[\mathrm{tr}\,\mathbf{W}^{2}], where 𝑾=ν𝑺*\mathbf{W} = \nu\mathbf{S}^{*} is the Wishart matrix on ν=n−1\nu = n - 1 degrees of freedom built from the sample contrast covariance 𝑺*\mathbf{S}^{*} (the ν\nu cancels, since the ratio is scale-free). Those two are not the same number, and at these sample sizes they are not close. E(ε̂)E(\hat{\varepsilon}) itself has no comparably simple closed form, but it can be simulated directly, so all three quantities fit in one table:

# 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)
   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.868
#> Scenario 1: epsilon = .862 at every n; Muller-Barton = .747 .781 .800 .812 .820;
#>   simulated E(eps-hat) = .787 .812 .827 .833 .839
#> Scenario 2: epsilon = .9 at every n; Muller-Barton = .771 .810 .830 .843 .852;
#>   simulated E(eps-hat) = .806 .836 .852 .861 .868

Read that table across. The population ε\varepsilon does not move with nn — 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 nn, and they say the same thing at different magnitudes.

The bias in ε̂\hat{\varepsilon} is real. In Scenario 1 at ten subjects its expectation is 0.787 against a population ε\varepsilon of 0.862, so the statistic a researcher computes is expected to understate ε\varepsilon 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 E(ε̂)E(\hat{\varepsilon}), 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 ϕi\phi_i as weights and, in the numerator, noncentralities ωi\omega_i 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 tt test its fractional degrees of freedom — and the ratio of the two becomes an approximating noncentral FF with degrees of freedom ν1*\nu_1^{*} and ν2*\nu_2^{*} and noncentrality λ\lambda. Power is then the probability that this approximating FF exceeds a critical value built on ε\varepsilon-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:

# 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)
   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.791
#> Scenario 1: .282 .437 .569 .677 .763 — matches book p. 747
#> Scenario 2: .233 .398 .555 .688 .791 — matches book p. 747

All 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 𝝁\boldsymbol{\mu}, 𝚺\boldsymbol{\Sigma}, nn, and α\alpha.

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 ε̂\hat{\varepsilon} from that sample, compare FF to the critical value that ε̂\hat{\varepsilon} 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.

# 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)
   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.788
#> Simulated Scenario 1: .284 .436 .567 .673 .760 (book .282 .437 .569 .677 .763)
#> Simulated Scenario 2: .241 .408 .556 .684 .788 (book .233 .398 .555 .688 .791)

# Monte Carlo standard error at 20,000 replications
round(sqrt(0.25 / 20000), 4)                                  # worst case, at p = .5
[1] 0.0035
round(sqrt(gg_check$Simulated_S1 * (1 - gg_check$Simulated_S1) / 20000), 4)
[1] 0.0032 0.0035 0.0035 0.0033 0.0030
#> .0035 at worst; .0030 to .0035 across this table

Twenty 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 p(1−p)/20000\sqrt{p(1-p)/20000}, 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 n=15n = 15 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 E(ε̂)E(\hat{\varepsilon}) — 0.771 against 0.806 at n=10n = 10 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:

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)
   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.794
#> Scenario 1: .282 .437 .569 .677 .763 becomes .292 .444 .575 .682 .766
#> Scenario 2: .233 .398 .555 .688 .791 becomes .243 .406 .561 .693 .794

In Scenario 2 that one change lands on the 200,000-replication simulation almost exactly — .243 against .242 at n=10n = 10 and .406 against .405 at n=15n = 15, 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 ε̂\hat{\varepsilon} that is random and computed from the same sample as FF, so the two are not independent, and the Satterthwaite match to the distribution of FF 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 n=10n = 10, and by .001 or less in both by n=30n = 30. 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 ε\varepsilon were known?

The epsilon argument makes the first of the three quantities listed earlier available for comparison. Substituting the population ε\varepsilon 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:

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)
   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.801
#> Known-epsilon Scenario 1: .309 .456 .583 .687 .770
#> Known-epsilon Scenario 2: .266 .424 .575 .702 .801

The 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 nn grows, exactly as the epsilon table predicted: the Muller–Barton value closes on ε\varepsilon, so the real test’s extra conservatism fades. This is not an academic distinction. Planning a study at n=10n = 10 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 ε\varepsilon, the idealized test of the previous subsection, while ANOVA_power(design, correction = "GG", nsims = ...) simulates data sets and fits each with afex, which estimates ε̂\hat{\varepsilon} 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 FF. 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 𝝁\boldsymbol{\mu} and 𝚺\boldsymbol{\Sigma}:

three_approaches <- data.frame(
  n            = sample_sizes,
  GG_adjusted  = gg_power_table$Scenario_1,   # UNIREP, Muller-Barton epsilon
  Multivariate = mv_power_table$Scenario_1,   # Equation 13.40, C has a - 1 rows
  Linear_trend = linear_power                 # Equation 13.40, C has one row
)
round(three_approaches, 3)
   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.782
#> GG:           .282 .437 .569 .677 .763 — matches book p. 749
#> Multivariate: .212 .340 .463 .574 .669 — matches book p. 749
#> Linear trend: .310 .463 .594 .700 .782 — matches book p. 749

That 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 𝑪\mathbf{C}: the same power_multivariate() call, handed a two-row 𝑪\mathbf{C}, gives the omnibus test, and handed the single row −1,0,1-1, 0, 1, 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 n=20n = 20. In Scenario 2 the ordering reverses and the multivariate margin is the larger of the two, reaching .157 at n=20n = 20. 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 n=30n = 30) 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