R Companion — All Chapters

Book website · Chapter data

Chapter 1: The Logic of Experimental Design and Analysis

Open the separate reading

Code
Results
On this page

Chapter 1 is largely conceptual, situating statistical reasoning within the philosophy and history of science. The quantitative material appears in Section 1.4, Introduction to the Fisher Tradition, which develops two classic examples from first principles: a discrete probability example (Fisher’s tea-tasting experiment, §1.4.2) and a randomization test (the Bayley twins example, §1.4.3). This document reproduces those examples in R, one-to-one with the book.

HideShow
# Load all of the packages used.
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(ggplot2)        # the grammar of graphics used for the book's data figures
library(dplyr)          # data manipulation used by some of the figures

R ignores everything to the right of a # on a line, so the comments in the code throughout this page are notes to the reader rather than instructions to R.

The book’s data in R

The AMCP package supplies the book’s data. Install the packages used in this chapter from CRAN once.

HideShow
install.packages(c("AMCP", "DMAR", "ggplot2", "dplyr"))

With AMCP loaded, data() brings a data set into the session. The names follow the book’s own numbering: chapter_1_table_1 holds Table 1.1 and chapter_11_table_20 holds Table 11.20, while the data behind an end-of-chapter exercise replace table with exercise, as in chapter_1_exercise_21. Short forms work as well, abbreviating those two as C1T1 and C1E21. A suffix marks the few data sets that come in more than one form: _raw where the book itself prints only summary statistics (chapter_3_table_7_raw), and _univariate where the same data are also supplied in a long layout (chapter_15_exercise_18_univariate). data(package = "AMCP") lists every data set in the package, and ?chapter_1_table_1 documents an individual one.

R preliminaries with the Table 1.1 data

The data set we use here is chapter_1_table_1, the Bayley Mental Scale scores for ten pairs of twins shown in Table 1.1 of the book. We return to these data for the randomization test in §1.4.3; for now they give us a concrete data set on which to introduce some base R.

Loading and viewing the data

We load a data set with the data() function.

HideShow
data(chapter_1_table_1)

To see the data, simply type its name. Output on these pages is shown directly beneath the code that produced it, without a prefix; in your own console R prefixes printed values with an index such as [1]. (Pressing the up arrow in the console recalls a previously entered command, ready to run again.)

HideShow
chapter_1_table_1
HideShow
   treat control week
1     28      32    1
2     31      25    1
3     25      15    1
4     23      25    1
5     28      16    1
6     26      30    2
7     36      24    2
8     23      13    2
9     23      25    2
10    24      16    2

The data are organized by condition (treat, control) and by week, with one row per twin pair. For larger data sets you may want only the first part (with head()) or the last part (with tail()).

HideShow
head(chapter_1_table_1)
HideShow
  treat control week
1    28      32    1
2    31      25    1
3    25      15    1
4    23      25    1
5    28      16    1
6    26      30    2
HideShow
tail(chapter_1_table_1)
HideShow
   treat control week
5     28      16    1
6     26      30    2
7     36      24    2
8     23      13    2
9     23      25    2
10    24      16    2

Creating the difference score

This is a paired (matched-pairs) design, so a natural quantity is the difference between the two paired conditions. We extract the treat and control values, subtract, and store the result as a new variable, Difference, in the data frame.

The $ operator extracts the variable on its right from the data frame on its left; for example, Data$Score extracts Score from Data. Placing $ after a data frame and a new name, together with the assignment operator <-, creates that new variable in the data frame. The assignment operator assigns what is on the right (here, the result of a calculation) to the object on the left.

HideShow
chapter_1_table_1$Difference <- chapter_1_table_1$treat - chapter_1_table_1$control
chapter_1_table_1
HideShow
   treat control week Difference
1     28      32    1         -4
2     31      25    1          6
3     25      15    1         10
4     23      25    1         -2
5     28      16    1         12
6     26      30    2         -4
7     36      24    2         12
8     23      13    2         10
9     23      25    2         -2
10    24      16    2          8

Summarizing the data

There are many ways to summarize data in R. Using only base R (the functions that come with R, with no add-on packages), we can extract a subset of interest and then apply a function to it. Subsetting matters here because the data are structured by condition and by week, and because—this being a paired design—there is a linkage among the scores that we should respect.

We subset with square brackets, Data[rows, columns]. To the left of the comma we identify the rows: chapter_1_table_1$week == 1 returns TRUE/FALSE for each row, and R keeps the TRUE rows. To the right of the comma we name the column. For example, the Week 1 scores for the Treatment group are:

HideShow
chapter_1_table_1[chapter_1_table_1$week == 1, "treat"]
HideShow
[1] 28 31 25 23 28

Applying a few functions to that subset gives descriptive statistics for the Week 1 Treatment group (other descriptive statistics can be requested as well):

HideShow
sum(chapter_1_table_1[chapter_1_table_1$week == 1, "treat"])
HideShow
[1] 135
HideShow
mean(chapter_1_table_1[chapter_1_table_1$week == 1, "treat"])
HideShow
[1] 27
HideShow
sd(chapter_1_table_1[chapter_1_table_1$week == 1, "treat"])
HideShow
[1] 3.082207
HideShow
summary(chapter_1_table_1[chapter_1_table_1$week == 1, "treat"])
HideShow
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
     23      25      28      27      28      31 

The same pattern gives the Week 1 Control group:

HideShow
sum(chapter_1_table_1[chapter_1_table_1$week == 1, "control"])
HideShow
[1] 113
HideShow
mean(chapter_1_table_1[chapter_1_table_1$week == 1, "control"])
HideShow
[1] 22.6
HideShow
sd(chapter_1_table_1[chapter_1_table_1$week == 1, "control"])
HideShow
[1] 7.092249
HideShow
summary(chapter_1_table_1[chapter_1_table_1$week == 1, "control"])
HideShow
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   15.0    16.0    25.0    22.6    25.0    32.0 

Rather than repeating this subsetting for every week-by-condition combination, we can reproduce the weekly sums of Table 1.1 at once, along with the corresponding weekly means (which the table itself does not report). The aggregate() function applies a function to each variable, broken down by week:

HideShow
# Weekly sums
aggregate(cbind(treat, control, Difference) ~ week, data = chapter_1_table_1, FUN = sum)
HideShow
  week treat control Difference
1    1   135     113         22
2    2   132     108         24
HideShow
#> 135 / 113 / 22 (Week 1) and 132 / 108 / 24 (Week 2) — matches book p. 29, Table 1.1

# Weekly means
aggregate(cbind(treat, control, Difference) ~ week, data = chapter_1_table_1, FUN = mean)
HideShow
  week treat control Difference
1    1  27.0    22.6        4.4
2    2  26.4    21.6        4.8

The overall (two-week) sums and means, the last two rows of Table 1.1, follow from colSums() and colMeans():

HideShow
colSums(chapter_1_table_1[, c("treat", "control", "Difference")])    # 267 / 221 / 46
HideShow
     treat    control Difference 
       267        221         46 
HideShow
colMeans(chapter_1_table_1[, c("treat", "control", "Difference")])   # 26.7 / 22.1 / 4.6
HideShow
     treat    control Difference 
      26.7       22.1        4.6 
HideShow
#> matches the last two rows of Table 1.1, book p. 29

1.4 — Introduction to the Fisher Tradition

Section 1.4 of the book derives two statistical tests entirely from first principles, so that the meaning of a pp value is transparent rather than something “looked up in a table.” Section 1.4.1 is conceptual; the worked examples begin in §1.4.2.

1.4.2 — A Discrete Probability Example

This is Fisher’s famous tea-tasting experiment. A lady claims she can taste whether the milk or the tea was poured first. She is given eight cups—four milk-first (MF) and four tea-first (TF), in random order—and asked to sort them into the two groups of four. If she cannot discriminate at all, every way of choosing four cups to call “milk-first” is equally likely, so the probability of a perfect performance by chance is one divided by the number of such choices.

Counting rules in R

How many ways are there to choose four cups out of eight to label MF? Following the book’s reasoning, there are 8×7×6×58 \times 7 \times 6 \times 5 ways to choose four cups in a particular order:

HideShow
8 * 7 * 6 * 5
HideShow
[1] 1680

But order does not matter—(A, B, C, D) is the same set as (D, C, B, A)—and each distinct set of four can be ordered in 4×3×2×14 \times 3 \times 2 \times 1 ways:

HideShow
factorial(4)
HideShow
[1] 24

Dividing the ordered count by the number of orderings of each set gives the number of distinct sets of four cups. This is Equation (1.2) in the book:

HideShow
# Equation (1.2): the number of distinct sets of four cups
(8 * 7 * 6 * 5) / (4 * 3 * 2 * 1)
HideShow
[1] 70

This quantity is the number of combinations of eight things taken four at a time, 8C4{}_{8}C_{4}. R computes combinations directly with choose(n, k):

HideShow
choose(n = 8, k = 4)
HideShow
[1] 70

The general counting rule, nCr=n!/[r!(n−r)!]{}_{n}C_{r} = n! \, / \, [r!(n - r)!], is Equation (1.3). The factorial() function evaluates it and returns the same 70 (note that factorial() can overflow for large arguments, which is one reason choose() is preferred in practice):

HideShow
# Equation (1.3): n! / (r! (n - r)!)
factorial(8) / (factorial(4) * factorial(8 - 4))
HideShow
[1] 70

Because only one of these 70 equally likely divisions is exactly correct, the probability of a perfect classification by chance alone is 1/701/70. This is Equation (1.1):

HideShow
# Equation (1.1): probability of being exactly correct by chance
1 / choose(n = 8, k = 4)
HideShow
[1] 0.01428571
HideShow
#> 0.01428..., the 1/70 of Equation (1.1); matches book p. 26

That value, about .014, is below the conventional .05 criterion: a perfect performance would be convincing evidence of discrimination ability.

To actually enumerate the choices, combn() returns a matrix whose columns are the distinct sets. There are 70 columns (one per set), so we look at the dimensions and the first few columns rather than printing all of them:

HideShow
dim(combn(x = 8, m = 4))      # 4 rows (cups per set) by 70 columns (sets)
HideShow
[1]  4 70
HideShow
combn(x = 8, m = 4)[, 1:8]    # the first eight of the 70 possible sets
HideShow
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    1    1    1    1    1
[2,]    2    2    2    2    2    2    2    2
[3,]    3    3    3    3    3    4    4    4
[4,]    4    5    6    7    8    5    6    7

Combinations are unordered choices. Permutations are ordered choices and count (A, B) and (B, A) separately. The number of ordered selections of four cups from eight—the 1,680 from earlier—is the permutation 8P4=n!/(n−r)!{}_{8}P_{4} = n! \, / \, (n - r)!:

HideShow
factorial(8) / factorial(8 - 4)
HideShow
[1] 1680

Base R has no function to enumerate permutations directly; see the permutations() function in the gtools package if a listing is needed.

Now consider a near-perfect performance: three of the four MF cups classified correctly. Misclassifying one MF cup necessarily means one TF cup was also misclassified, and the two choices are made independently. The number of ways to make one error of each kind is 4C3⋅4C1{}_{4}C_{3} \cdot {}_{4}C_{1}, Equation (1.4):

HideShow
# Equation (1.4): one error of each kind
choose(n = 4, k = 3) * choose(n = 4, k = 1)
HideShow
[1] 16

The probability of that near-perfect outcome is this count over the 70 possible divisions, Equation (1.5):

HideShow
# Equation (1.5): probability of three MF (and one TF) classified as MF
choose(n = 4, k = 3) * choose(n = 4, k = 1) / choose(n = 8, k = 4)
HideShow
[1] 0.2285714
HideShow
#> 0.2286..., the 16/70 = .229 of Equation (1.5); matches book p. 27

So the probability of performance at least this good—three or four correct—is the sum of the two cases, (16+1)/70≈.243(16 + 1)/70 \approx .243:

HideShow
(choose(n = 4, k = 3) * choose(n = 4, k = 1) + 1) / choose(n = 8, k = 4)
HideShow
[1] 0.2428571
HideShow
#> 0.2429..., the (16 + 1)/70 = .243 of "three or four correct"; matches book p. 27

Because .243 far exceeds .05, even the next-best-to-perfect outcome would not be convincing. Every probability computed above is a special case of the general rule in Equation (1.6) for selecting nn items from NN, of which RR are “right.” That rule is the hypergeometric probability, which R provides as dhyper(). Here N=8N = 8 cups, R=4R = 4 are truly MF (m), N−R=4N - R = 4 are TF (n), and the lady selects k=4k = 4:

HideShow
# Equation (1.6) via dhyper(): x correct of the 4 MF cups among the 4 labeled MF
dhyper(x = 3, m = 4, n = 4, k = 4)   # three correct: 16/70 = .229
HideShow
[1] 0.2285714
HideShow
dhyper(x = 4, m = 4, n = 4, k = 4)   # all four correct: 1/70 = .014
HideShow
[1] 0.01428571
HideShow
sum(dhyper(x = 3:4, m = 4, n = 4, k = 4))   # three or four correct: 17/70 = .243
HideShow
[1] 0.2428571
Fisher’s exact test in R

The test we have just built by hand is, in general, the Fisher-Irwin exact test, more commonly called Fisher’s exact test. R implements it with fisher.test(). The data are entered as a 2 × 2 table whose rows are the lady’s guesses and whose columns are the actual classifications.

We first consider a perfect performance (all four of each kind correct). Using matrix() to enter the table:

HideShow
TeaTasting_Perfect <- matrix(
  c(4, 0, 0, 4),
  nrow = 2,
  dimnames = list(Guess  = c("Milk-first", "Tea-first"),
                  Actual = c("Milk-first", "Tea-first"))
)
TeaTasting_Perfect
HideShow
            Actual
Guess        Milk-first Tea-first
  Milk-first          4         0
  Tea-first           0         4
HideShow
fisher.test(TeaTasting_Perfect, alternative = "greater")
HideShow

    Fisher's Exact Test for Count Data

data:  TeaTasting_Perfect
p-value = 0.01429
alternative hypothesis: true odds ratio is greater than 1
95 percent confidence interval:
 2.003768      Inf
sample estimates:
odds ratio 
       Inf 

The one-sided pp value is 0.0143—exactly the 1/701/70 we derived as Equation (1.1).

Now the near-perfect performance, with one error of each kind. An alternative way to enter the table is with rbind():

HideShow
TeaTasting_Near <- rbind("Milk-first" = c(3, 1),
                         "Tea-first"  = c(1, 3))
TeaTasting_Near
HideShow
           [,1] [,2]
Milk-first    3    1
Tea-first     1    3
HideShow
fisher.test(TeaTasting_Near, alternative = "greater")
HideShow

    Fisher's Exact Test for Count Data

data:  TeaTasting_Near
p-value = 0.2429
alternative hypothesis: true odds ratio is greater than 1
95 percent confidence interval:
 0.3135693       Inf
sample estimates:
odds ratio 
  6.408309 

The one-sided pp value is 0.2429—exactly the (16+1)/70=.243(16 + 1)/70 = .243 we obtained for “three or four correct.” So fisher.test() simply automates the counting we did by hand. (The reported odds-ratio estimate is a conditional maximum likelihood estimate and differs from the simple sample odds ratio; see ?fisher.test.)

Effect size for the 2 × 2 table

Beyond the pp value, it is useful to describe the magnitude of the effect. One option for a 2 × 2 table is the phi coefficient, which is the Pearson correlation between two binary variables—here, each cup’s Actual category and the lady’s Judged category. In the one-error-of-each-kind case the eight cups give the pairs the book lists, and the correlation is .50:

HideShow
Actual <- c(1, 1, 1, 1, 2, 2, 2, 2)   # true category of each cup (four MF, four TF)
Judged <- c(1, 1, 1, 2, 1, 2, 2, 2)   # the lady's classification (one error of each kind)
cor(Actual, Judged)
HideShow
[1] 0.5
HideShow
#> 0.50 — matches book p. 28

A phi of .50 corresponds to a large effect by Cohen’s benchmarks (.10, .30, .50 for small, medium, large).

A second option is the odds ratio, Equation (1.7), the ratio of the odds of “success” in the two rows:

odds ratio=p1/(1−p1)p2/(1−p2).\text{odds ratio} = \frac{p_{1} / (1 - p_{1})}{p_{2} / (1 - p_{2})}.

A small function makes this reusable. For the hypothesized success probabilities used in the power calculation below (p1=.9p_1 = .9, p2=.3p_2 = .3), the odds ratio is 21:

HideShow
odds_ratio <- function(p1, p2) (p1 / (1 - p1)) / (p2 / (1 - p2))
odds_ratio(p1 = 0.9, p2 = 0.3)
HideShow
[1] 21
Power of Fisher’s exact test (advanced)

This subsection follows the book’s footnote on the power of Fisher’s exact test and may be skipped on a first reading.

Power is the probability of detecting a true effect. For Fisher’s exact test with fixed marginals, power is computed from the noncentral hypergeometric distribution, whose noncentrality is the odds ratio θ\theta of the true success probabilities in the two rows. Suppose a tea-first cup is truly classified “tea-first” with probability .9 and a milk-first cup with probability .3, giving θ=21\theta = 21:

HideShow
p1 <- 0.9   # P(classify a tea-first cup as "tea-first")
p2 <- 0.3   # P(classify a milk-first cup as "tea-first")
theta <- odds_ratio(p1, p2)
theta
HideShow
[1] 21

With four cups of each kind, the only convincing outcome is perfect classification (all four, r=4r = 4). Summing the noncentral hypergeometric probabilities over the rejection region gives the power:

HideShow
numerator   <- choose(4, 4) * choose(4, 0) * theta^4
denominator <- sum(sapply(0:4, function(i) choose(4, i) * choose(4, 4 - i) * theta^i))
numerator / denominator
HideShow
[1] 0.541926

The power is about .542. This is appreciably larger than the value obtained if one incorrectly treats the two rows as independent binomials (as some software does), which assumes the lady is not constrained to give four responses of each kind:

HideShow
(choose(4, 4) * p1^4 * (1 - p1)^0) * (choose(4, 0) * p2^0 * (1 - p2)^4)
HideShow
[1] 0.1575296

That value, about .158, differs markedly from the correct .542—a reminder that the appropriate power computation depends on how the experiment constrains the responses.

The same power in DMAR

The DMAR package automates the power calculation with power_fisher_exact(). It evaluates power under the unconditional (independent-binomials) model, so it reports the .158 value, not the conditional .542. It is the right tool when the two margins are free to vary rather than fixed at four responses of each kind.

HideShow
power_fisher_exact(n_1 = 4, n_2 = 4, p_1 = 0.9, p_2 = 0.3,
                   alpha = 1 / choose(8, 4), alternative = "greater")
term value
power 0.158
odds_ratio_alt 21
p_1 0.900
p_2 0.300
expected_s 4.800
n_1 4
n_2 4
alpha_level 0.014

The power row reproduces the .158 independent-binomials value computed by hand just above; the agreement confirms that the two routes are the same calculation. What the call buys over the one-line hand formula is that it takes the two cell probabilities directly and reports the implied odds ratio and expected number of successes alongside the power, so the assumptions of the planned design are visible in the output. The conditional .542 is the power given the fixed margins of the tea-tasting design; the two answer different questions, so a power analysis should be explicit about which model the design implies.

1.4.3 — Randomization Test

The second example uses a quantitative outcome and again requires no assumption about the shape of the population distribution. A developmental psychologist asks whether brief training improves 2-year-olds’ scores on the Bayley Mental Scale. Ten pairs of twins take part; one twin from each pair is randomly assigned to training, the other to control. The measure of effect for each pair is the difference, Treatment − Control—the Difference variable we created earlier from chapter_1_table_1 (Table 1.1). The observed differences sum to 46.

Under the null hypothesis, the treatment has no effect, so each pair’s two scores were predetermined and the random assignment merely decided which sign the difference carried. With 10 pairs, there are 2102^{10} equally likely sign patterns; with the 5 pairs from Week 1 alone, there are 252^{5}:

HideShow
2^5
HideShow
[1] 32
HideShow
2^10
HideShow
[1] 1024
The logic, illustrated with Week 1

If the first week were the whole experiment, we would have five differences, hence 25=322^5 = 32 possible assignments of signs. The observed Week 1 differences are:

HideShow
week1_diff <- chapter_1_table_1[chapter_1_table_1$week == 1, "Difference"]
week1_diff
HideShow
[1] -4  6 10 -2 12

expand.grid() lists every combination of the supplied values. Giving it each observed difference paired with its sign-reversed value produces all 32 sign patterns (this reproduces Table 1.2 of the book; the first listed value of each pair is the observed difference):

HideShow
Possible_Assignments_Week1 <- expand.grid(
  Pair1 = c(-4,  4),
  Pair2 = c( 6, -6),
  Pair3 = c(10, -10),
  Pair4 = c(-2,  2),
  Pair5 = c(12, -12)
)
head(Possible_Assignments_Week1)
HideShow
  Pair1 Pair2 Pair3 Pair4 Pair5
1    -4     6    10    -2    12
2     4     6    10    -2    12
3    -4    -6    10    -2    12
4     4    -6    10    -2    12
5    -4     6   -10    -2    12
6     4     6   -10    -2    12

We sum each row with apply() (using MARGIN = 1 to work row by row), then ask what proportion of the 32 sums are at least as large as the observed Week 1 total of 22. Because every sign pattern is equally likely under the null hypothesis, that proportion is the one-tailed pp value:

HideShow
Week1_Sums <- apply(Possible_Assignments_Week1, 1, sum)
sort(Week1_Sums, decreasing = TRUE)
HideShow
 [1]  34  30  26  22  22  18  14  14  10  10  10   6   6   2   2   2  -2  -2  -2
[20]  -6  -6 -10 -10 -10 -14 -14 -18 -22 -22 -26 -30 -34
HideShow
sum(Week1_Sums >= 22)        # how many of the 32 sums reach the observed 22
HideShow
[1] 5
HideShow
mean(Week1_Sums >= 22)       # the proportion: 5/32 = .16
HideShow
[1] 0.15625
HideShow
#> 5 of 32 — matches book p. 31 (Table 1.2)

Five of the 32 assignments give a total of 22 or more, so the one-tailed probability is 5/32≈.165/32 \approx .16—not small enough to claim significance for Week 1 alone.

Figure 1.2. Distribution of possible totals of difference scores (Week 1)

Section 1.4.3 develops a randomization test from the five matched-pairs difference scores observed in Week 1. Under the null hypothesis that training had no effect, each pair’s difference was equally likely to carry a plus or a minus sign, giving 25=322^5 = 32 equally likely totals. This figure is the grouped relative-frequency histogram of those 32 totals, with the bars at totals at least as large as the observed +22 shaded; that shaded area, 5/32≈.165/32 \approx .16, is the one-tailed pp value. We build the 32 totals directly from chapter_1_table_1, so the figure is reproduced exactly rather than transcribed.

HideShow
# week1_diff was created above from Table 1.1; its total is the observed +22.
observed_total <- sum(week1_diff)

# All 2^5 = 32 sign patterns; each row's total is one possible reassignment.
signs <- as.matrix(expand.grid(rep(list(c(1, -1)), length(week1_diff))))
totals <- as.vector(signs %*% week1_diff)

# Group the 32 totals into the book's width-8 bins. Each bin spans two of the
# possible totals (which are 4 apart), e.g. "-34 or -30", ..., "+30 or +34".
breaks  <- seq(-36, 36, by = 8)
centers <- head(breaks, -1) + 4                       # bin midpoints: -32, -24, ...
labels  <- sprintf("%+d or %+d", centers - 2, centers + 2)
binned  <- cut(totals, breaks = breaks, right = FALSE)

fig_1_2 <- data.frame(table(binned)) |>
  mutate(center = centers,
         label  = factor(labels, levels = labels),
         # Shade the bins whose totals are >= the observed +22.
         shaded = center + 2 >= observed_total)

ggplot(fig_1_2, aes(label, Freq / 32, fill = shaded)) +
  geom_col(color = "black", width = 1) +
  scale_fill_manual(values = c(`FALSE` = "white",
                               `TRUE`  = "#0C2340"),
                    guide = "none") +
  # Break on whole counts out of 32 so the axis reads 0/32, 1/32, 2/32, ...
  scale_y_continuous(breaks = (0:8) / 32,
                     labels = function(p) paste0(round(p * 32), "/32")) +
  labs(x = "Total of difference scores", y = "Relative frequency") +
  theme(axis.text.x = element_text(size = rel(0.85)))
Figure 1.2. Distribution of possible totals of difference scores using data from Week 1.

Figure 1.2. Distribution of possible totals of difference scores using data from Week 1.

The two shaded bars are the totals of +22 or more (the +22-or-+26 bin and the +30-or-+34 bin); together they hold 5 of the 32 equally likely totals, the 5/32≈.165/32 \approx .16 that Section 1.4.3 reports for Week 1 alone.

The full ten-pair test

Listing all 210=1,0242^{10} = 1{,}024 sign patterns by hand is impractical, so we write a small function that builds them for any set of differences. expand.grid() produces every combination of +1+1 and −1-1 across the pairs; multiplying those sign patterns by the differences and summing gives one total per assignment:

HideShow
all_signflip_sums <- function(differences) {
  n <- length(differences)
  # Each row of 'signs' is one of the 2^n ways to attach +1 or -1 to each difference.
  signs <- as.matrix(expand.grid(rep(list(c(1, -1)), n)))
  # Multiply each sign pattern by the differences and sum: one total per assignment.
  as.vector(signs %*% differences)
}

The function reproduces the Week 1 result, and then gives us the full ten-pair distribution:

HideShow
# Check: Week 1 still gives 5/32 = .16
mean(all_signflip_sums(week1_diff) >= 22)
HideShow
[1] 0.15625
HideShow
# All ten pairs
all_diff      <- chapter_1_table_1$Difference
all_sums      <- all_signflip_sums(all_diff)
observed_sum  <- sum(all_diff)
observed_sum                       # 46
HideShow
[1] 46
HideShow
length(all_sums)                   # 1024 assignments
HideShow
[1] 1024

The one-tailed pp value is the proportion of the 1,024 totals that are at least 46:

HideShow
sum(all_sums >= observed_sum)      # 40 of the 1024 assignments
HideShow
[1] 40
HideShow
mean(all_sums >= observed_sum)     # 40/1024 = .039 (one-tailed)
HideShow
[1] 0.0390625
HideShow
#> "only 40 of 1,024, or .039" — matches book p. 31

Only 40 of 1,024 assignments (about .039) reach the observed total, so a one-tailed randomization test gives significant evidence that training improved performance. The breakdown by how the totals compare to 46 reproduces Table 1.3:

HideShow
c(greater = sum(all_sums >  observed_sum),
  equal   = sum(all_sums == observed_sum),
  less    = sum(all_sums <  observed_sum))   # 26, 14, 984
HideShow
greater   equal    less 
     26      14     984 
HideShow
#> the Sum > 46 / Sum = 46 / Sum < 46 totals of Table 1.3; matches book p. 32

Because the randomization distribution is symmetric, a two-tailed test counts totals at least as extreme as 46 in either direction, giving 80/1024≈.07880/1024 \approx .078:

HideShow
sum(abs(all_sums) >= observed_sum)     # 80
HideShow
[1] 80
HideShow
mean(abs(all_sums) >= observed_sum)    # 80/1024 = .078 (two-tailed)
HideShow
[1] 0.078125

So the directional conclusion (one-tailed .039) and the nondirectional conclusion (two-tailed .078) differ on the .05 criterion—a reminder that the choice of a one- or two-tailed test must be made on substantive grounds.

The same test in DMAR

The hand enumeration above is exactly what DMAR’s randomization_test_paired() automates. It enumerates all 2n2^{n} sign patterns when nn is small (here n=10n = 10, so all 1,024) and falls back to Monte Carlo sampling when nn is large. The x = control, y = treat ordering matches the book’s Treatment − Control direction:

HideShow
randomization_test_paired(x = chapter_1_table_1$control,
                          y = chapter_1_table_1$treat,
                          statistic = "mean", alternative = "greater")
term value
statistic 4.600
p_value 0.0391
n_pairs 10
n_evaluated 1024
exact 1

The p_value row reproduces the one-tailed 40/1024≈.03940/1024 \approx .039; the two-sided version (set alternative = "two.sided") returns the 80/1024≈.07880/1024 \approx .078 we found by hand. The hand enumeration and the DMAR call agree exactly, as they must—the function automates the counting rather than substituting a different test. What it buys is the bookkeeping and a Monte Carlo fallback for a sample too large to enumerate, neither of which changes the answer here.

A paired effect size: the probability of superiority

The pp value says how surprising the result is under the null hypothesis; it does not say how large the effect is. For a matched-pairs design a natural companion is the probability of superiority: the probability that the trained twin of a pair outscores its control. It uses only the order within each pair, not the size of the difference, so no distributional assumption is needed—the same spirit as the randomization test.

Base R gets the estimate by counting, with no package at all. Each pair is one comparison, so we count the pairs training won, the pairs that tied, and take the proportion:

HideShow
sum(chapter_1_table_1$treat >  chapter_1_table_1$control)    # pairs won by training: 6
HideShow
[1] 6
HideShow
sum(chapter_1_table_1$treat == chapter_1_table_1$control)    # tied pairs: 0
HideShow
[1] 0
HideShow
mean(chapter_1_table_1$treat >  chapter_1_table_1$control)   # 6 of 10 = .60
HideShow
[1] 0.6

Six of the ten pairs favor training, so the estimate is 6/10=.606/10 = .60. Because the sampling unit is the pair and no pair is tied, that proportion is a binomial one, and base R’s binom.test() attaches an exact (Clopper–Pearson) interval to it:

HideShow
binom.test(
  x           = sum(chapter_1_table_1$treat > chapter_1_table_1$control),
  n           = nrow(chapter_1_table_1),
  p           = 0.5,
  alternative = "two.sided",
  conf.level  = 0.95
)
HideShow

    Exact binomial test

data:  sum(chapter_1_table_1$treat > chapter_1_table_1$control) and nrow(chapter_1_table_1)
number of successes = 6, number of trials = 10, p-value = 0.7539
alternative hypothesis: true probability of success is not equal to 0.5
95 percent confidence interval:
 0.2623781 0.8784477
sample estimates:
probability of success 
                   0.6 

The estimate is .60 with a 95% interval of about .262 to .878—wide, as it must be with only ten pairs. The pp value binom.test() reports here is the sign test, and it is a useful contrast rather than a competitor: keeping only the signs and discarding the magnitudes throws away the information the randomization test used, which is why its pp value (about .75) is so much larger than the .039 above.

The same effect size in DMAR

DMAR’s probability_of_superiority_paired() reports the same quantity directly:

HideShow
probability_of_superiority_paired(x = chapter_1_table_1$control,
                                  y = chapter_1_table_1$treat,
                                  conf_level = 0.95)
term value
probability_of_superiority 0.600
ci_lower 0.297
ci_upper 0.842
var_ps 0.024
wins_y_over_x 6
losses_y_under_x 4
ties 0

Confidence level: 95%

The probability_of_superiority row is .600, agreeing exactly with the mean() count above—the agreement is the check that the two routes are computing the same thing. What the DMAR call adds is what the counting route leaves the reader to assemble by hand: the win/loss/tie breakdown (wins_y_over_x, losses_y_under_x, ties) and the variance of the estimate reported alongside the estimate, ties credited as half a win rather than silently dropped by a bare > comparison, and an interval—.297 to .842 here—built for this estimand on a transformed scale so that it cannot run outside 0 and 1. It is a large-sample interval and so differs from the exact binomial interval above; with ten pairs the two bracket .60 similarly and neither is narrow.

Correspondence with the paired tt test

The book notes that a paired tt-test, although it makes more assumptions, is a close approximation to the randomization test. R’s t.test() performs a one-sample, paired, or independent-samples tt-test depending on its arguments. A one-sample test on the 10 difference scores is equivalent to a paired test (the default null value is 0, changeable with mu =):

HideShow
t.test(chapter_1_table_1$Difference)
HideShow

    One Sample t-test

data:  chapter_1_table_1$Difference
t = 2.1386, df = 9, p-value = 0.06116
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 -0.2658294  9.4658294
sample estimates:
mean of x 
      4.6 

Equivalently, supply the two conditions and declare the design paired:

HideShow
t.test(chapter_1_table_1$treat, chapter_1_table_1$control, paired = TRUE)
HideShow

    Paired t-test

data:  chapter_1_table_1$treat and chapter_1_table_1$control
t = 2.1386, df = 9, p-value = 0.06116
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
 -0.2658294  9.4658294
sample estimates:
mean difference 
            4.6 

This gives t=2.14t = 2.14 on 9 degrees of freedom, with a two-tailed pp value of about .061. The book reports the matching one-tailed value, .031, which we obtain with the directional alternative:

HideShow
t.test(chapter_1_table_1$treat, chapter_1_table_1$control,
       paired = TRUE, alternative = "greater")
HideShow

    Paired t-test

data:  chapter_1_table_1$treat and chapter_1_table_1$control
t = 2.1386, df = 9, p-value = 0.03058
alternative hypothesis: true mean difference is greater than 0
95 percent confidence interval:
 0.6570313       Inf
sample estimates:
mean difference 
            4.6 
HideShow
#> t = 2.14 on 9 df, one-tailed p = .031; matches book p. 32

The one-tailed tt-test pp value, .031, is close to the .039 from the exact randomization test—the correspondence the book emphasizes. The book notes that the agreement is closer still once the tt test is corrected for the discontinuous nature of these data, at which point the two probabilities differ by about 1 in 1,000, and the two tests may be viewed as very close approximations to one another. Deciding to reject the null hypothesis of the randomization test is tantamount to rejecting the null hypothesis of the tt-test.

1.4.5 — Toward Tests Based on Distributional Assumptions

1.4.5.2 — The Assumption of Normality

Having derived the two tests above from first principles, the chapter turns to two classic data sets to make a foundational point concrete: although any single observation can be erratic, composite behavioral measurements tend to pile up in a roughly bell-shaped, approximately normal distribution. This near-normality is part of what motivates the normal-theory linear models developed throughout the book. The grouped frequencies behind the next two figures are read from the published figures and entered inline, since these historical raw data are not in the AMCP package.

Figure 1.3. Grouped frequency distribution of simple reaction times

Reaction time is a workhorse measure in experimental psychology. Although a single person’s reaction times over repeated trials are positively skewed, the distribution of average reaction times across people is very nearly normal. This figure shows that for the mean reaction times to sound of 1,000 Parisian machinist applicants (Fessard, 1926, as cited by Woodworth & Schlosberg, 1954), each measured over 30 trials, with a normal curve overlaid. Fessard excluded 35 extreme cases, leaving 965 (book p. 39). These historical raw data are not in the AMCP package, so the grouped frequencies below are read off the published figure’s bar heights and entered inline; they sum to 958 rather than 965, which is the accuracy of reading a printed histogram rather than a discrepancy with the book.

HideShow
# Grouped frequencies read from Figure 1.3 (Fessard, 1926). Bars are centered at
# 130, 140, ..., 210 ms (bin width 10 ms); 35 of the original 1,000 cases were
# excluded by Fessard as extreme.
rt <- data.frame(
  midpoint  = seq(130, 210, by = 10),
  frequency = c(27, 60, 125, 177, 202, 181, 105, 55, 26)
)

# A normal curve with the same total area as the histogram (n * bin width),
# using the mean and SD implied by the grouped data.
n_rt   <- sum(rt$frequency)
bin_rt <- 10
mean_rt <- with(rt, sum(midpoint * frequency) / n_rt)
sd_rt   <- with(rt, sqrt(sum(frequency * (midpoint - mean_rt)^2) / (n_rt - 1)))
curve_rt <- data.frame(x = seq(115, 225, length.out = 400))
curve_rt$y <- dnorm(curve_rt$x, mean_rt, sd_rt) * n_rt * bin_rt

ggplot(rt, aes(midpoint, frequency)) +
  geom_col(width = bin_rt, fill = "grey35",
           color = "white", alpha = 0.9) +
  geom_line(data = curve_rt, aes(x, y),
            color = "#0C2340", linewidth = 1) +
  scale_x_continuous(breaks = seq(130, 210, by = 10)) +
  labs(x = "Reaction time (in milliseconds)", y = "Frequency")
Figure 1.3. Grouped frequency distribution of simple reaction times.

Figure 1.3. Grouped frequency distribution of simple reaction times.

The average reaction times pile up symmetrically around roughly 170 ms and track the overlaid normal curve closely, the chapter’s first empirical illustration of approximate normality in a behavioral measure (book p. 39).

Figure 1.4. MMPI hypochondriasis scores

A second illustration of approximate normality comes from a personality scale. This figure shows the distribution of Hypochondriasis-scale TT scores for 699 Minnesotans who were not ill but accompanied relatives or friends to a hospital (McKinley & Hathaway, 1956, originally described in Hathaway & McKinley, 1940), again with a normal curve overlaid (book pp. 39–40). As with the reaction-time data, the composite nature of the score (a sum over many items) produces a roughly bell-shaped distribution. As for Figure 1.3, the frequencies below are read off the published figure’s bar heights and entered inline; they sum to 698 rather than the 699 the book reports.

HideShow
# Grouped frequencies read from Figure 1.4 (McKinley & Hathaway, 1956). Bars span
# T scores from about 20 to 80 in steps of 3.
mmpi <- data.frame(
  Tscore    = seq(20, 80, by = 3),
  frequency = c(1, 5, 5, 9, 20, 24, 46, 76, 65, 95, 98,
                63, 52, 50, 37, 18, 19, 7, 5, 2, 1)
)

# Normal curve scaled to the histogram's total area (n * bin width).
n_mm   <- sum(mmpi$frequency)
bin_mm <- 3
mean_mm <- with(mmpi, sum(Tscore * frequency) / n_mm)
sd_mm   <- with(mmpi, sqrt(sum(frequency * (Tscore - mean_mm)^2) / (n_mm - 1)))
curve_mm <- data.frame(x = seq(17, 83, length.out = 400))
curve_mm$y <- dnorm(curve_mm$x, mean_mm, sd_mm) * n_mm * bin_mm

ggplot(mmpi, aes(Tscore, frequency)) +
  geom_col(width = bin_mm, fill = "grey35",
           color = "white", alpha = 0.9) +
  geom_line(data = curve_mm, aes(x, y),
            color = "#0C2340", linewidth = 1) +
  scale_x_continuous(breaks = seq(20, 80, by = 6)) +
  labs(x = expression("MMPI hypochondriasis" ~ italic(T) ~ "score"), y = "Frequency")
Figure 1.4. MMPI hypochondriasis scores.

Figure 1.4. MMPI hypochondriasis scores.

The roughly 700 “Minnesota normals” produce a distribution centered near a TT score of 50 that, allowing for sampling variability, corresponds closely to the overlaid normal curve, reinforcing the chapter’s point that composite behavioral measurements are often approximately normal (book p. 40).

Summary

This chapter’s quantitative material builds two tests from first principles so that the pp value is something we derive, not merely look up:

  • Fisher’s exact test (§1.4.2), from counting rules—choose(), factorial(), combn(), and the hypergeometric dhyper()—and automated by fisher.test(), together with the phi-coefficient and odds-ratio effect sizes and the (advanced) power computation.
  • The randomization test (§1.4.3), from the 2n2^{n} equally likely sign patterns of the matched-pairs differences, with the probability of superiority—counted in base R and interval-estimated by DMAR—as its order-only effect size, and its close correspondence to the paired t.test().

These ideas—deriving a reference distribution from the design itself, and the close agreement between randomization and normal-theory tests—motivate the normal-theory linear models developed in the chapters that follow.

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 1: The Logic of Experimental Design and Analysis (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

Chapter 2: Drawing Valid Inferences from Experiments

Open the separate reading

Code
Results
On this page

Chapter 1 covers the R groundwork these notes take for granted: installing packages from CRAN, loading them, and the way the book’s data sets are named. Chapter 2 is conceptual: it carries no numerical worked example, and AMCP ships no chapter_2_table_* data for it, so everything below is computed from scratch rather than read out of a data set.

HideShow
# Load all of the packages used.
library(tidyverse)      # data wrangling and plotting (dplyr, tidyr, ggplot2, and friends)
library(pwr)            # power analysis for common designs
library(DMAR)           # design, measurement, and analysis

What this companion covers

Chapter 2 is conceptual. It distinguishes the four types of validity — statistical conclusion, internal, construct, and external (Section 2.3.1, p. 54) — surveys the threats to each, sets out a general strategy for conceptualizing and controlling those threats (Section 2.3.6, p. 62), previews the designs developed in the rest of the book (Section 2.4, p. 64), and closes on the growth of experimentation, online experiments included (Section 2.5, p. 68). There is no data set to analyze and no printed table of results to reproduce.

Two kinds of chapter content do carry over into R, and they are what this page contains:

  • The quantitative claims behind Section 2.3.2. The chapter argues that low power is the most pervasive threat to statistical conclusion validity, that too-small samples and unreliable dependent variables are its leading causes, and that inflated Type I error rates come primarily from testing the same general hypothesis repeatedly (pp. 56–57, summarized in Table 2.1, p. 57). Each of those claims can be made quantitative in a few lines of base R.
  • The chapter’s design schematics. Figures 2.1–2.4 (pp. 62–64) recast threats to validity as missing cells of a larger factorial design, and Figures 2.5–2.7 (pp. 66–68) introduce the design vocabulary — one-way versus two-way, crossed versus nested, between-subjects versus within-subjects — that organizes the remaining chapters. All seven are drawn below in ggplot2, cell for cell as printed.

The numbers this page reports are computed here, not copied from the chapter: Chapter 2 prints none. Every page citation points at the sentence, table, or figure in the book that the code is making concrete.

2.3 — Threats to the Validity of Inferences from Experiments

2.3.2 — Statistical Conclusion Validity

Statistical conclusion validity asks whether the original statistical inference was correct (p. 55). Because the Type I error rate α\alpha is fixed by convention within a discipline, the chapter identifies power — the probability of rejecting a false null hypothesis, equal to 1−Pr⁡(Type II error)1 - \Pr(\text{Type II error}) — as the critical issue, and low power as the most pervasive threat to it (p. 56).

Power as a function of per-group nn (base R)

The chapter’s first stated cause of low power is that sample sizes are too small for the situation, and it notes that increasing the number of participants is conceptually the simplest remedy (p. 56). power.t.test(), in base R’s stats package, makes that trade-off explicit for the two-independent-groups case. We tabulate power against per-group nn at three illustrative population standardized mean differences, δ=0.2,0.5,0.8\delta = 0.2, 0.5, 0.8. The common population standard deviation is 1 here, so each mean difference entered in power.t.test() equals its standardized value.

HideShow
power_grid <- expand_grid(
  delta = c(0.2, 0.5, 0.8),
  n     = seq(10, 400, by = 10)
) |>
  mutate(
    power = power.t.test(
      n = n, delta = delta, sd = 1, sig.level = 0.05,
      type = "two.sample", alternative = "two.sided",
      strict = TRUE  # count rejections in both tails
    )$power
  )

power_grid
HideShow
# A tibble: 120 × 3
   delta     n  power
   <dbl> <dbl>  <dbl>
 1   0.2    10 0.0708
 2   0.2    20 0.0946
 3   0.2    30 0.119 
 4   0.2    40 0.143 
 5   0.2    50 0.168 
 6   0.2    60 0.192 
 7   0.2    70 0.217 
 8   0.2    80 0.242 
 9   0.2    90 0.266 
10   0.2   100 0.291 
# ℹ 110 more rows
HideShow
ggplot(power_grid, aes(x = n, y = power, color = factor(delta))) +
  geom_hline(yintercept = c(0.80, 0.95), linetype = "dotted",
             color = "#0C2340") +
  geom_line(linewidth = 0.9) +
  scale_color_discrete(
    breaks = c("0.2", "0.5", "0.8"),
    labels = expression(italic("δ") == 0.2, italic("δ") == 0.5, italic("δ") == 0.8)
  ) +
  scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, by = 0.1)) +
  labs(
    x     = expression("Sample size per group," ~ italic(n)),
    y     = "Power",
    color = NULL
  )
Power of the two-sample \(t\) test as a function of per-group \(n\) at three population standardized mean differences (two-sided, \(\alpha = .05\)). Dotted lines mark 80% and 95% power.

Power of the two-sample tt test as a function of per-group nn at three population standardized mean differences (two-sided, α=.05\alpha = .05). Dotted lines mark 80% and 95% power.

For 80% power, δ=0.8\delta = 0.8 requires 26 participants per group, whereas δ=0.2\delta = 0.2 requires 394.

The same answer from pwr, and from DMAR

Solving the same equation for nn instead of for power is the sample-size question. Base R and the pwr package answer it identically; the agreement is worth seeing, because it means nothing in the result depends on which package a reader reaches for.

HideShow
base_n <- power.t.test(
  delta       = 0.5,
  sd          = 1,
  power       = 0.80,
  sig.level   = 0.05,
  type        = "two.sample",
  alternative = "two.sided",
  strict      = TRUE
)$n

pwr_n <- pwr.t.test(
  d           = 0.5,  # pwr calls the assumed population effect d
  power       = 0.80,
  sig.level   = 0.05,
  type        = "two.sample",
  alternative = "two.sided"
)$n

c(power.t.test = base_n, pwr.t.test = pwr_n)
HideShow
power.t.test   pwr.t.test 
    63.76561     63.76561 
HideShow
#> 63.77 from both routes: base R and pwr agree to five significant digits.

Neither call above rounds its answer to a whole number of participants, or says what power that whole number buys. ss_power_smd() in DMAR reports both — the requirement rounded up, and the power actually achieved there, which is never exactly the power requested — along with the noncentrality parameter that generated them. Note the argument name: the planner takes true_smd, the assumed population standardized mean difference, rather than an estimate from data.

HideShow
ss_power_smd(
  true_smd      = 0.50,
  desired_power = 0.80,
  alpha_level   = 0.05,
  directional   = FALSE
)
term value
necessary_n_per_group 64
actual_power 0.801
noncentral_t_parm 2.828
true_smd 0.500
desired_power 0.800
alpha_level 0.050
tails 2
HideShow
#> necessary_n_per_group = 64, the ceiling of the 63.77 above, and
#> actual_power = 0.801 at that n rather than the 0.800 requested.
Required nn for 80% and 95% power

Collecting the base-R answers across the three benchmark effect sizes shows how steeply the requirement grows as the anticipated effect shrinks.

HideShow
n_needed <- function(delta, target_power) {
  power.t.test(
    delta       = delta,
    sd          = 1,
    power       = target_power,
    sig.level   = 0.05,
    type        = "two.sample",
    alternative = "two.sided",
    strict      = TRUE
  )$n
}

tibble(delta = c(0.2, 0.5, 0.8)) |>
  mutate(
    n_for_80 = vapply(delta, n_needed, numeric(1), target_power = 0.80),
    n_for_95 = vapply(delta, n_needed, numeric(1), target_power = 0.95)
  )
HideShow
# A tibble: 3 × 3
  delta n_for_80 n_for_95
  <dbl>    <dbl>    <dbl>
1   0.2    393.     651. 
2   0.5     63.8    105. 
3   0.8     25.5     41.6
HideShow
#> 393 / 63.8 / 25.5 per group for 80% power; 651 / 105 / 41.6 for 95%.
#> Dividing the population effect by four calls for about sixteen times as many participants.
Confirming the power curve by simulation

The analytic power above is not an approximation, but simulating the test it describes is a useful check on what “power” means operationally: it is the proportion of samples in which the test rejects. We draw samples under a true δ=0.5\delta = 0.5 and count rejections.

HideShow
set.seed(113)
n_replicates <- 2000

simulate_power <- function(n_per_group, true_smd) {
  rejects <- vapply(seq_len(n_replicates), function(i) {
    x <- rnorm(n_per_group, mean = 0,        sd = 1)
    y <- rnorm(n_per_group, mean = true_smd, sd = 1)
    t.test(x, y,
      alternative = "two.sided",
      var.equal   = TRUE,
      conf.level  = 0.95
    )$p.value < 0.05
  }, logical(1))
  mean(rejects)
}

tibble(n = c(10, 30, 50, 100, 200)) |>
  mutate(
    empirical_power  = vapply(n, simulate_power, numeric(1), true_smd = 0.5),
    analytic_power   = vapply(n, function(k) {
      power.t.test(
        n = k, delta = 0.5, sd = 1, sig.level = 0.05,
        type = "two.sample", alternative = "two.sided", strict = TRUE
      )$power
    }, numeric(1)),
    type2_error_rate = 1 - analytic_power
  )
HideShow
# A tibble: 5 × 4
      n empirical_power analytic_power type2_error_rate
  <dbl>           <dbl>          <dbl>            <dbl>
1    10           0.190          0.185          0.815  
2    30           0.488          0.478          0.522  
3    50           0.692          0.697          0.303  
4   100           0.937          0.940          0.0596 
5   200           0.998          0.999          0.00123
HideShow
#> Simulated and analytic power agree to within Monte Carlo error at every n,
#> and the Type II error rate falls as n grows — the point made on p. 56.

set.seed(113) is the seed used throughout these notes, so the figures above reproduce exactly on re-render; n_replicates is set in this chunk and reused by the simulation further down.

Why an unreliable dependent variable costs power

The chapter’s second stated cause of low power is an unreliable dependent variable, and its stated remedy is to lengthen the test, because longer tests are more reliable (pp. 56–57; the pairing appears in Table 2.1, p. 57). Both halves of that argument are short formulas, so the cost of unreliability can be read off directly in base R.

Lengthening a test by a factor kk changes its reliability by the Spearman–Brown relation. If δ\delta is the effect standardized by the true-score standard deviation, the population effect on the fallible measure is δρYY′\delta\sqrt{\rho_{YY'}}. The example uses δ=0.5\delta = 0.5 and a short-form reliability of 0.50.

HideShow
true_smd <- 0.50
rel_one_form <- 0.50

tibble(test_length_factor = c(1, 2, 4, 8)) |>
  mutate(
    reliability    = (test_length_factor * rel_one_form) /
                    (1 + (test_length_factor - 1) * rel_one_form),
    fallible_delta = true_smd * sqrt(reliability),
    n_for_80       = vapply(fallible_delta, n_needed, numeric(1),
                           target_power = 0.80)
  )
HideShow
# A tibble: 4 × 4
  test_length_factor reliability fallible_delta n_for_80
               <dbl>       <dbl>          <dbl>    <dbl>
1                  1       0.5            0.354    127. 
2                  2       0.667          0.408     95.2
3                  4       0.8            0.447     79.5
4                  8       0.889          0.471     71.6
HideShow
#> Reliability 0.50 attenuates the population effect from 0.50 to 0.354 and pushes the requirement to
#> 127 per group for 80% power; quadrupling test length raises reliability to
#> 0.80, raises that effect to 0.447, and brings the requirement down to 79.5.

The table makes the chapter’s caveat visible too: the returns diminish. Going from one form to two saves about 31 participants per group; going from four forms to eight saves fewer than 8 more. That is why the chapter frames lengthening the posttest and adding a pretest as complementary strategies whose relative value depends on how reliable the measure already is (p. 57).

Why repeated tests inflate the Type I error rate

Turning from conservative to liberal bias: the chapter identifies the primary cause of Type I error rates above the nominal level as the investigator having performed multiple tests of the same general hypothesis, and points to adjusted test procedures as the remedy (p. 57, and the first row of the liberal-bias half of Table 2.1, p. 57). With kk independent tests each at α=.05\alpha = .05, the probability that at least one is significant when every null is true is 1−(1−α)k1 - (1 - \alpha)^{k} — a one-line calculation in base R, which we then confirm by simulation and repair with p.adjust().

HideShow
set.seed(113)

one_family <- function(n_tests, n_per_group = 30) {
  p_values <- vapply(seq_len(n_tests), function(j) {
    x <- rnorm(n_per_group, mean = 0, sd = 1)
    y <- rnorm(n_per_group, mean = 0, sd = 1)
    t.test(x, y,
      alternative = "two.sided",
      var.equal   = TRUE,
      conf.level  = 0.95
    )$p.value
  }, numeric(1))
  c(
    unadjusted = any(p_values < 0.05),
    holm       = any(p.adjust(p_values, method = "holm") < 0.05)
  )
}

bind_rows(lapply(c(1, 3, 5, 10), function(k) {
  hits <- vapply(seq_len(n_replicates), function(i) one_family(k), logical(2))
  tibble(
    tests_per_family     = k,
    analytic_unadjusted  = 1 - (1 - 0.05)^k,
    empirical_unadjusted = mean(hits["unadjusted", ]),
    empirical_holm       = mean(hits["holm", ])
  )
}))
HideShow
# A tibble: 4 × 4
  tests_per_family analytic_unadjusted empirical_unadjusted empirical_holm
             <dbl>               <dbl>                <dbl>          <dbl>
1                1              0.0500                0.049         0.049 
2                3              0.143                 0.136         0.0475
3                5              0.226                 0.226         0.044 
4               10              0.401                 0.407         0.0555
HideShow
#> With every null true, the unadjusted familywise error rate climbs from .05
#> at one test toward .40 at ten, tracking 1 - (1 - .05)^k; Holm's adjustment
#> holds the familywise rate at about .05 throughout.

Holm’s procedure is used here because it is available in base R through p.adjust() and controls the familywise rate without assuming independence. The multiple-comparison procedures the book develops for the comparisons that actually arise in a one-way design — Tukey, Dunnett, Scheffé, and the rest — are the subject of Chapter 5, and appear in that chapter’s companion page rather than here.

2.3.6 — Conceptualizing and Controlling for Threats to Validity

Section 2.3.6 makes the organizing point of the chapter: most of the artifacts surveyed above can be thought of as incomplete designs, or as designs with more factors than were originally planned (p. 62). A two-group study in which selection bias operates is really two of the four cells of a treatment × population design; a two-group study whose treatment arrives with incidental features the control condition lacks — the vehicle that delivers the treatment — is really two of the four cells of a treatment × vehicle design. Figures 2.1 through 2.4 draw those designs. Each is a small grid, so each is a geom_tile() plot.

Figure 2.1 — the confounded two-group design

In the book’s Figure 2.1 (p. 62) all four cells of the 2 × 2 are drawn, and two of them are annotated as not included in the design. The two that are used pair treatment-present with vehicle-present and treatment-absent with vehicle-absent, which is exactly why a treatment effect and a vehicle effect cannot be told apart.

HideShow
two_by_two_cells <- function(included) {
  expand_grid(
    treatment = c("Present", "Absent"),
    vehicle   = c("Present", "Absent")
  ) |>
    mutate(in_design = paste(treatment, vehicle) %in% included) |>
    mutate(
      treatment = factor(treatment, levels = c("Absent", "Present")),
      vehicle   = factor(vehicle,   levels = c("Present", "Absent"))
    )
}

figure_2_1 <- two_by_two_cells(
  included = c("Present Present", "Absent Absent")
)
figure_2_1
HideShow
# A tibble: 4 × 3
  treatment vehicle in_design
  <fct>     <fct>   <lgl>    
1 Present   Present TRUE     
2 Present   Absent  FALSE    
3 Absent    Present FALSE    
4 Absent    Absent  TRUE     
HideShow
#> Present/Present and Absent/Absent in the design; Absent/Present and
#> Present/Absent marked "Not included in design" — matches Figure 2.1, p. 62.

ggplot(figure_2_1, aes(x = vehicle, y = treatment, fill = in_design)) +
  geom_tile(color = "black", linewidth = 0.6) +
  geom_text(
    data = \(d) filter(d, !in_design),
    aes(label = "Not included\nin design"),
    color = "black", size = 3.6
  ) +
  scale_fill_manual(
    values = c(`TRUE` = "#0C2340", `FALSE` = "white"),
    guide  = "none"
  ) +
  scale_x_discrete(expand = expansion(0), position = "top") +
  scale_y_discrete(expand = expansion(0)) +
  labs(x = "Vehicle (instrumental incidentals)", y = "\"Pure\" treatment")
Figure 2.1 (book p. 62): a two-group study seen as two cells of a 2 × 2 'pure' treatment × vehicle design. Shaded cells are in the design.

Figure 2.1 (book p. 62): a two-group study seen as two cells of a 2 × 2 ‘pure’ treatment × vehicle design. Shaded cells are in the design.

Figure 2.2 — the two preferred designs

The repair is to make the two groups differ along one dimension only. Either the control group is expanded to include the incidental features that had been unique to the experimental group — the sham-surgery control the chapter describes — or the experimental group is purified by stripping those features out (p. 63). Panel (a) of Figure 2.2 therefore holds the vehicle present in both groups; panel (b) holds it absent in both.

HideShow
figure_2_2 <- bind_rows(
  expand_grid(
    panel     = "(a) Expanded control group",
    treatment = c("Present", "Absent"),
    vehicle   = "Present"
  ) |>
    mutate(label = if_else(treatment == "Absent",
                           "Expanded\ncontrol group", "")),
  expand_grid(
    panel     = "(b) Purified experimental group",
    treatment = c("Present", "Absent"),
    vehicle   = "Absent"
  ) |>
    mutate(label = if_else(treatment == "Present",
                           "Purified\nexperimental group", ""))
) |>
  mutate(treatment = factor(treatment, levels = c("Absent", "Present")))
figure_2_2
HideShow
# A tibble: 4 × 4
  panel                           treatment vehicle label                       
  <chr>                           <fct>     <chr>   <chr>                       
1 (a) Expanded control group      Present   Present ""                          
2 (a) Expanded control group      Absent    Present "Expanded\ncontrol group"   
3 (b) Purified experimental group Present   Absent  "Purified\nexperimental gro…
4 (b) Purified experimental group Absent    Absent  ""                          
HideShow
#> One column per panel: vehicle Present in (a), Absent in (b), each with both
#> levels of treatment — matches Figure 2.2, p. 63.

ggplot(figure_2_2, aes(x = vehicle, y = treatment)) +
  geom_tile(fill = "#0C2340", color = "black", linewidth = 0.6) +
  geom_text(aes(label = label), color = "white", size = 3.4) +
  facet_wrap(~ panel, scales = "free_x") +
  scale_x_discrete(expand = expansion(0), position = "top") +
  scale_y_discrete(expand = expansion(0)) +
  labs(x = "Vehicle (instrumental incidentals)", y = "\"Pure\" treatment")
Figure 2.2 (book p. 63): the two preferred designs. (a) holds the vehicle present in both conditions; (b) holds it absent in both. In each panel the two groups differ only in the treatment.

Figure 2.2 (book p. 63): the two preferred designs. (a) holds the vehicle present in both conditions; (b) holds it absent in both. In each panel the two groups differ only in the treatment.

Figures 2.3 and 2.4 — expanding across subpopulations

The same move in the other direction serves generality rather than identifiability. A two-group study run in one subpopulation (Figure 2.3, p. 63) becomes a crossed design when a second subpopulation of interest is added (Figure 2.4, p. 64), and the treatment effect can then be examined in both.

HideShow
figure_2_3_2_4 <- bind_rows(
  expand_grid(
    panel         = "Figure 2.3 — Original design",
    condition     = c("Treatment", "Control"),
    subpopulation = "A"
  ),
  expand_grid(
    panel         = "Figure 2.4 — Expanded design",
    condition     = c("Treatment", "Control"),
    subpopulation = c("A", "B")
  )
) |>
  mutate(condition = factor(condition, levels = c("Control", "Treatment")))
figure_2_3_2_4
HideShow
# A tibble: 6 × 3
  panel                        condition subpopulation
  <chr>                        <fct>     <chr>        
1 Figure 2.3 — Original design Treatment A            
2 Figure 2.3 — Original design Control   A            
3 Figure 2.4 — Expanded design Treatment A            
4 Figure 2.4 — Expanded design Treatment B            
5 Figure 2.4 — Expanded design Control   A            
6 Figure 2.4 — Expanded design Control   B            
HideShow
#> Subpopulation A only in Figure 2.3; A and B in Figure 2.4, both crossed with
#> Treatment and Control — matches pp. 63--64.

ggplot(figure_2_3_2_4, aes(x = subpopulation, y = condition)) +
  geom_tile(fill = "#0C2340", color = "black", linewidth = 0.6) +
  facet_wrap(~ panel, scales = "free_x") +
  scale_x_discrete(expand = expansion(0), position = "top") +
  scale_y_discrete(expand = expansion(0)) +
  labs(x = "Subpopulation", y = "Condition")
Figures 2.3 and 2.4 (book pp. 63--64): a two-group study in a single subpopulation, and the expanded design that crosses condition with subpopulation.

Figures 2.3 and 2.4 (book pp. 63–64): a two-group study in a single subpopulation, and the expanded design that crosses condition with subpopulation.

2.4 — Overview of Experimental Designs To Be Considered

Section 2.4 introduces the distinctions that structure the rest of the book: how many factors a design has, how the levels of different factors are combined, whether the levels were chosen for their own sake or sampled, and whether each subject experiences one condition or several (pp. 64–68). The schematics in Figures 2.5 through 2.7 are the vocabulary for all of it, drawn here with the book’s own example labels.

Figure 2.5 — one-way and two-way designs

The book’s one-way example is three instructional conditions — classroom instruction, a self-study manual, and a no-treatment control — and its two-way example adds a breakdown of participants by gender, which it notes typically increases power to detect the treatment effect while also allowing a check on whether the effect is consistent across subgroups (p. 66).

HideShow
instruction <- c("Classroom", "Self-Study", "Control")

figure_2_5 <- bind_rows(
  tibble(panel = "One-Way Design", condition = instruction, row = ""),
  expand_grid(
    panel     = "Two-Way Design",
    condition = instruction,
    row       = c("Males", "Females")
  )
) |>
  mutate(
    panel     = factor(panel, levels = c("One-Way Design", "Two-Way Design")),
    condition = factor(condition, levels = instruction),
    row       = factor(row, levels = c("Females", "Males", ""))
  )
figure_2_5
HideShow
# A tibble: 9 × 3
  panel          condition  row      
  <fct>          <fct>      <fct>    
1 One-Way Design Classroom  ""       
2 One-Way Design Self-Study ""       
3 One-Way Design Control    ""       
4 Two-Way Design Classroom  "Males"  
5 Two-Way Design Classroom  "Females"
6 Two-Way Design Self-Study "Males"  
7 Two-Way Design Self-Study "Females"
8 Two-Way Design Control    "Males"  
9 Two-Way Design Control    "Females"
HideShow
#> One row of three cells for the one-way design; Males above Females crossed
#> with the same three columns for the two-way — matches Figure 2.5, p. 66.

ggplot(figure_2_5, aes(x = condition, y = row)) +
  geom_tile(fill = "white", color = "black", linewidth = 0.6) +
  facet_wrap(~ panel, ncol = 1, scales = "free_y") +
  scale_x_discrete(expand = expansion(0), position = "top") +
  scale_y_discrete(expand = expansion(0)) +
  labs(x = NULL, y = NULL)
Figure 2.5 (book p. 66): schematic diagrams of a one-way design (three instructional conditions) and a two-way design (the same three conditions crossed with gender).

Figure 2.5 (book p. 66): schematic diagrams of a one-way design (three instructional conditions) and a two-way design (the same three conditions crossed with gender).

Figure 2.6 — crossed and nested designs

Crossing and nesting differ in which combinations of levels occur. In the book’s example, four therapists deliver Rogerian and Behavior Analytic therapy; if every therapist uses both methods, therapists are crossed with method, and if each is qualified for only one, therapists are nested within method (pp. 66–67). The book marks the absent combinations of the nested design with the word missing, and so do we.

HideShow
methods     <- c("Rogerian", "Behavior Analytic")
therapists  <- paste("Therapist", 1:4)

rogerian_only <- paste("Therapist", 1:2)

figure_2_6 <- bind_rows(
  expand_grid(panel = "Crossed Design", therapist = therapists,
              method = methods) |>
    mutate(present = TRUE),
  expand_grid(panel = "Nested Design", therapist = therapists,
              method = methods) |>
    mutate(present = if_else(
      therapist %in% rogerian_only,
      method == "Rogerian",
      method == "Behavior Analytic"
    ))
) |>
  mutate(
    panel     = factor(panel, levels = c("Crossed Design", "Nested Design")),
    method    = factor(method, levels = methods),
    therapist = factor(therapist, levels = rev(therapists))
  )

figure_2_6 |> filter(panel == "Nested Design")
HideShow
# A tibble: 8 × 4
  panel         therapist   method            present
  <fct>         <fct>       <fct>             <lgl>  
1 Nested Design Therapist 1 Rogerian          TRUE   
2 Nested Design Therapist 1 Behavior Analytic FALSE  
3 Nested Design Therapist 2 Rogerian          TRUE   
4 Nested Design Therapist 2 Behavior Analytic FALSE  
5 Nested Design Therapist 3 Rogerian          FALSE  
6 Nested Design Therapist 3 Behavior Analytic TRUE   
7 Nested Design Therapist 4 Rogerian          FALSE  
8 Nested Design Therapist 4 Behavior Analytic TRUE   
HideShow
#> Therapists 1 and 2 under Rogerian, Therapists 3 and 4 under Behavior
#> Analytic, the other four cells "missing" — matches Figure 2.6, p. 67.

ggplot(figure_2_6, aes(x = method, y = therapist, fill = present)) +
  geom_tile(color = "black", linewidth = 0.6) +
  geom_text(
    data = \(d) filter(d, !present),
    aes(label = "missing"), color = "black", size = 3.4
  ) +
  scale_fill_manual(
    values = c(`TRUE` = "#0C2340", `FALSE` = "white"),
    guide  = "none"
  ) +
  facet_wrap(~ panel, ncol = 1) +
  scale_x_discrete(expand = expansion(0), position = "top") +
  scale_y_discrete(expand = expansion(0)) +
  labs(x = "Therapy method", y = NULL)
Figure 2.6 (book p. 67): diagrams of crossed and nested designs. In the nested design each therapist delivers only one of the two methods.

Figure 2.6 (book p. 67): diagrams of crossed and nested designs. In the nested design each therapist delivers only one of the two methods.

Figure 2.7 — between-subjects and within-subjects designs

The chapter calls this perhaps the most important distinction among designs: whether each subject experiences one condition or several (p. 67). Figure 2.7 shows it with fifteen subjects spread one-to-a-condition across three conditions, against five subjects who each appear in all three.

HideShow
conditions <- paste("Condition", 1:3)

figure_2_7 <- bind_rows(
  expand_grid(panel = "Between-subjects design",
              condition = conditions, slot = 1:5) |>
    mutate(subject = paste0("S", (match(condition, conditions) - 1) * 5 + slot)),
  expand_grid(panel = "Within-subjects design",
              condition = conditions, slot = 1:5) |>
    mutate(subject = paste0("S", slot))
) |>
  mutate(
    panel     = factor(panel, levels = c("Between-subjects design",
                                         "Within-subjects design")),
    condition = factor(condition, levels = conditions),
    slot      = factor(slot, levels = 5:1)
  )

figure_2_7 |> filter(panel == "Between-subjects design")
HideShow
# A tibble: 15 × 4
   panel                   condition   slot  subject
   <fct>                   <fct>       <fct> <chr>  
 1 Between-subjects design Condition 1 1     S1     
 2 Between-subjects design Condition 1 2     S2     
 3 Between-subjects design Condition 1 3     S3     
 4 Between-subjects design Condition 1 4     S4     
 5 Between-subjects design Condition 1 5     S5     
 6 Between-subjects design Condition 2 1     S6     
 7 Between-subjects design Condition 2 2     S7     
 8 Between-subjects design Condition 2 3     S8     
 9 Between-subjects design Condition 2 4     S9     
10 Between-subjects design Condition 2 5     S10    
11 Between-subjects design Condition 3 1     S11    
12 Between-subjects design Condition 3 2     S12    
13 Between-subjects design Condition 3 3     S13    
14 Between-subjects design Condition 3 4     S14    
15 Between-subjects design Condition 3 5     S15    
HideShow
#> S1-S5 in Condition 1, S6-S10 in Condition 2, S11-S15 in Condition 3, against
#> S1-S5 in every condition in the within-subjects panel — matches Figure 2.7,
#> p. 68.

ggplot(figure_2_7, aes(x = condition, y = slot)) +
  geom_tile(fill = "white", color = "black", linewidth = 0.6) +
  geom_text(aes(label = sub("S([0-9]+)", "plain(S)[\\1]", subject)),
            parse = TRUE, color = "#0C2340", size = 3.6) +
  facet_wrap(~ panel, ncol = 1) +
  scale_x_discrete(expand = expansion(0), position = "top") +
  scale_y_discrete(expand = expansion(0), breaks = NULL) +
  labs(x = NULL, y = NULL)
Figure 2.7 (book p. 68): a between-subjects design, in which fifteen subjects each appear in one of three conditions, and a within-subjects design, in which five subjects each appear in all three.

Figure 2.7 (book p. 68): a between-subjects design, in which fifteen subjects each appear in one of three conditions, and a within-subjects design, in which five subjects each appear in all three.

The division of labor these three figures set up is the book’s own table of contents: between-subjects designs in Chapters 3 through 10, within-subjects and correlated-data designs in Chapters 11 through 16 (p. 68).

2.5 — The New Experimental Revolution

Section 2.5 documents how much more common experimentation has become, and devotes its closing pages to online controlled experiments — A/B tests — whose defining feature is an enormous supply of participants and, usually, a very small effect to detect (pp. 68–70). The chapter is explicit that the principles are the same as for traditional experiments while some of the implications differ, and that power analysis and sample-size planning are among the points of emphasis the rest of the book develops (p. 70).

The sample-size arithmetic shows why the scale is what it is. Suppose a conversion rate of 5.0% and a lift worth detecting of one-tenth of a percentage point. Base R’s power.prop.test() and pwr’s pwr.2p.test() — the latter working on the arcsine-transformed difference — give the per-arm requirement.

HideShow
base_arm <- power.prop.test(
  p1          = 0.050,
  p2          = 0.051,
  power       = 0.80,
  sig.level   = 0.05,
  alternative = "two.sided"
)$n

pwr_arm <- pwr.2p.test(
  h           = ES.h(p1 = 0.051, p2 = 0.050),
  power       = 0.80,
  sig.level   = 0.05,
  alternative = "two.sided"
)$n

c(power.prop.test = base_arm, pwr.2p.test = pwr_arm)
HideShow
power.prop.test     pwr.2p.test 
       752702.5        752684.0 
HideShow
#> About 753,000 per arm, 1.5 million in all, for a tenth-of-a-point lift.
#> The two routes differ by 0.002%, well inside any planning tolerance.

A requirement of that size is the reason the book reports, from the online experimentation literature it reviews, that detecting a swing of ten million dollars in annual revenue at 80% power could call for 18.4 billion participants — more than twice the human population (p. 70). We do not reproduce that figure here, because the assumptions behind it belong to the study the chapter is citing rather than to the chapter itself, but the arithmetic is of exactly this kind.

At the other end of the scale the approximation is less comfortable. It is dependable at the sample sizes above, but in a small pilot the discreteness of the binomial starts to matter. For the same two-proportion comparison, power_fisher_exact() in DMAR reports the power Fisher’s exact test actually has at a given pair of group sizes.

HideShow
power_fisher_exact(
  n_1         = 200,
  n_2         = 200,
  p_1         = 0.050,
  p_2         = 0.100,
  alpha_level = 0.05,
  alternative = "two_sided"
)
term value
power 0.472
odds_ratio_alt 0.474
p_1 0.050
p_2 0.100
expected_s 30
n_1 200
n_2 200
alpha_level 0.050
HideShow
power.prop.test(
  n           = 200,
  p1          = 0.050,
  p2          = 0.100,
  sig.level   = 0.05,
  alternative = "two.sided"
)$power
HideShow
[1] 0.4753103
HideShow
#> Exact power 0.472 against the approximation's 0.475: the same conclusion
#> about an underpowered pilot, with the exact test slightly more conservative.

Readers who want the relationship between traditional and online experiments developed at length are pointed by the chapter to its own references on the subject (p. 70).

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 2: Drawing Valid Inferences from Experiments (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

Chapter 3: Introduction to Model Comparisons: One-Way Between-Subjects Designs

Open the separate reading

Code
Results
On this page

Chapter 1 covers the R groundwork these notes take for granted: installing packages from CRAN, loading them, and the way the book’s data sets are named. This chapter draws on three of them — chapter_3_table_1, chapter_3_table_3, and chapter_3_table_7_raw, the last holding the raw scores behind a table the book presents in summary form. data(package = "AMCP") lists every data set in the package.

HideShow
# Load all of the packages used.
library(AMCP)           # the textbook's data sets
library(ggplot2)        # the grammar of graphics used for the book's data figures
library(dplyr)          # data manipulation
library(DMAR)           # design, measurement, and analysis
library(car)            # leveneTest() and Anova() for Type II/III tests
library(moments)        # skewness and kurtosis
library(psych)          # many functions for descriptive statistics and psychometrics
library(pwr)            # power analysis for common designs
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables
library(sjPlot)         # tab_model(): mixed-model tables, including the ICC

3.5 — One-Group Situation

3.5.3 — Numerical Example

The chapter’s one-group numerical example is the WISC-R IQ data for six hyperactive children in Table 3.1 (p. 88), tested against a null value of 98. We begin with the descriptive statistics, then work the model comparison the table lays out.

Descriptive statistics in base R

Load Chapter 3, Table 1 with the following command (AMCP was loaded with the other packages above).

HideShow
data(chapter_3_table_1)

One could call upon the summary statistics of interest individually, as we do below. Note that chapter_3_table_1 is a data frame, which typically means there is more than a single variable (as above). Because of the more flexible nature of a data frame, we need to identify the variable of interest for which we want to take the summary statistics. This seems unnecessary here, but consider the more general case of multiple variables, where identifying the variable of interest is important. The functions below are commonly used functions for describing data. There are many others that can be used. For information on any of the function uses, use the ?function.name or help("") or help.search("topic of interest")

HideShow
mean(chapter_3_table_1$IQ)
HideShow
[1] 104
HideShow
median(chapter_3_table_1$IQ)
HideShow
[1] 104
HideShow
quantile(chapter_3_table_1$IQ, probs=c(.05, .25, .5, .75, .95))
HideShow
   5%   25%   50%   75%   95% 
 97.5 102.5 104.0 107.0 109.5 
HideShow
sd(chapter_3_table_1$IQ)
HideShow
[1] 4.898979
HideShow
length(chapter_3_table_1$IQ)
HideShow
[1] 6

Let’s summarize Table 3.1a in the book. Note that in the code below, MARGIN=2 indicates that margin totals across the columns are taken (MARGIN=1 would be the margin totals across rows).

HideShow
Table_3_1a <- cbind(Y=chapter_3_table_1$IQ, Parameter.Term=rep(104,
  length(chapter_3_table_1$IQ)), Error_Scores=chapter_3_table_1$IQ-104,
  Squared_Term=(chapter_3_table_1$IQ-104)^2)

# From the table, take a sum of all but the second column ("-2" ignores the second column).
apply(Table_3_1a[,-2], MARGIN=2, FUN=sum)
HideShow
           Y Error_Scores Squared_Term 
         624            0          120 
Descriptive statistics with dplyr

The same sum of squared deviations comes out of a single call to summarize() from the dplyr package: each argument names a quantity and the expression that produces it, so the whole summary is one statement rather than several.

The %>% below is a pipe. It feeds the value on its left into the function on its right as that function’s first argument, so chapter_3_table_1 %>% summarize(...) reads in the order the work is done: start with these data, then summarize them. Base R has since gained a native pipe, |>, which behaves the same way in the uses that appear on these pages.

HideShow
chapter_3_table_1 %>%
  summarize(Sum_Y = sum(IQ),
            n = n(),
            Sum_Squared_Errors = sum((IQ-104)^2))
HideShow
  Sum_Y n Sum_Squared_Errors
1   624 6                120
The model comparison and the FF test

Here we find FF as done in Table 3.1.

HideShow
Values <- chapter_3_table_1 %>%
  summarize(Error_F = sum((IQ-mean(IQ))^2),
            df_F = n()-1,
            Error_R = sum((IQ-98)^2),
            df_R = n(),
            F = ((Error_R - Error_F)/(df_R - df_F))/(Error_F/df_F))

# Print the whole row, then the F column. (A bare `F` would print the built-in
# constant FALSE, since R reads `F` as an abbreviation for FALSE; we want the
# column we just computed.)
Values
HideShow
  Error_F df_F Error_R df_R F
1     120    5     336    6 9
HideShow
Values$F
HideShow
[1] 9
HideShow
#> matches book p. 88 (Table 3.1): E_F = 120, E_R = 336, F = 216/24 = 9

Linear models, as discussed in the text, can be implemented in R using the lm() function. Here we use the lm() function in a non-standard way to illustrate the idea of model comparisons. Additionally, we use the anova() function in order to compare two lm(). Note that the anova() function requires that the dependent variable be named the same in the two competing models, which is why we form IQ.1 and IQ.2 as we do below.

HideShow
# Define two data frames, IQ.1 and IQ.2, which is simply the data from Chapter 3, Table 1
IQ_1 = IQ_2 <- chapter_3_table_1

# Reassign `IQ` from the IQ.2 data set as the IQ scores minus the value of 98, which is
# the null.
IQ_2$IQ <- IQ_2$IQ-98

# Fit a linear model in which only the intercept (i.e., the 1) is estimated, which is the
# mean in this context, using the IQ.1 data set.
Full <- lm(IQ ~ 1, data=IQ_1)

# Fit a linear model in which there is no intercept term (i.e., the -1).
Restricted <- lm(IQ ~ -1, data=IQ_2)

# Now, perform the model comparisons. It is important that the two data sets use the same
# name for the dependent variable.
anova(Restricted, Full)
HideShow
Analysis of Variance Table

Model 1: IQ ~ -1
Model 2: IQ ~ 1
  Res.Df RSS Df Sum of Sq  F Pr(>F)  
1      6 336                         
2      5 120  1       216  9 0.0301 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The critical value from an FF-distribution can be found using the qf() function, in which the quantile of interest is specified (e.g., .95) and the numerator and denominator degrees of freedom. Generically, qf() is used as qf(1-alpha, df1, df2). For our example:

HideShow
qf(.95, 1, 5)
HideShow
[1] 6.607891

The pp-value from an FF-test can be found using the pf() function, in which the observed FF-value and degrees of freedom are supplied as arguments. Generically, pf() is used as 1-pf(F, df1, df2) (to obtain the area greater than the observed FF-value). For our example:

HideShow
1-pf(9, 1, 5)
HideShow
[1] 0.03009925
HideShow
# Alternatively
pf(9, 1, 5, lower.tail = FALSE)
HideShow
[1] 0.03009925
The equivalent tt test

As noted in the text, a tt-test can be done. In R, the t.test() function with the null values to test of mu=98 specified can be used.

HideShow
t.test(chapter_3_table_1$IQ, mu=98)
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 3, df = 5, p-value = 0.0301
alternative hypothesis: true mean is not equal to 98
95 percent confidence interval:
  98.85884 109.14116
sample estimates:
mean of x 
      104 

The t.test() function is very general. It can be used for single-sample tt-tests, paired samples tt-test, and independent-samples tt-tests based on the way in which the arguments are specified. To learn more about the various options or a function, use the help() function. Equivalently, a question mark immediately followed by the function for which you want to see the help file can be used. Either one opens the help page in your own R session, so the two lines below are shown but not run here.

HideShow
help(t.test)
?t.test

Doing a tt-test step-by-step can be done as follows, where we first define a variable called IQ to make the code easier to follow.

HideShow
IQ <- chapter_3_table_1$IQ
Mean_IQ <- mean(IQ)
s_IQ <- sd(IQ)
n <- length(IQ)
(Mean_IQ - 98)/(s_IQ/sqrt(n))
HideShow
[1] 3

The critical value or values from a tt-distribution can be found using the qt() function, in which the quantiles of interest are specified (e.g., .025 and .975 for a two-sided test; .95 for a one-sided test). For example

HideShow
# For a one-sided test using alpha=.05
qt(.95, 5)
HideShow
[1] 2.015048
HideShow
# For a two-sided test using alpha=.05
qt(c(.025, .975), 5)
HideShow
[1] -2.570582  2.570582

The pp-value from a tt-test can be found using the pt() function, in which the observed tt-value and degrees of freedom are supplied as arguments. For a two-sided pp-value, the pt() function can be used generically as 2*(1-pt(abs(t), df)), where the absolute value is used for the observed tt-value.

HideShow
# For a two-sided p-value
2*(1-pt(abs(3), 5))
HideShow
[1] 0.03009925

For a one-sided pp-value the pt() function is used differently based on the alternative hypothesis that is specified. For an alternative hypothesis of “<”, only the area to the left of the observed tt-value is needed, so pt is used as pt(t, df), which returns the cumulative probability. It is important that the absolute value function (i.e., abs()) is not used for single-sided tests.

HideShow
pt(3, 5)
HideShow
[1] 0.9849504
HideShow
# The above differs considerably from, say, an observed negative t-value and a "<"
# alternative hypothesis.
pt(-3, 5)
HideShow
[1] 0.01504962

Had a “>” alternative hypothesis been specified, the pt() function would be used as 1-pt(t, df), which returns the area more extreme than the observed tt-value. Again, it is important that the absolute value function (i.e., abs()) is not used for single-sided tests.

HideShow
1-pt(3, 5)
HideShow
[1] 0.01504962
HideShow
# The above differs considerably from, say, an observed negative t-value and a ">"
# alternative hypothesis.
1-pt(-3, 5)
HideShow
[1] 0.9849504

3.7 — The General Case of One-Way Designs

3.7.2 — Numerical Example

The chapter’s one-way numerical example is the mood-induction study of Table 3.3: 30 participants are assigned to a pleasant, neutral, or unpleasant mood induction, and each gives a single global-affect rating on a 7-point scale. Table 3.4 (p. 98) works the analysis of variance for these data, which we reproduce below after first preparing and plotting them.

Loading and viewing the data

We begin with Table 3.3, the data upon which Figure 3.1 is based. Calling the object by name returns it, so we can see what we have.

HideShow
data(chapter_3_table_3)
chapter_3_table_3
HideShow
   Condition Rating
1          1      6
2          1      5
3          1      4
4          1      7
5          1      7
6          1      5
7          1      5
8          1      7
9          1      7
10         1      7
11         2      5
12         2      4
13         2      4
14         2      3
15         2      4
16         2      3
17         2      4
18         2      4
19         2      4
20         2      5
21         3      3
22         3      3
23         3      4
24         3      4
25         3      4
26         3      3
27         3      1
28         3      2
29         3      2
30         3      4

To learn the structure of the data, the str() function can be used. Importantly, here, we see that Condition is treated as an integer (a number).

HideShow
str(chapter_3_table_3)
HideShow
'data.frame':   30 obs. of  2 variables:
 $ Condition: int  1 1 1 1 1 1 1 1 1 1 ...
 $ Rating   : int  6 5 4 7 7 5 5 7 7 7 ...

The above can also be seen by using the class() function, which shows that Condition is a numeric variable.

HideShow
class(chapter_3_table_3$Condition)
HideShow
[1] "integer"

We can convert Condition into a factor, so that it is explicitly recognized as a grouping variable, using the as.factor() function and redefining the Condition variable.

HideShow
chapter_3_table_3$Condition <- as.factor(chapter_3_table_3$Condition)
class(chapter_3_table_3$Condition)
HideShow
[1] "factor"
Boxplots of the three conditions

Every figure in these notes is drawn with ggplot2. A ggplot is built up in layers: a call to ggplot() names the data and maps variables to positions, and one or more geom_*() layers say how to draw them. The simplest box-and-whiskers plot of the ratings by condition is a single geom_boxplot() layer.

HideShow
ggplot(chapter_3_table_3, aes(x = Condition, y = Rating)) +
  geom_boxplot()

Axis labels and a title are added with labs().

HideShow
ggplot(chapter_3_table_3, aes(x = Condition, y = Rating)) +
  geom_boxplot() +
  labs(title = "Box and whiskers plot of affect rating by group",
       x = "Group", y = "Global affect rating")

The conditions are still labeled 1, 2, and 3. Spelling the levels out makes the figure readable on its own. We map each code to its name with case_when() so the correspondence is written out rather than left to the order of a vector, then call factor() only to fix the order in which the levels appear.

HideShow
mood <- chapter_3_table_3 |>
  mutate(Condition = case_when(
    Condition == 1 ~ "Pleasant",
    Condition == 2 ~ "Neutral",
    Condition == 3 ~ "Unpleasant"
  )) |>
  mutate(Condition = factor(Condition,
    levels = c("Pleasant", "Neutral", "Unpleasant")))

ggplot(mood, aes(x = Condition, y = Rating)) +
  geom_boxplot() +
  labs(title = "Box and whiskers plot of affect rating by group",
       x = "Group", y = "Global affect rating")

Adding the individual scores with geom_point() shows what each box summarizes.

HideShow
ggplot(mood, aes(x = Condition, y = Rating)) +
  geom_boxplot(outlier.shape = NA) +
  geom_point() +
  labs(title = "Box and whiskers plot of affect rating by group",
       x = "Group", y = "Global affect rating")

Because several participants gave the same rating, those points fall on top of one another and cannot be counted. “Jittering” them (literally, shifting each one slightly) makes the distribution within each group visible. That is what the book’s Figure 3.1 does, which we draw next.

Figure 3.1. Individual global-affect scores in three treatment groups

This figure shows every individual score, grouped by condition, with a box summarizing each group. Plotting the raw points — jittered horizontally so ties are visible — is the figure’s purpose: it shows the spread within each group, not just the group means.

HideShow
set.seed(113)  # reproducible jitter
ggplot(mood, aes(x = Condition, y = Rating)) +
  geom_boxplot(width = 0.55, fill = "white",
               color = "black", outlier.shape = NA) +
  geom_jitter(width = 0.12, height = 0, size = 2.3, alpha = 0.8,
              color = "#0C2340") +
  scale_y_continuous(breaks = 1:7, limits = c(1, 7)) +
  labs(x = "Treatment group", y = "Global affect rating")
Figure 3.1. Individual scores on a 7-point rating scale of global affect in three treatment groups.

Figure 3.1. Individual scores on a 7-point rating scale of global affect in three treatment groups.

The pleasant-induction scores sit high (mostly 5 to 7), the unpleasant-induction scores low (mostly 1 to 4), and the neutral group in between — the pattern the one-way FF test formalizes below.

Group descriptive statistics with dplyr

Numeric summaries can be obtained with the summary() function. One way to do this is to select the rows of interest (i.e., the groups) by using logical statements. Later we explore other ways of doing this. Note that, however, the percentiles (or quantiles) that are given are from but one way of calculating percentiles (or quantiles). See ?quantile for more information on how R makes such computations (there are, in fact, nine different algorithms that R can use, with the appropriate options selected).

HideShow
summary(chapter_3_table_3[chapter_3_table_3[,"Condition"]==1, "Rating"])
HideShow
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
    4.0     5.0     6.5     6.0     7.0     7.0 
HideShow
summary(chapter_3_table_3[chapter_3_table_3[,"Condition"]==2, "Rating"])
HideShow
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
      3       4       4       4       4       5 
HideShow
summary(chapter_3_table_3[chapter_3_table_3[,"Condition"]==3, "Rating"])
HideShow
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00    2.25    3.00    3.00    4.00    4.00 
HideShow
sd(chapter_3_table_3[chapter_3_table_3[,"Condition"]==1, "Rating"])
HideShow
[1] 1.154701
HideShow
sd(chapter_3_table_3[chapter_3_table_3[,"Condition"]==2, "Rating"])
HideShow
[1] 0.6666667
HideShow
sd(chapter_3_table_3[chapter_3_table_3[,"Condition"]==3, "Rating"])
HideShow
[1] 1.054093
Computations for the one-way ANOVA

We used the summarize() function from the dplyr package earlier. A wonderful function within dplyr is the group_by() function, which does the summarizing as demonstrated before, but it does so by a grouping factor. For us, the grouping factor is Condition, which identifies the levels of the group (i.e., Condition). We can very simply replicate Table 3.4 (something that takes some work in other programs).

HideShow
Summary_Mood <- chapter_3_table_3 %>%
  group_by(Condition) %>%
  summarize(Sum_Y = sum(Rating),
            Y_bar = mean(Rating),
            Sum_Squared_Errors = sum((Rating-mean(Rating))^2),
            n = n())

Summary_Mood
HideShow
# A tibble: 3 × 5
  Condition Sum_Y Y_bar Sum_Squared_Errors     n
  <fct>     <int> <dbl>              <dbl> <int>
1 1            60     6                 12    10
2 2            40     4                  4    10
3 3            30     3                 10    10
HideShow
(a <- length(unique(chapter_3_table_3$Condition)))
HideShow
[1] 3
HideShow
(N <- length(chapter_3_table_3$Rating))
HideShow
[1] 30
HideShow
(E_F <- sum(Summary_Mood$Sum_Squared_Errors))
HideShow
[1] 26
HideShow
(E_R <- sum((chapter_3_table_3$Rating - mean(chapter_3_table_3$Rating))^2))
HideShow
[1] 72.66667
HideShow
(SS_Between <- E_R - E_F)
HideShow
[1] 46.66667
HideShow
(MS_Between <- SS_Between/(a-1))
HideShow
[1] 23.33333
HideShow
(MS_Within <- E_F/(N-a))
HideShow
[1] 0.962963
HideShow
(df_F <- df_Within <- N-a)
HideShow
[1] 27
HideShow
(df_R <- N-1)
HideShow
[1] 29
HideShow
(df_Between <- df_R-df_F)
HideShow
[1] 2
HideShow
# Named F_obs rather than F: R reads a bare `F` as an abbreviation for FALSE,
# so assigning to it would mask the built-in constant for the rest of the session.
(F_obs <- ((E_R - E_F)/(df_R-df_F))/(E_F/df_F))
HideShow
[1] 24.23077
HideShow
# Or
((E_R - E_F)/df_Between)/(E_F/df_Within)
HideShow
[1] 24.23077
HideShow
# Or,
MS_Between/MS_Within
HideShow
[1] 24.23077
HideShow
# Critical value
qf(.95, df_Between, df_Within)
HideShow
[1] 3.354131
HideShow
# p-value
1-pf(F_obs, df_Between, df_Within)
HideShow
[1] 9.421379e-07

As a direct check that these intermediate quantities match the book’s Table 3.4, we plug the numbers into the formula.

HideShow
c(E_F = E_F, E_R_minus_E_F = SS_Between, MS_Between = MS_Between,
  MS_Within = MS_Within, F = F_obs)
HideShow
          E_F E_R_minus_E_F    MS_Between     MS_Within             F 
    26.000000     46.666667     23.333333      0.962963     24.230769 
HideShow
#> matches book p. 98 (Table 3.4): E_F = SS_W = 26, SS_B = 46.67,
#> MS_B = 23.33, MS_W = 0.963, F = 24.23

The above showed the step-by-step how-to that mimics the text. In R, a one-way ANOVA can be done as follows (recalling that we already defined Condition as a factor). In the code below the aov() function fits an ANOVA model but summary() provides a summary of an aov() (and many other) objects, as we will see.

HideShow
summary(aov(Rating ~ Condition, data=chapter_3_table_3))
HideShow
            Df Sum Sq Mean Sq F value   Pr(>F)    
Condition    2  46.67  23.333   24.23 9.42e-07 ***
Residuals   27  26.00   0.963                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Note that, had we not already defined Condition as a factor, it can be done within the aov() function as follows. Specification of the factor is important, otherwise use of the aov() and summary() functions will produce results for a different type of analysis.

HideShow
summary(aov(Rating ~ as.factor(Condition), data=chapter_3_table_3))
HideShow
                     Df Sum Sq Mean Sq F value   Pr(>F)    
as.factor(Condition)  2  46.67  23.333   24.23 9.42e-07 ***
Residuals            27  26.00   0.963                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
The two models side by side

This is the first one-way between-subjects design in the book, so it is worth seeing the model comparison the FF test actually performs. The restricted model estimates a single grand mean (Rating ~ 1); the full model estimates a separate mean for each condition (Rating ~ Condition). The FF test asks whether the extra two parameters of the full model reduce error enough to be worth keeping.

HideShow
Restricted_Model <- lm(Rating ~ 1, data=chapter_3_table_3)         # grand mean only
Full_Model       <- lm(Rating ~ Condition, data=chapter_3_table_3) # group means

# The error sums of squares of these two models are E_R and E_F from the
# by-hand table above, and anova() returns the same F as summary(aov()).
anova(Restricted_Model, Full_Model)
HideShow
Analysis of Variance Table

Model 1: Rating ~ 1
Model 2: Rating ~ Condition
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
1     29 72.667                                  
2     27 26.000  2    46.667 24.231 9.421e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

A side-by-side table makes the two models easy to compare. With modelsummary, each model is in its own column with standard errors in parentheses and the fit statistics at the foot. The full model’s residual deviance is E_F (26) and the restricted model’s is E_R (72.667), the same error terms compared by hand.

HideShow
modelsummary(
  list("Restricted (grand mean)" = Restricted_Model,
       "Full (group means)"      = Full_Model),
  estimate  = "{estimate}",
  statistic = "({std.error})",   # standard errors in parentheses, APA style
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  output    = "gt"
)
Restricted (grand mean) Full (group means)
(Intercept) 4.333 6.000
(0.289) (0.310)
Condition2 -2.000
(0.439)
Condition3 -3.000
(0.439)
Num.Obs. 30 30
AIC 115.7 88.8
BIC 118.5 94.4
Log.Lik. -55.838 -40.422

The full model’s coefficients as a gtsummary regression table. With the default (treatment) contrasts the intercept is the pleasant-condition mean (6), and each slope is a group mean’s deviation from it (neutral, 4−6=−24 - 6 = -2; unpleasant, 3−6=−33 - 6 = -3).

HideShow
tbl_regression(Full_Model, intercept = TRUE)
Characteristic Beta 95% CI p-value
(Intercept) 6.0 5.4, 6.6 <0.001
Condition


    1 — —
    2 -2.0 -2.9, -1.1 <0.001
    3 -3.0 -3.9, -2.1 <0.001
Abbreviation: CI = Confidence Interval

The same analysis as an APA-style ANOVA table built with gt: Source, SSSS, dfdf, MSMS, FF, pp, and partial η2\eta^2. (For a one-way design partial η2\eta^2 equals η2=SSB/SST\eta^2 = SS_B / SS_T, the full model’s R2R^2.)

HideShow
aov_fit <- aov(Rating ~ Condition, data=chapter_3_table_3)
aov_df  <- as.data.frame(summary(aov_fit)[[1]])
ss_res  <- aov_df["Residuals", "Sum Sq"]
data.frame(
  Source = c("Condition (Between)", "Within (Error)"),
  SS     = aov_df[, "Sum Sq"],
  df     = aov_df[, "Df"],
  MS     = aov_df[, "Mean Sq"],
  Fstat  = aov_df[, "F value"],
  p      = aov_df[, "Pr(>F)"],
  # Partial eta-squared: effect SS over effect-plus-error SS.
  peta   = c(aov_df["Condition", "Sum Sq"] /
               (aov_df["Condition", "Sum Sq"] + ss_res), NA_real_)
) |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("**Table 3.4**. Analysis of Variance for Global Affect Rating")) |>
  cols_align(align = "center", columns = -Source)
Table 3.4. Analysis of Variance for Global Affect Rating
Source SS df MS F p Partial η2
Condition (Between) 46.67 2 23.33 24.23 0.0000 0.642
Within (Error) 26.00 27 0.96


3.9 — Measures of Effect

3.9.1 — Measures of Effect Size

3.9.1.2 — Confidence Intervals

To compute a confidence interval, in a step-by-step fashion, we can create objects of the relevant values, where MOE is margin of error.

HideShow
alpha <- .05
n <- 6
Y_bar <- 104
s <- sqrt(24)
s_Y_bar <- s/sqrt(n)
MOE <- qt(1-.05/2, n-1)*s_Y_bar
Y_bar - MOE
HideShow
[1] 98.85884
HideShow
Y_bar + MOE
HideShow
[1] 109.1412
HideShow
#> 98.86, 109.14 — matches book p. 108

Recall that earlier we used the t.test() function for the test of the null hypothesis that IQ had a mean of 98. In particular, we did the following, which, as part of the output, also provides the 95% confidence interval.

HideShow
t.test(chapter_3_table_1$IQ, mu=98)
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 3, df = 5, p-value = 0.0301
alternative hypothesis: true mean is not equal to 98
95 percent confidence interval:
  98.85884 109.14116
sample estimates:
mean of x 
      104 

Note that use of the t.test() function for purposes of obtaining a confidence interval does not depend, in any way, on the null value that is specified. For example, had the null value been 100, the confidence interval is unchanged.

HideShow
t.test(chapter_3_table_1$IQ, mu=100)
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 2, df = 5, p-value = 0.1019
alternative hypothesis: true mean is not equal to 100
95 percent confidence interval:
  98.85884 109.14116
sample estimates:
mean of x 
      104 

Further, note that a different confidence level can be specified with the additional argument of conf.level = 0.95. For example, a 99% confidence interval can be obtained as

HideShow
t.test(chapter_3_table_1$IQ, mu=98, conf.level = 0.99)
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 3, df = 5, p-value = 0.0301
alternative hypothesis: true mean is not equal to 98
99 percent confidence interval:
  95.93571 112.06429
sample estimates:
mean of x 
      104 

Also note that a single-sided confidence interval, based on the alternative hypothesis of interest, can be obtained as the following if the alternative hypothesis is “less than”

HideShow
t.test(chapter_3_table_1$IQ, mu=98, alternative="less")
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 3, df = 5, p-value = 0.985
alternative hypothesis: true mean is less than 98
95 percent confidence interval:
     -Inf 108.0301
sample estimates:
mean of x 
      104 

A single sided confidence-interval for an alternative hypothesis of “greater than” can be obtained as

HideShow
t.test(chapter_3_table_1$IQ, mu=98, alternative="greater")
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 3, df = 5, p-value = 0.01505
alternative hypothesis: true mean is greater than 98
95 percent confidence interval:
 99.9699     Inf
sample estimates:
mean of x 
      104 

In this section of the book, the confidence interval for the two-independent group tt-test is done using data based on summary statistics (i.e., the Brown and Miller, 1993 example). This data is not presented in the text, as it was not presented in the article. Suppose, however, that one wanted to test the hypothesis that two independent groups had the same mean and/or they wanted to form a confidence interval for the population mean differences. Here, we will create a data set (rather than reading one from AMCP) to show how one might create a data set directly in R. The scores below are actually the scores from Groups 1 and 2 from Chapter 3, Table 3. We type in the data simply to illustrate how one might (though there are different ways) form a data set in R. Below is just one of many ways data can be entered into R.

HideShow
Group_1 <- cbind(Group=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), Score=c(6, 5, 4, 7, 7, 5, 5, 7, 7, 7))
Group_2 <- cbind(Group=c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2), Score=c(5, 4, 4, 3, 4, 3, 4, 4, 4, 5))
Data <- as.data.frame(rbind(Group_1, Group_2))
Data$Group <- as.factor(Data$Group)

Another way to enter the data above is as follows.

HideShow
Data2 <- cbind(Group=as.factor(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)),
                  Score=c(6, 5, 4, 7, 7, 5, 5, 7, 7, 7, 5, 4, 4, 3, 4, 3, 4, 4, 4, 5))

Yet another way uses the rep() function, which replicates a value the specified number of times.

HideShow
Data3 <- cbind(Group=as.factor(c(rep(1, 10), rep(2, 10))),
                  Score=c(6, 5, 4, 7, 7, 5, 5, 7, 7, 7, 5, 4, 4, 3, 4, 3, 4, 4, 4, 5))

Now that we have data from two independent groups, we can perform a two-group tt-test and obtain the confidence interval as follows. Note that this tt-test does not assume homogeneity of variance, which we show momentarily.

HideShow
t.test(Score~Group, data=Data)
HideShow

    Welch Two Sample t-test

data:  Score by Group
t = 4.7434, df = 14.4, p-value = 0.0002915
alternative hypothesis: true difference in means between group 1 and group 2 is not equal to 0
95 percent confidence interval:
 1.09803 2.90197
sample estimates:
mean in group 1 mean in group 2 
              6               4 

Alternatively, the above tt-test can be modified so that it assumes homogeneity of variance, as we have done thus far in the book for comparing means among some number of groups. This is accomplished in R using the additional specification of var.equal=TRUE.

HideShow
t.test(Score~Group, data=Data, var.equal=TRUE)
HideShow

    Two Sample t-test

data:  Score by Group
t = 4.7434, df = 18, p-value = 0.0001623
alternative hypothesis: true difference in means between group 1 and group 2 is not equal to 0
95 percent confidence interval:
 1.114173 2.885827
sample estimates:
mean in group 1 mean in group 2 
              6               4 

The above tt-test can also be specified without the use of the data argument, but by using two matrices of scores (recall that we defined two vectors of the scores when we first created this data set). Note that you must select only the Score column (otherwise the group identifier will also be used)

HideShow
t.test(Group_1[,"Score"], Group_2[,"Score"], var.equal=TRUE)
HideShow

    Two Sample t-test

data:  Group_1[, "Score"] and Group_2[, "Score"]
t = 4.7434, df = 18, p-value = 0.0001623
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 1.114173 2.885827
sample estimates:
mean of x mean of y 
        6         4 

Had the matrix of data for Group 1 and Group 2 been specified as simply a vector of scores, we would implement a tt-test as

HideShow
group_1 <- c(6, 5, 4, 7, 7, 5, 5, 7, 7, 7)
group_2 <- c(5, 4, 4, 3, 4, 3, 4, 4, 4, 5)
t.test(group_1, group_2, var.equal=TRUE)
HideShow

    Two Sample t-test

data:  group_1 and group_2
t = 4.7434, df = 18, p-value = 0.0001623
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 1.114173 2.885827
sample estimates:
mean of x mean of y 
        6         4 
3.9.1.4 — The Standardized Difference Between Means

Brown and Miller’s treatment and control groups each had 13 participants. The mean difference is standardized by the pooled within-group standard deviation for dd, or by the control standard deviation for dCd_C (book p. 111).

HideShow
mean_diff <- 60.9 - 18.5
# Equal group sizes give the two sample variances equal weight.
d_pooled  <- mean_diff / sqrt((778.41 + 2756.25) / 2)
d_control <- mean_diff / sqrt(2756.25)
c(d = d_pooled, d_C = d_control)
HideShow
       d      d_C 
1.008572 0.807619 
HideShow
#> 1.0086 and 0.8076 — matches book p. 111.

For Equation 3.86, DMAR applies the small-sample correction using the degrees of freedom for the chosen standardizer.

HideShow
DMAR::smd(mean_1 = 60.9, mean_2 = 18.5, s_1 = sqrt(778.41),
          s_2 = sqrt(2756.25), n_1 = 13, n_2 = 13, unbiased = TRUE)
term value
smd 0.977
HideShow
smd_c(mean_T = 60.9, mean_C = 18.5, s_C = sqrt(2756.25),
      n_C = 13, unbiased = TRUE)
term value
smd_c 0.756
HideShow
#> 0.7559 for the corrected control-standardized difference (book p. 112).
3.9.1.5 — Confidence Intervals for Standardized Differences Between Means

DMAR inverts the noncentral tt distribution for both standardizers. The intervals below assume independent normal groups with equal population variances. Using the control standard deviation alone gives 12 degrees of freedom for that interval, compared with 24 for the pooled interval.

HideShow
ci_smd(smd = d_pooled, n_1 = 13, n_2 = 13, conf_level = 0.95)
term value
ci_lower 0.180
smd 1.009
ci_upper 1.819

Confidence level: 95%

HideShow
#> 95% CI [0.1799, 1.8188] for the pooled-standardized effect (book p. 114).
ci_smd_c(smd_c = d_control, n_C = 13, n_E = 13, conf_level = 0.95)
term value
ci_lower -0.039
smd_c 0.808
ci_upper 1.626

Confidence level: 95%

Figure 3.2. Noncentral tt distributions at the confidence limits

Section 3.9 forms a confidence interval for a standardized mean difference by inverting the noncentral-tt distribution. Using the Brown and Miller (1993) two-group example (n1=n2=13n_1 = n_2 = 13, observed t=F=6.612=2.5714t = \sqrt{F} = \sqrt{6.612} = 2.5714), the limits of the 95% confidence interval for the noncentrality parameter are the two values whose noncentral-tt distributions place the observed tt at their 2.5th and 97.5th percentiles. The upper axis expresses each possible tt as a sample standardized mean difference dd. The same conversion takes the confidence limits for λ\lambda to limits for the population effect δ\delta.

HideShow
# Two-group example with an observed t statistic of 2.5714.
n1 <- 13; n2 <- 13; nu <- n1 + n2 - 2
t_obs <- 2.5714
per_d <- sqrt((n1 * n2) / (n1 + n2))   # t = d * per_d; lambda = delta * per_d

lims <- ci_nc_t(ncp = t_obs, df = nu, conf_level = 0.95)
ncp_low <- lims$value[lims$term == "ci_lower"]
ncp_up  <- lims$value[lims$term == "ci_upper"]

x <- seq(-4, 13, by = 0.01)
dens <- rbind(
  data.frame(t = x, density = dt(x, df = nu, ncp = ncp_low),
             limit = "Lower"),
  data.frame(t = x, density = dt(x, df = nu, ncp = ncp_up),
             limit = "Upper")
)

ggplot(dens, aes(t, density, color = limit)) +
  geom_line(linewidth = 0.9) +
  geom_vline(xintercept = t_obs, color = "#0C2340",
             linewidth = 0.8) +
  annotate("text", x = t_obs, y = max(dens$density) * 1.02,
           label = sprintf("italic(t)[plain(obs)] == %.2f", t_obs), parse = TRUE,
           color = "#0C2340", hjust = -0.12, vjust = 0, size = 3.3) +
  scale_color_brewer(
    palette = "Dark2", breaks = c("Lower", "Upper"),
    labels = as.expression(list(
      bquote(italic("λ")[plain(L)] == .(round(ncp_low, 2))),
      bquote(italic("λ")[plain(U)] == .(round(ncp_up, 2)))
    ))
  ) +
  scale_x_continuous(
    name = expression(paste("Noncentral ", italic(t), " value")),
    sec.axis = sec_axis(~ . / per_d,
                        name = expression("Standardized mean difference," ~ italic(d)))
  ) +
  labs(
    subtitle = expression("95% confidence limits for the noncentrality parameter" ~ italic("λ")),
    y = "Density", color = NULL
  ) +
  theme(legend.position = "top")
Figure 3.2. Noncentral \(t\) distributions at the limits of a 95% confidence interval for the noncentrality parameter (Brown & Miller, 1993).

Figure 3.2. Noncentral tt distributions at the limits of a 95% confidence interval for the noncentrality parameter (Brown & Miller, 1993).

On the lower distribution the observed tt sits at the 97.5th percentile and on the upper distribution at the 2.5th percentile; rescaled to δ\delta the limits are about .18 and 1.82, the 95% confidence interval the book reports.

A two-group contrast in the mood-induction data

To anchor the standardized mean difference to data we have at hand, we take the Pleasant-versus-Unpleasant contrast from the mood-induction example (Table 3.3). Two standardizers are in play, and it is worth keeping them apart: the analysis of variance pools all three groups, giving MSW\sqrt{MS_W}, whereas a two-group dd pools only the two groups being compared. We compute both in base R.

HideShow
# Recover the three groups from the mood data.
pleasant   <- chapter_3_table_3$Rating[chapter_3_table_3$Condition == 1]
neutral    <- chapter_3_table_3$Rating[chapter_3_table_3$Condition == 2]
unpleasant <- chapter_3_table_3$Rating[chapter_3_table_3$Condition == 3]

# The analysis of variance's pooled within-group SD: sqrt(MS_W), all three groups.
E_F  <- sum((pleasant   - mean(pleasant))^2)   +
        sum((neutral    - mean(neutral))^2)    +
        sum((unpleasant - mean(unpleasant))^2)
df_F <- length(chapter_3_table_3$Rating) - 3
sd_pooled <- sqrt(E_F / df_F)
sd_pooled
HideShow
[1] 0.9813068
HideShow
# The Pleasant-minus-Unpleasant difference standardized by that within-group SD.
smd_value <- (mean(pleasant) - mean(unpleasant)) / sd_pooled
smd_value
HideShow
[1] 3.057148

The contrast itself is an ordinary two-group tt test, which base R performs with t.test(). Pooling only the two groups being compared, Cohen’s dd is the observed tt rescaled by the group sizes, d=t1/n1+1/n2d = t\sqrt{1/n_1 + 1/n_2}.

HideShow
n_g  <- length(pleasant)
df_t <- 2 * n_g - 2

Pleasant_vs_Unpleasant <- t.test(
  x           = pleasant,
  y           = unpleasant,
  alternative = "two.sided",
  var.equal   = TRUE,
  conf.level  = 0.95
)
Pleasant_vs_Unpleasant
HideShow

    Two Sample t-test

data:  pleasant and unpleasant
t = 6.0678, df = 18, p-value = 9.812e-06
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 1.961276 4.038724
sample estimates:
mean of x mean of y 
        6         3 
HideShow
t_obs <- unname(Pleasant_vs_Unpleasant$statistic)
t_obs
HideShow
[1] 6.067799
HideShow
d_two_group <- t_obs * sqrt(1 / n_g + 1 / n_g)
d_two_group
HideShow
[1] 2.713602

DMAR can recover the two-group estimate directly from the scores and give a 95% confidence interval for the corresponding population effect.

HideShow
DMAR::smd(group_1 = pleasant, group_2 = unpleasant)
term value
smd 2.714
HideShow
ci_smd(ncp = t_obs, n_1 = n_g, n_2 = n_g, conf_level = 0.95)
term value
ci_lower 1.453
smd 2.714
ci_upper 3.936

Confidence level: 95%

HideShow
#> d = 2.714, 95% CI [1.453, 3.936].

# ci_smd() also accepts the standardized mean difference itself, which is often
# all a published report provides; the result is the same.
ci_smd(smd = d_two_group, n_1 = n_g, n_2 = n_g, conf_level = 0.95)
term value
ci_lower 1.453
smd 2.714
ci_upper 3.936

Confidence level: 95%

Under independent normal outcomes with a common variance, the standardized mean difference also gives the proportion of the Pleasant population above the Unpleasant mean and the probability that a randomly chosen Pleasant score exceeds a randomly chosen Unpleasant score. The two-group intervals use the same two-group standardizer and sample sizes as the preceding calculation.

HideShow
pnorm(d_two_group)
HideShow
[1] 0.9966722
HideShow
pnorm(d_two_group / sqrt(2))
HideShow
[1] 0.9724956
HideShow
1 / (2 * pnorm(d_two_group / sqrt(2)) - 1)  # number needed to treat
HideShow
[1] 1.058211
HideShow
proportion_of_superiority(smd = d_two_group, n_1 = n_g, n_2 = n_g, conf_level = 0.95)
term value
smd 2.714
proportion_of_superiority 0.997
smd_ci_lower 1.453
smd_ci_upper 3.936
ci_lower 0.927
ci_upper 1.000

Confidence level: 95%

HideShow
cles(smd = d_two_group, n_1 = n_g, n_2 = n_g, conf_level = 0.95)
term value
smd 2.714
cles 0.972
smd_ci_lower 1.453
smd_ci_upper 3.936
cles_ci_lower 0.848
cles_ci_upper 0.997

Confidence level: 95%

HideShow
nnt_from_smd(smd = d_two_group, n_1 = n_g, n_2 = n_g, conf_level = 0.95)
term value
smd 2.714
srd 0.945
nnt 1.058
smd_ci_lower 1.453
smd_ci_upper 3.936
nnt_ci_lower 1.005
nnt_ci_upper 1.437
srd_ci_lower 0.696
srd_ci_upper 0.995

Confidence level: 95%

HideShow
#> The first two point estimates are 0.997 and 0.972.

For illustration, take the observed two-group value as the assumed population effect in a future study of the same size. DMAR then gives the exact sampling variance and expected value of dd under that assumption.

HideShow
# Large-sample variance approximation and approximate bias-correction factor
2 / n_g + d_two_group^2 / (2 * df_t)
HideShow
[1] 0.4045455
HideShow
1 - 3 / (4 * df_t - 1)
HideShow
[1] 0.9577465
HideShow
var_smd(true_smd = d_two_group, n_1 = n_g, n_2 = n_g)
term value
var_smd_exact 0.480
var_smd_approx 0.405
HideShow
expected_smd(true_smd = d_two_group, n_1 = n_g, n_2 = n_g)
true_smd n_1 n_2 expected_smd bias j_correction
2.714 10 10 2.834 0.120 0.958
3.9.1.6 — Standardized Effects, the Signal-to-Noise Ratio, and Confidence Intervals for ff
Cohen’s ff by hand

The interval above is for the square root of the signal-to-noise ratio, which is Cohen’s ff. The point estimate needs no package at all: ff is the standard deviation of the group means, taking aa rather than a−1a - 1 as the denominator, divided by the within-group standard deviation MSW\sqrt{MS_W}.

HideShow
# Group means and the within-group mean square (the pooled within-cell variance):
group_stats <- chapter_3_table_3 %>%
  group_by(Condition) %>%
  summarize(n = n(), mean = mean(Rating), sd = sd(Rating), .groups = "drop")
group_stats
HideShow
# A tibble: 3 × 4
  Condition     n  mean    sd
  <fct>     <int> <dbl> <dbl>
1 1            10     6 1.15 
2 2            10     4 0.667
3 3            10     3 1.05 
HideShow
ms_w <- E_F / df_F
ms_w
HideShow
[1] 0.962963
HideShow
a       <- nrow(group_stats)
sigma_m <- sqrt(sum((group_stats$mean - mean(chapter_3_table_3$Rating))^2) / a)
sigma_m
HideShow
[1] 1.247219
HideShow
f_base <- sigma_m / sqrt(ms_w)
f_base
HideShow
[1] 1.270978
HideShow
# Squaring f gives the signal-to-noise ratio itself.
f_base^2
HideShow
[1] 1.615385
The same signal-to-noise measures in DMAR

The same group summaries give Cohen’s ff in DMAR. The observed FF statistic also gives confidence intervals for ff and for its square.

HideShow
F_value <- 24.23
df_1    <- 2    # numerator df
df_2    <- 27   # denominator df
N       <- 30

# Cohen's f (the square root of the signal-to-noise ratio):
cohen_f(means = group_stats$mean, var_within = ms_w,
        n_per_group = group_stats$n)
term value
cohen_f 1.271
HideShow
#> 1.271 — the f_base computed by hand above

# A confidence interval on Cohen's f from the observed F statistic:
ci_srsnr(F_value = F_value, df_1 = df_1, df_2 = df_2, N = N,
         conf_level = 0.95)
term value
ci_lower 0.754
ci_upper 1.746

Confidence level: 95%

HideShow
#> [0.754, 1.746] — matches book p. 116.
ci_snr(F_value = F_value, df_1 = df_1, df_2 = df_2, N = N,
       conf_level = 0.95)
term value
ci_lower 0.568
ci_upper 3.049

Confidence level: 95%

HideShow
# Equivalently, using the design-stage entry to ci_srsnr() that takes
# means + within-group variance + n directly, no F-value required:
ci_srsnr(means       = group_stats$mean,
         var_within  = ms_w,
         n_per_group = group_stats$n,
         conf_level  = 0.95)
term value
ci_lower 0.754
ci_upper 1.746

Confidence level: 95%

The median-unbiased estimate of ff uses the value of the noncentrality parameter for which the observed FF is the median (book p. 116).

HideShow
median_f <- function(F_value, df_1, df_2, N) {
  if (pf(F_value, df_1, df_2) <= 0.5) return(0)
  lambda <- uniroot(
    function(lambda) pf(F_value, df_1, df_2, ncp = lambda) - 0.5,
    interval = c(0, N), extendInt = "downX"
  )$root
  sqrt(lambda / N)
}
median_f(F_value, df_1, df_2, N)
HideShow
[1] 1.243929
HideShow
#> 1.244 — matches book p. 116.

3.9.2 — Measures of Association Strength

Computing R2R^2 and ω2\omega^2

One of the advantages of an object oriented language, such as R, is that objects can contain other objects and these objects can be used within other functions. Below we perform an anova using the aov() function and then ask R to state the various objects that are available using the names() function.

HideShow
Result <- aov(Rating ~ as.factor(Condition), data=chapter_3_table_3)
Summary_Output <- summary(Result)

#View the structure of what is in the Summary_Output object.
str(Summary_Output)
HideShow
List of 1
 $ :Classes 'anova' and 'data.frame':   2 obs. of  5 variables:
  ..$ Df     : num [1:2] 2 27
  ..$ Sum Sq : num [1:2] 46.7 26
  ..$ Mean Sq: num [1:2] 23.333 0.963
  ..$ F value: num [1:2] 24.2 NA
  ..$ Pr(>F) : num [1:2] 9.42e-07 NA
 - attr(*, "class")= chr [1:2] "summary.aov" "listof"
HideShow
# Extract the various attributes of interest (first using double square brackets).
Summary_Output[[1]]["Df"]
HideShow
                     Df
as.factor(Condition)  2
Residuals            27
HideShow
Summary_Output[[1]]["Mean Sq"]
HideShow
                     Mean Sq
as.factor(Condition)  23.333
Residuals              0.963
HideShow
Summary_Output[[1]]["Sum Sq"]
HideShow
                     Sum Sq
as.factor(Condition) 46.667
Residuals            26.000
HideShow
Summary_Output[[1]]["F value"]
HideShow
                     F value
as.factor(Condition)  24.231
Residuals                   
HideShow
Summary_Output[[1]]["Pr(>F)"]
HideShow
                        Pr(>F)    
as.factor(Condition) 9.421e-07 ***
Residuals                         
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#Further, objects within the above objects can themselves be extracted:
Summary_Output[[1]]["Df"][1,1]
HideShow
[1] 2
HideShow
Summary_Output[[1]]["Df"][2,1]
HideShow
[1] 27
HideShow
Summary_Output[[1]]["Mean Sq"][1,1]
HideShow
[1] 23.33333
HideShow
Summary_Output[[1]]["Mean Sq"][2,1]
HideShow
[1] 0.962963

Given the above information, Omega^2 can be obtained by extracting the necessary objects.

HideShow
SS_B <- Summary_Output[[1]]["Sum Sq"][1,1]
SS_W <- Summary_Output[[1]]["Sum Sq"][2,1]
df_1 <- Summary_Output[[1]]["Df"][1,1]
df_2 <- Summary_Output[[1]]["Df"][2,1]
MS_W <- Summary_Output[[1]]["Mean Sq"][2,1]

SS_T <- SS_B + SS_W

(Omega_Sq <- (SS_B-df_1*MS_W)/(SS_T + MS_W))
HideShow
[1] 0.6076459
HideShow
#> 0.608 — matches book p. 118

#Or, using F as follows:
F_Val <- Summary_Output[[1]]["F value"][1,1]
df_2 <- Summary_Output[[1]]["Df"][2,1]

(df_1*(F_Val-1))/(df_1*(F_Val-1)+(df_1+df_2+1))
HideShow
[1] 0.6076459
HideShow
#> 0.608 — matches book p. 118 (Equation 3.98)

Similarly, for R^2

HideShow
E_R <- SS_T
E_F <- SS_W
(R2 <- (E_R - E_F)/E_R)
HideShow
[1] 0.6422018
HideShow
#> 0.642 — matches book p. 118

Or for Adjusted R^2

HideShow
N <- df_1 + df_2 + 1
a <- df_1+1

1 - ((N-1)/(N-a))*(1-R2)
HideShow
[1] 0.6156983
HideShow
#> 0.616 — matches book p. 118 (Equation 3.99)
3.9.2.1 — Confidence Intervals for Measures of Association Strength

The preceding calculations give sample R2R^2 and ω̂2\hat\omega^2. DMAR also inverts the noncentral FF distribution for confidence limits on the population proportion of variance accounted for.

HideShow
F_value <- 24.23
df_1    <- 2    # numerator df
df_2    <- 27   # denominator df
N       <- 30

# Omega-squared with a noncentral-F CI. For a one-way design the "partial" and
# "total" omega-squared coincide, which is the estimand asked for here; F and
# its degrees of freedom alone cannot identify a total in a larger design.
ci_omega_squared(F_value = F_value, df_effect = df_1, df_error = df_2, N = N,
                 conf_level = 0.95, estimand = "partial")
effect omega_squared_partial omega_squared_partial_ci_lower omega_squared_partial_ci_upper F_value df_effect df_error N
overall 0.608 0.362 0.753 24.230 2 27 30

Confidence level: 95%

HideShow
#> 0.608 — the Omega_Sq computed by hand above (book p. 118)
#> 0.362, 0.753 — matches book p. 119

# Asymptotic variance of omega-squared (Fleishman 1980), useful for
# Wald-style CIs or meta-analytic weighting. This one has no base-R
# counterpart; we feed it the hand-computed estimate from above.
var_omega_squared(true_omega_squared = Omega_Sq,
                  df_effect = df_1, df_error = df_2, N = N)
term value
var_omega_squared 0.011
HideShow
# Proportion of variance accounted for, with a noncentral-F CI:
ci_pvaf(F_value = F_value, df_1 = df_1, df_2 = df_2, N = N,
        conf_level = 0.95)
term value prob_less prob_greater
ci_lower 0.362 0.025 0.975
pvaf 0.642 NA NA
ci_upper 0.753 0.975 0.025
actual_coverage 0.950 NA NA

Confidence level: 95%

HideShow
#> 0.362, 0.753 — matches book p. 119;
#> pvaf = 0.642 is the R^2 computed by hand above (book p. 118)

# A 90% (1 - 2*alpha) interval is often reported for variance-accounted-for
# measures, the interest being a lower bound on a non-negative quantity:
ci_pvaf(F_value = F_value, df_1 = df_1, df_2 = df_2, N = N,
        conf_level = 0.90)
term value prob_less prob_greater
ci_lower 0.409 0.050 0.950
pvaf 0.642 NA NA
ci_upper 0.735 0.950 0.050
actual_coverage 0.900 NA NA

Confidence level: 90%

3.9.4 — Alternative Representations of Effects

3.9.4.1 — Binomial Effect Size Display (BESD)

A binomial effect size display (using the example from Rosenthal and Rubin (1982)).

HideShow
# Taken from Table 3.6
r <- .32
rbind(c(.5 + r/2, .5 - r/2)*100,
      c(.5 - r/2, .5 + r/2)*100)
HideShow
     [,1] [,2]
[1,]   66   34
[2,]   34   66
3.9.4.2 — Common Language (CL) Effect Size

Common language (CL) effect size. Recalling the example above where we have two groups (taken from Table 3 in Chapter 3). We repeat the data here. We then use the expand.grid() function (as used in the Chapter 1 R code) in order to find all possible pairings of the scores.

HideShow
group_1 <- c(6, 5, 4, 7, 7, 5, 5, 7, 7, 7)
group_2 <- c(5, 4, 4, 3, 4, 3, 4, 4, 4, 5)

Grid <- expand.grid(group_1=group_1, group_2=group_2)
Difs <- Grid[,1] - Grid[,2]

# Note that this is not corrected for ties.
(CL_Uncorrected <- mean(Difs > 0))
HideShow
[1] 0.86
HideShow
# Proportion of ties
(Ties <- mean(Difs==0))
HideShow
[1] 0.12
HideShow
(CL.Corrected <- CL_Uncorrected + .5*Ties)
HideShow
[1] 0.92
Cliff’s measure
HideShow
# Note that `Difs` is defined above.
mean(Difs > 0) - mean(Difs <0)
HideShow
[1] 0.84

3.10 — Statistical Assumptions

3.10.3 — Checking for Normality and Homogeneity of Variance

Sections 3.10.3 and 3.10.4 use the drinking data of Table 3.7: the average number of standard drinks per week reported by homeless alcoholics (Smith et al., 1998) at the 9-month follow-up, across five therapy groups. We load it before using it.

HideShow
data(chapter_3_table_7_raw)
O’Brien’s test

Here we compute O’Brien’s test step-by-step.

HideShow
Y_i1 <- chapter_3_table_7_raw[chapter_3_table_7_raw$Group==1,"Drinks"]
Ybar_1 <- mean(Y_i1)
s2_1 <- var(Y_i1)
n_1 <- length(Y_i1)

Y_i2 <- chapter_3_table_7_raw[chapter_3_table_7_raw$Group==2,"Drinks"]
Ybar_2 <- mean(Y_i2)
s2_2 <- var(Y_i2)
n_2 <- length(Y_i2)


Y_i3 <- chapter_3_table_7_raw[chapter_3_table_7_raw$Group==3,"Drinks"]
Ybar_3 <- mean(Y_i3)
s2_3 <- var(Y_i3)
n_3 <- length(Y_i3)

Y_i4 <- chapter_3_table_7_raw[chapter_3_table_7_raw$Group==4,"Drinks"]
Ybar_4 <- mean(Y_i4)
s2_4 <- var(Y_i4)
n_4 <- length(Y_i4)

Y_i5 <- chapter_3_table_7_raw[chapter_3_table_7_raw$Group==5,"Drinks"]
Ybar_5 <- mean(Y_i5)
s2_5 <- var(Y_i5)
n_5 <- length(Y_i5)

r_1 <- (((n_1-1.5)*n_1*((Y_i1-Ybar_1)^2))-(.5*s2_1*(n_1-1)))/((n_1-1)*(n_1-2))
r_2 <- (((n_2-1.5)*n_2*((Y_i2-Ybar_2)^2))-(.5*s2_2*(n_2-1)))/((n_2-1)*(n_2-2))
r_3 <- (((n_3-1.5)*n_3*((Y_i3-Ybar_3)^2))-(.5*s2_3*(n_3-1)))/((n_3-1)*(n_3-2))
r_4 <- (((n_4-1.5)*n_4*((Y_i4-Ybar_4)^2))-(.5*s2_4*(n_4-1)))/((n_4-1)*(n_4-2))
r_5 <- (((n_5-1.5)*n_5*((Y_i5-Ybar_5)^2))-(.5*s2_5*(n_5-1)))/((n_5-1)*(n_5-2))

# Notice the following, where the first column is the mean of the r.j and the second
#column is the variance.
as.matrix(rbind(
c(mean(r_1), s2_1),
c(mean(r_2), s2_2),
c(mean(r_3), s2_3),
c(mean(r_4), s2_4),
c(mean(r_5), s2_5)))
HideShow
          [,1]      [,2]
[1,]  2439.836  2439.836
[2,]  3713.122  3713.122
[3,] 22162.041 22162.041
[4,]  3952.290  3952.290
[5,]  2008.812  2008.812
HideShow
# Add a column of the r values.
chapter_3_table_7_raw$r <- c(r_1, r_2, r_3, r_4, r_5)

Now, using the new column of data in the data set, r, we perform the ANOVA as before.

HideShow
summary(aov(r ~ as.factor(Group), data=chapter_3_table_7_raw))
HideShow
                 Df    Sum Sq   Mean Sq F value Pr(>F)
as.factor(Group)  4 5.074e+09 1.269e+09   0.953  0.438
Residuals        83 1.105e+11 1.331e+09               
Levene’s test

The Levene test is implemented in the car package with the LeveneTest() function. Note that below we use center=mean, though the default is center=median.

HideShow
leveneTest(Drinks ~ as.factor(Group), data=chapter_3_table_7_raw, center=mean)
HideShow
Levene's Test for Homogeneity of Variance (center = mean)
      Df F value Pr(>F)
group  4  1.7558 0.1456
      83               
Visualizing distribution shape

Here we plot a quantile-quantile plot of the chapter_3_table_7_raw data, ignoring groups. In ggplot2 the sample is mapped to the sample aesthetic, and stat_qq() draws the points against theoretical normal quantiles while stat_qq_line() adds the reference line a normal sample would follow. Points bending away from that line indicate a departure from normality.

HideShow
ggplot(chapter_3_table_7_raw, aes(sample = Drinks)) +
  stat_qq(size = 1.6, alpha = 0.8) +
  stat_qq_line(color = "#0C2340", linewidth = 0.8) +
  labs(x = "Theoretical quantiles", y = "Sample quantiles")

Figure 3.3. Distribution of standard drinks per week

The intake measurements in Smith et al. (1998) have a long right tail. The bars below use the grouped frequencies read from the published histogram. The normal curve uses the intake mean and standard deviation printed in the original figure.

HideShow
bin_width <- 25
intake <- data.frame(
  center = seq(0, 575, by = bin_width),
  frequency = c(11, 11, 11, 11, 8, 9, 7, 4, 4, 5, 6, 2,
                 6,  2,  1,  0, 1, 1, 2, 2, 0, 0, 1, 1)
)

# Convert the normal density to the same frequency scale as the bars.
intake_mean <- 149.7
intake_sd <- 133.43
edges <- range(intake$center) + c(-0.5, 0.5) * bin_width
curve_x <- seq(edges[1], edges[2], length.out = 500)
normal_curve <- data.frame(
  x = curve_x,
  frequency = dnorm(curve_x, intake_mean, intake_sd) *
    sum(intake$frequency) * bin_width
)

ggplot(intake, aes(center, frequency)) +
  geom_col(width = bin_width, fill = "grey74", colour = "grey25", linewidth = 0.4) +
  geom_line(data = normal_curve, aes(x = x), colour = "#0C2340", linewidth = 0.85) +
  annotate("text", x = 570, y = 11.5, label = "bar(italic(Y)) == 149.7",
           parse = TRUE, hjust = 1) +
  annotate("text", x = 570, y = 10.7, label = "italic(s)[italic(Y)] == 133.43",
           parse = TRUE, hjust = 1) +
  scale_x_continuous(breaks = seq(0, 550, by = 50), expand = expansion(0)) +
  scale_y_continuous(breaks = seq(0, 12, by = 2), expand = expansion(0)) +
  coord_cartesian(xlim = edges, ylim = c(0, 12)) +
  labs(x = "Average number of standard drinks per week", y = "Frequency")
Histogram of weekly drinking at intake. The four leftmost bars are tallest, and a sparse right tail extends beyond 500 drinks per week. A fitted normal curve is overlaid.

Figure 3.3. Average number of standard drinks per week at intake (Smith et al., 1998).

For the remaining examples, we return to the individual nine-month follow-up measurements in chapter_3_table_7_raw. The moments package reports raw kurtosis (3 for a normal distribution). The DMAR summaries below use a small-sample correction and report excess kurtosis (0 for a normal distribution).

HideShow
moments::skewness(chapter_3_table_7_raw$Drinks)
HideShow
[1] 4.770605
HideShow
moments::kurtosis(chapter_3_table_7_raw$Drinks)
HideShow
[1] 32.00413
Visualizing confidence intervals

Beyond distributional shape, we can visualize group means and variability using confidence intervals. These plots also help in assessing potential assumption violations.

Here we visualize the confidence interval limits by group. We use the t.test() function as before, but not literally for the hypothesis test. Recall that this function also provides a confidence interval for the population mean. We extract the conf.int results from the t.test() of each group and plot one interval per group.

HideShow
# Give the five nine-month follow-up groups the labels used in Figures 3.4 and 3.5.
drinks <- chapter_3_table_7_raw |>
  mutate(Therapy = factor(Group, levels = 1:5,
    labels = c("T1 CRA-D", "T1 CRA+D", "T1 Std", "T2 CRA-D", "T2 Std")))
Group_Names <- levels(drinks$Therapy)
Group_Names
HideShow
[1] "T1 CRA-D" "T1 CRA+D" "T1 Std"   "T2 CRA-D" "T2 Std"  
Figure 3.4. Confidence intervals around group means of drinks per week

Beyond a single distribution, plotting a confidence interval for each group’s mean makes between-group differences and unequal spread visible at once. This figure shows the 95% confidence interval around the mean number of drinks per week for each of the five therapy groups at the 9-month follow-up (Smith et al., 1998), each computed from that group’s own standard deviation. The widely differing interval lengths are the figure’s lesson: with roughly equal group sizes, intervals that differ several-fold in width signal a likely violation of homogeneity of variance.

HideShow
# One 95% CI per group, from each group's own t.test (separate-variances limits).
ci_by_group <- function(data, value) {
  data |>
    group_by(Therapy) |>
    summarize(mean = mean(.data[[value]]),
              lower = t.test(.data[[value]])$conf.int[1],
              upper = t.test(.data[[value]])$conf.int[2],
              .groups = "drop")
}
ci_drinks <- ci_by_group(drinks, "Drinks")

ggplot(ci_drinks, aes(Therapy, mean)) +
  geom_hline(yintercept = 0, color = "grey70", linewidth = 0.3) +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.18,
                color = "black", linewidth = 0.8) +
  geom_point(size = 2.6, shape = 22, fill = "#0C2340",
             color = "black") +
  labs(x = "Therapy group", y = "95% CI for number of drinks")
Figure 3.4. Confidence intervals around means for number of drinks per week for five groups at 9-month follow-up (Smith et al., 1998).

Figure 3.4. Confidence intervals around means for number of drinks per week for five groups at 9-month follow-up (Smith et al., 1998).

The T1 Std interval is several times longer than the others even though its sample size is comparable, the hallmark of heterogeneous variances that Section 3.10 warns against.

Skewness and kurtosis

To complement the visual diagnostics, we calculate descriptive statistics, including skewness and kurtosis, which provide numeric summaries of distributional shape.

The psych package has a nice descriptive statistics function, describe() that can easily be applied to a data set. To obtain a useful set of descriptives for all variables in a data set, describe() can be used as follows.

HideShow
describe(chapter_3_table_7_raw)
HideShow
         vars  n    mean       sd median trimmed    mad     min       max
Group       1 88    3.09     1.42   3.00    3.11   1.48    1.00      5.00
Drinks      2 88   36.88    81.96   3.85   19.64   5.70    0.00    624.62
LgDrinks    3 88    0.84     0.85   0.68    0.77   1.01    0.00      2.80
r           4 88 6718.94 36447.29 649.23 1217.95 595.96 -106.15 335136.99
             range  skew kurtosis      se
Group         4.00 -0.04    -1.35    0.15
Drinks      624.62  4.69    28.28    8.74
LgDrinks      2.80  0.40    -1.34    0.09
r        335243.14  8.37    71.99 3885.29

For the follow-up sample, compare the raw kurtosis from moments with the three definitions of excess kurtosis available in psych::describe(). Its type 1 estimate is the raw kurtosis minus 3. Types 2 and 3 use different sample-size adjustments.

HideShow
kurtosis(chapter_3_table_7_raw$Drinks)
HideShow
[1] 32.00413
HideShow
describe(chapter_3_table_7_raw$Drinks, type=1)$kurtosis
HideShow
[1] 29.00413
HideShow
describe(chapter_3_table_7_raw$Drinks, type=2)$kurtosis
HideShow
[1] 30.79357
HideShow
describe(chapter_3_table_7_raw$Drinks, type=3)$kurtosis
HideShow
[1] 28.2809

The book uses what describe() calls type=2. Thus, to reproduce the values in the descriptive statistics table, we have the code below that also adds the group name to the output.

HideShow
rbind(c(Group=Group_Names[1],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==1,"Drinks"], type=2)),
      c(Group=Group_Names[2],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==2,"Drinks"], type=2)),
      c(Group=Group_Names[3],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==3,"Drinks"], type=2)),
      c(Group=Group_Names[4],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==4,"Drinks"], type=2)),
      c(Group=Group_Names[5],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==5,"Drinks"], type=2)))
HideShow
     Group      vars n  mean     sd       median   trimmed  mad      min
[1,] "T1 CRA-D" 1    15 33.80431 49.3947  10.97846 25.98249 16.27667 0  
[2,] "T1 CRA+D" 1    19 26.4196  60.93539 0        15.57014 0        0  
[3,] "T1 Std"   1    17 71.51416 148.8692 28.8     39.40836 40.91976 0  
[4,] "T2 CRA-D" 1    17 20.31077 62.86724 0        5.864205 0        0  
[5,] "T2 Std"   1    20 33.76562 44.81977 13.47692 25.65317 19.98089 0  
     max      range    skew     kurtosis se      
[1,] 169.2923 169.2923 1.836401 3.100115 12.75366
[2,] 237.28   237.28   2.782492 8.104232 13.97954
[3,] 624.6154 624.6154 3.587491 13.73201 36.10609
[4,] 257.32   257.32   3.778988 14.76502 15.24755
[5,] 164.0615 164.0615 1.634646 2.432478 10.02201
The same descriptives in DMAR

DMAR’s descriptives() returns a tidy descriptive-statistics table, including DMAR’s skewness and kurtosis, for one or more variables. Below we apply it to the Drinks and LgDrinks variables, and then build a by-group summary that places the raw and log skewness side by side, which makes §3.10.4’s argument for the log transformation visible at a glance.

HideShow
descriptives(chapter_3_table_7_raw[, c("Drinks", "LgDrinks")])$descriptives
HideShow
  variable    type  n n_missing prop_missing      mean    median         sd min
1   Drinks numeric 88         0            0 36.879240 3.8461539 81.9633081   0
2 LgDrinks numeric 88         0            0  0.840819 0.6834186  0.8505308   0
         max q25       q75  skewness  kurtosis
1 624.615385   0 36.433846 4.8537336 30.793569
2   2.796307   0  1.572357 0.4178558 -1.308316
HideShow
chapter_3_table_7_raw %>%
  group_by(Group) %>%
  summarize(
    n         = n(),
    mean_d    = mean(Drinks),    sd_d    = sd(Drinks),
    skew_d    = DMAR::skewness(Drinks),
    mean_lg   = mean(LgDrinks),  sd_lg   = sd(LgDrinks),
    skew_lg   = DMAR::skewness(LgDrinks),
    .groups   = "drop"
  )
HideShow
# A tibble: 5 × 8
  Group     n mean_d  sd_d skew_d mean_lg sd_lg skew_lg
  <int> <int>  <dbl> <dbl>  <dbl>   <dbl> <dbl>   <dbl>
1     1    15   33.8  49.4   1.84   1.01  0.803 -0.0322
2     2    19   26.4  60.9   2.78   0.540 0.827  1.37  
3     3    17   71.5 149.    3.59   1.23  0.869 -0.237 
4     4    17   20.3  62.9   3.78   0.391 0.744  1.94  
5     5    20   33.8  44.8   1.63   1.05  0.781 -0.209 

Note the dramatic drop in skewness from the raw to the log scale, exactly §3.10.4’s argument for the transformation.

3.10.4 — Transformations

If assumptions appear violated, transformations such as the logarithm or square root may stabilize variance and normalize distributions, which we can evaluate using the same descriptive and visual methods.

Using now the log of the number of Drinks, we can use the describe() function as follows, where we replace Drinks with LgDrinks (note that LgDrinks is already in the data set).

HideShow
rbind(c(Group=Group_Names[1],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==1,"LgDrinks"], type=2)),
      c(Group=Group_Names[2],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==2,"LgDrinks"], type=2)),
      c(Group=Group_Names[3],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==3,"LgDrinks"], type=2)),
      c(Group=Group_Names[4],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==4,"LgDrinks"], type=2)),
      c(Group=Group_Names[5],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==5,"LgDrinks"], type=2)))
HideShow
     Group      vars n  mean      sd        median   trimmed   mad       min
[1,] "T1 CRA-D" 1    15 1.007188  0.8033638 1.078401 0.9905094 1.147596  0  
[2,] "T1 CRA+D" 1    19 0.5400679 0.8274548 0        0.4637766 0         0  
[3,] "T1 Std"   1    17 1.228967  0.8689398 1.474216 1.206408  0.8106354 0  
[4,] "T2 CRA-D" 1    17 0.3912861 0.7442338 0        0.282647  0         0  
[5,] "T2 Std"   1    20 1.053933  0.7811781 1.150223 1.05333   1.063293  0  
     max      range    skew        kurtosis   se       
[1,] 2.231195 2.231195 -0.03217937 -1.457266  0.2074276
[2,] 2.377088 2.377088 1.373427    0.3182206  0.1898312
[3,] 2.796307 2.796307 -0.2371426  -0.8679882 0.2107489
[4,] 2.412158 2.412158 1.943825    2.782116   0.1805032
[5,] 2.217646 2.217646 -0.2085922  -1.387944  0.1746767

Note that, had we been interested in applying a different type of transformation to the data, that can be done directly within the describe() function on the data of interest, such as what we do below using the sqrt() function (for the square root transformation).

HideShow
rbind(c(Group=Group_Names[1],
        describe(sqrt(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==1,"Drinks"]), type=2)),
      c(Group=Group_Names[2],
        describe(sqrt(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==2,"Drinks"]), type=2)),
      c(Group=Group_Names[3],
        describe(sqrt(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==3,"Drinks"]), type=2)),
      c(Group=Group_Names[4],
        describe(sqrt(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==4,"Drinks"]), type=2)),
      c(Group=Group_Names[5],
        describe(sqrt(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==5,"Drinks"]), type=2)))
HideShow
     Group      vars n  mean     sd       median   trimmed  mad      min
[1,] "T1 CRA-D" 1    15 4.229386 4.129589 3.313376 3.879196 4.912411 0  
[2,] "T1 CRA+D" 1    19 2.596713 4.557393 0        1.996097 0        0  
[3,] "T1 Std"   1    17 5.937236 6.207242 5.366563 5.062714 6.33236  0  
[4,] "T2 CRA-D" 1    17 1.886724 4.218765 0        1.068875 0        0  
[5,] "T2 Std"   1    20 4.374796 3.923851 3.645773 4.040459 5.317046 0  
     max      range    skew      kurtosis   se       
[1,] 13.01124 13.01124 0.8036426 -0.2710347 1.066255 
[2,] 15.4039  15.4039  1.873749  2.622742   1.045538 
[3,] 24.99231 24.99231 1.877095  4.900944   1.505477 
[4,] 16.0412  16.0412  2.810644  8.264705   1.023201 
[5,] 12.80865 12.80865 0.5849369 -0.6513498 0.8773998

Using the descriptive statistics previously calculated on the number of Drinks by group, here we fit a regression model with the log standard deviations conditional on the log of the means for the five groups. First, we create a data frame of the log transformed means and standard deviations. Then, we use the lm() function to fit a linear model, here a simple regression model.

HideShow
Log_Descriptives <- data.frame(LogMeans=log(c(Ybar_1, Ybar_2, Ybar_3, Ybar_4, Ybar_5)),
                               LogSD=log(sqrt(c(s2_1, s2_2, s2_3, s2_4, s2_5))))
summary(lm(LogSD~LogMeans, data=Log_Descriptives))
HideShow

Call:
lm(formula = LogSD ~ LogMeans, data = Log_Descriptives)

Residuals:
      1       2       3       4       5 
-0.2926  0.1003  0.2545  0.3267 -0.3889 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   1.5795     1.4096   1.121    0.344
LogMeans      0.7422     0.3977   1.866    0.159

Residual standard error: 0.3735 on 3 degrees of freedom
Multiple R-squared:  0.5372,    Adjusted R-squared:  0.3829 
F-statistic: 3.482 on 1 and 3 DF,  p-value: 0.1589
Figure 3.5. Confidence intervals around the mean of log drinks per week

The natural remedy for the skew and unequal spread in Figure 3.4 is a transformation. This figure repeats the five-group confidence-interval plot on the log-transformed number of drinks per week (variable LgDrinks) at the 9-month follow-up. On the log scale the interval lengths are far more uniform, showing that the transformation has largely stabilized the variance across groups, the payoff Section 3.10 describes.

HideShow
ci_logdrinks <- ci_by_group(drinks, "LgDrinks")

ggplot(ci_logdrinks, aes(Therapy, mean)) +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.18,
                color = "black", linewidth = 0.8) +
  geom_point(size = 2.6, shape = 22, fill = "#0C2340",
             color = "black") +
  labs(x = "Therapy group", y = "95% CI for log number of drinks")
Figure 3.5. Confidence intervals around the mean of log-transformed drinks per week for five groups at 9-month follow-up (Smith et al., 1998).

Figure 3.5. Confidence intervals around the mean of log-transformed drinks per week for five groups at 9-month follow-up (Smith et al., 1998).

With the data on the log scale the five intervals are of comparable length, in sharp contrast to Figure 3.4, illustrating how a log transformation can bring badly skewed, heteroscedastic data closer to the assumptions of the one-way model.

ANOVA on log transformed number of Drinks

HideShow
summary(aov(LgDrinks ~ as.factor(Group), data=chapter_3_table_7_raw))
HideShow
                 Df Sum Sq Mean Sq F value Pr(>F)  
as.factor(Group)  4   9.04  2.2597    3.48 0.0112 *
Residuals        83  53.90  0.6494                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

3.11 — Power of the FF Test: One-Way ANOVA

3.11.1 — Determining an Appropriate Sample Size

Power computed directly from the noncentral FF distribution

Computing the supposed noncentral FF parameter based on a set of supposed population means (for a hypothetical situation)

HideShow
Supposed_Within_Group_SD <- 100
Supposed_Group_Means <- c(400, 450, 500)
Grand_Mean <- mean(Supposed_Group_Means)
Treatment_Effects <- Supposed_Group_Means-Grand_Mean
n <- 10
a <- 3
N <- n*a
(lambda <- 10*sum(Treatment_Effects^2)/Supposed_Within_Group_SD^2)
HideShow
[1] 5
HideShow
(f2 <- lambda/N)
HideShow
[1] 0.1666667
HideShow
(f <- sqrt(f2))
HideShow
[1] 0.4082483

Using the above supposed scores, the ff effect size can be estimated as follows, with
(length(Supposed.Group.Means)-1)/length(Supposed.Group.Means)
being used in order to use nn in the denominator of the variance, rather than the default or typical denominator (n−1n-1).

HideShow
sigma_m <- sqrt(var(Supposed_Group_Means)*(length(Supposed_Group_Means)-1)/length(Supposed_Group_Means))
f <- sigma_m/Supposed_Within_Group_SD
f
HideShow
[1] 0.4082483

In R, we can find the exact power based on the area of the particular noncentral FF-distribution for the specified degrees of freedom by determining the area that is beyond the critical value from the central FF-distributoin as follows, for different sample sizes (some of this is calculated above but it is repeated here for completeness).

HideShow
# Constant (parameters)
(Supposed_sigma_e <- 100)
HideShow
[1] 100
HideShow
(Supposed_Group_Means <- c(400, 450, 500))
HideShow
[1] 400 450 500
HideShow
(a <- length(Supposed_Group_Means))
HideShow
[1] 3
HideShow
(Grand_Mean <- mean(Supposed_Group_Means))
HideShow
[1] 450
HideShow
(alpha <- Supposed_Group_Means-Grand_Mean)
HideShow
[1] -50   0  50
HideShow
(Supposed_sigma_m <- sqrt(sum(alpha^2)/a))
HideShow
[1] 40.82483
HideShow
(f <- Supposed_sigma_m/Supposed_sigma_e)
HideShow
[1] 0.4082483
HideShow
# Variables
(n <- 10)
HideShow
[1] 10
HideShow
# Constant Conditional on the situation (i.e., Conditional based on n)
(lambda <- n*sum(Treatment_Effects^2)/Supposed_Within_Group_SD^2)
HideShow
[1] 5
HideShow
(CV <- qf(.95, df1=a-1, df2=a*n-a))
HideShow
[1] 3.354131
HideShow
# Statistical power.
(power <- pf(CV, df1=a-1, df2=a*n-a, ncp=lambda, lower.tail=FALSE))
HideShow
[1] 0.4579923

Here we use the above Constant values but specify a different sample size (and then a new lambda results)

HideShow
# Variables
(n <- 25)
HideShow
[1] 25
HideShow
# Constant Conditional on the situation (i.e., Conditional based on n)
(lambda <- n*sum(Treatment_Effects^2)/Supposed_Within_Group_SD^2)
HideShow
[1] 12.5
HideShow
(CV <- qf(.95, df1=a-1, df2=a*n-a))
HideShow
[1] 3.123907
HideShow
(power <- pf(CV, df1=a-1, df2=a*n-a, ncp=lambda, lower.tail=FALSE))
HideShow
[1] 0.8827749

Here we use the above Constant values but specify a different sample size (and then a new lambda results)

HideShow
# Variables
(n <- 20)
HideShow
[1] 20
HideShow
# Constant Conditional on the situation (i.e., Conditional based on n)
(lambda <- n*sum(Treatment_Effects^2)/Supposed_Within_Group_SD^2)
HideShow
[1] 10
HideShow
(CV <- qf(.95, df1=a-1, df2=a*n-a))
HideShow
[1] 3.158843
HideShow
(power <- pf(CV, df1=a-1, df2=a*n-a, ncp=lambda, lower.tail=FALSE))
HideShow
[1] 0.7933118

Trying to hone in on power of .80, we try n=21, which is the smallest sample size that satisfies desired power.

HideShow
# Variables
(n <- 21)
HideShow
[1] 21
HideShow
# Constant Conditional on the situation (i.e., Conditional based on n)
(lambda <- n*sum(Treatment_Effects^2)/Supposed_Within_Group_SD^2)
HideShow
[1] 10.5
HideShow
(CV <- qf(.95, df1=a-1, df2=a*n-a))
HideShow
[1] 3.150411
HideShow
(power <- pf(CV, df1=a-1, df2=a*n-a, ncp=lambda, lower.tail=FALSE))
HideShow
[1] 0.8147697
Power analysis with the pwr package

Rather than planning sample size as above based on the definitional forms and noncentral distributions directly, the pwr package (loaded with the other packages above) can be used as follows.

HideShow
# Returns exact power based on fractional sample sizes.
pwr.anova.test(k=3, f=f, sig.level=.05, power=.80)
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 3
              n = 20.30205
              f = 0.4082483
      sig.level = 0.05
          power = 0.8

NOTE: n is number in each group
HideShow
# Here we "round up" by using the ceiling function to get
# the necessary per-group sample size.
ceiling(pwr.anova.test(k=3, f=f, sig.level=.05, power=.80)$n)
HideShow
[1] 21

Using the Brown and Miller results, we can plan with the median-unbiased estimate of ff, or with a one-sided lower confidence bound (book p. 139).

HideShow
median_f(F_value = 6.612, df_1 = 1, df_2 = 24, N = 26)
HideShow
[1] 0.4988501
HideShow
ci_srsnr(F_value = 6.612, df_1 = 1, df_2 = 24, N = 26,
         alpha_lower = 0.20, alpha_upper = 0)
term value
ci_lower 0.323
ci_upper Inf

Confidence level: 80% (one-sided: the lower limit is the 80% lower confidence bound, with tail area 0.2 below it and none above the upper limit)

HideShow
ci_srsnr(F_value = 6.612, df_1 = 1, df_2 = 24, N = 26,
         alpha_lower = 0.3333, alpha_upper = 0)
term value
ci_lower 0.409
ci_upper Inf

Confidence level: 66.67% (one-sided: the lower limit is the 66.67% lower confidence bound, with tail area 0.3333 below it and none above the upper limit)

HideShow
#> About 0.499 for the median-unbiased estimate, with lower bounds of
#> 0.323 and 0.409 at 80% and 66.7% confidence, respectively.

# Using the book’s rounded median-unbiased estimate for planning:
pwr.anova.test(k=2, f=.4988, sig.level=.05, power=.80)
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 2
              n = 16.79008
              f = 0.4988
      sig.level = 0.05
          power = 0.8

NOTE: n is number in each group
HideShow
#> n = 16.79, so 17 per group (N = 34) — matches book p. 139

# Using the 80% single-sided confidence interval limits.
pwr.anova.test(k=2, f=.3230, sig.level=.05, power=.80)
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 2
              n = 38.60018
              f = 0.323
      sig.level = 0.05
          power = 0.8

NOTE: n is number in each group
HideShow
#> n = 38.60, so 39 per group — matches book p. 139

# Using the 66.66% single-sided confidence interval limits.
pwr.anova.test(k=2, f=.4088, sig.level=.05, power=.80)
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 2
              n = 24.48155
              f = 0.4088
      sig.level = 0.05
          power = 0.8

NOTE: n is number in each group
HideShow
#> n = 24.48, so 25 per group — matches book p. 139

To evaluate power at a given sample size for supposed population value, we can also use the pwr.anova.test() function, but now specifying sample size instead of (desired) power. The 17 participants per group that the median effect size called for would, if the population effect were really the 80% lower limit of f=.3230f = .3230, deliver much less power than the .80 that was planned for.

HideShow
pwr.anova.test(k=2, n=17, f=.3230, sig.level=.05)
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 2
              n = 17
              f = 0.323
      sig.level = 0.05
          power = 0.4471123

NOTE: n is number in each group
HideShow
#> power = .447 — matches book p. 139
The same plan three ways: base R, pwr, and DMAR

Take a medium effect for three groups, Cohen’s f=0.25f = 0.25, and ask for 80% power at α=.05\alpha = .05. All three routes below are the same noncentral-FF calculation; they differ only in what they ask the computer to solve for, and in how they round to whole participants. Base R first, by stepping the total sample size until power reaches .80 exactly as earlier in this section.

HideShow
f <- 0.25
a <- 3

# Power at a given total N, straight from the noncentral F distribution.
power_at_N <- function(N_total) {
  pf(qf(.95, df1 = a - 1, df2 = N_total - a),
     df1 = a - 1, df2 = N_total - a,
     ncp = N_total * f^2, lower.tail = FALSE)
}
c(N_157 = power_at_N(157), N_158 = power_at_N(158))
HideShow
    N_157     N_158 
0.7994818 0.8021998 

So 158 in total is the smallest sample reaching .80. The pwr package solves the same equation for nn per group, which it reports as a fraction; rounding up to whole participants per group gives 53×3=15953 \times 3 = 159.

HideShow
pwr_plan <- pwr.anova.test(k = a, f = f, sig.level = .05, power = .80)
pwr_plan
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 3
              n = 52.3966
              f = 0.25
      sig.level = 0.05
          power = 0.8

NOTE: n is number in each group
HideShow
ceiling(pwr_plan$n) * a
HideShow
[1] 159

DMAR’s planners address the same two questions from the regression side, which is what makes them useful when the effect is stated as a variance accounted for rather than as ff: power (the probability of rejecting at a chosen effect size) and AIPE, accuracy in parameter estimation (the precision of the estimate). ss_power_R2() searches on the total NN, so for a fixed-effects design it returns the 158 found by hand above. Because the §3.11 material is framed in terms of Cohen’s ff, we convert via R2=f2/(1+f2)R^2 = f^2 / (1 + f^2).

HideShow
# Cohen's f -> R^2 conversion: R^2 = f^2 / (1 + f^2)
eta2 <- f^2 / (1 + f^2)
eta2
HideShow
[1] 0.05882353
HideShow
# ss_power_R2 returns the necessary total N for the F test. The predictors in
# an experiment are fixed by design rather than sampled, hence
# random_predictors = FALSE.
ss_power_R2(true_R2 = eta2, p = 2,                      # df_1 = a - 1 = 2
            alpha_level = 0.05, desired_power = 0.80,
            random_predictors = FALSE)
term value
necessary_N 158
actual_power 0.802
noncentral_f_parm 9.875
true_f2 0.062
HideShow
#> 158 — the N found by hand above; pwr's 52.40 per group is the same
#> calculation rounded differently

For accuracy in parameter estimation, suppose the anticipated population R2R^2 is .10 and the target is an expected full width of .10 for a 95% confidence interval. Set method = "analytic" to reproduce the analytical sample-size calculation. The predictor assumptions distinguish the first two plans.

HideShow
ss_aipe_R2(true_R2 = 0.10, p = 2, width = 0.10, conf_level = 0.95,
           random_predictors = TRUE, method = "analytic")
term value
necessary_N 502

For this analytical plan, check the mean full interval width by simulation at the proposed N. See ?ss_aipe_R2.

Confidence level: 95%

HideShow
#> N = 502 for random predictors.
ss_aipe_R2(true_R2 = 0.10, p = 2, width = 0.10, conf_level = 0.95,
           random_predictors = FALSE, method = "analytic")
term value
necessary_N 471

For this analytical plan, check the mean full interval width by simulation at the proposed N. See ?ss_aipe_R2.

Confidence level: 95%

HideShow
#> N = 471 for fixed predictors.

For the one-way design, plan directly for the interval on ω2\omega^2 at the same confidence level and target full width.

HideShow
ss_aipe_omega_squared(true_omega_squared = 0.10, df_effect = 2,
                      width = 0.10, conf_level = 0.95)
term value
necessary_N 473
expected_width 0.100
true_omega_squared 0.100
df_effect 2
width 0.100
conf_level 0.950

Confidence level: 95%

HideShow
#> N = 473.

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 3: Introduction to Model Comparisons: One-Way Between-Subjects Designs (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

Chapter 4: Individual Comparisons of Means

Open the separate reading

Code
Results
On this page

Chapter 4 tests individual comparisons of means: single questions about a set of group means, each posed as a contrast and each tested by comparing a full model against a restricted model that forces the contrast to zero. Every worked example in the chapter uses the hypothetical hypertension data of Table 4.1, which is chapter_4_table_1 in the AMCP package. Chapter 1 of these notes explains how to install the packages and how AMCP names its data sets.

HideShow
# Load all of the packages used.
library(dplyr)          # data manipulation
library(AMCP)           # the textbook's data sets
library(emmeans)        # estimated marginal means and contrasts of them
library(DMAR)           # design, measurement, and analysis
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables

4.4 — A Model Comparison Approach for Testing Individual Comparisons

4.4.4 — Numerical Example

The data of Table 4.1

Table 4.1 holds blood pressure readings for 20 mild hypertensives assigned to four treatments. The group codes are spelled out one at a time with case_when(), and factor() is then used only to fix the level order to the book’s, so that Drug Therapy is the reference group in every model fitted below.

HideShow
data(chapter_4_table_1)
chapter_4_table_1
HideShow
   bloodpr cond
1       84    1
2       95    1
3       93    1
4      104    1
5       81    2
6       84    2
7       92    2
8      101    2
9       80    2
10     108    2
11      98    3
12      95    3
13      86    3
14      87    3
15      94    3
16      91    4
17      78    4
18      85    4
19      80    4
20      81    4
HideShow
chapter_4_table_1 <- chapter_4_table_1 |>
  mutate(group = case_when(
    cond == 1 ~ "Drug Therapy",
    cond == 2 ~ "Biofeedback",
    cond == 3 ~ "Diet",
    cond == 4 ~ "Combination"
  )) |>
  mutate(group = factor(group,
    levels = c("Drug Therapy", "Biofeedback", "Diet", "Combination")))
Group descriptive statistics with dplyr
HideShow
Summary_4_1 <- chapter_4_table_1 |>
  group_by(group) |>
  summarize(
    mean   = mean(bloodpr),
    median = median(bloodpr),
    var    = var(bloodpr),
    sd     = sd(bloodpr),
    n      = n()
  ) |>
  as.data.frame()
# The conversion to a data frame matters for how Summary_4_1 is used later: a
# single bracketed value extracted from a data frame is a scalar, whereas the
# same extraction from a dplyr tibble returns a one-column tibble.

Summary_4_1
HideShow
         group mean median       var        sd n
1 Drug Therapy   94     94  67.33333  8.205689 4
2  Biofeedback   91     88 132.00000 11.489125 6
3         Diet   92     94  27.50000  5.244044 5
4  Combination   83     81  26.50000  5.147815 5
HideShow
#> Means 94.0, 91.0, 92.0, 83.0 and variances 67.3, 132.0, 27.5, 26.5
#> on n = 4, 6, 5, 5 — matches Table 4.1, book p. 164

The means and variances reproduce the bottom two rows of Table 4.1, and the unequal group sizes are the ones the book chose deliberately, so that the example illustrates the general case for testing comparisons.

The error term, MSWMS_W

Every test in the chapter that assumes homogeneity of variance uses the same error term, MSWMS_W. It can be built directly from the definition as the weighted mean of the within-group variances, or read off an analysis of variance table.

HideShow
# Method 1: the pooled within-group variance, straight from the definition.
MS_within <- sum(Summary_4_1$var * (Summary_4_1$n - 1)) / sum(Summary_4_1$n - 1)
MS_within
HideShow
[1] 67.375
HideShow
#> 67.375 — matches book p. 165 (the MS_W computation shown in Table 4.2)
HideShow
# Method 2: extracting the same quantity from a fitted ANOVA.
ANOVA_Object <- aov(bloodpr ~ group, data = chapter_4_table_1)
ANOVA_4_1    <- anova(ANOVA_Object)
ANOVA_4_1
HideShow
Analysis of Variance Table

Response: bloodpr
          Df  Sum Sq Mean Sq F value Pr(>F)
group      3  334.55 111.517  1.6552 0.2165
Residuals 16 1078.00  67.375               
HideShow
SS_b <- ANOVA_4_1$"Sum Sq"[1]
SS_w <- ANOVA_4_1$"Sum Sq"[2]
c(SS_b, SS_w)
HideShow
[1]  334.55 1078.00
HideShow
#> 334.55 — matches book p. 182; 1078.00 — matches book p. 165 (E_F) and p. 183

MS_b <- ANOVA_4_1$"Mean Sq"[1]
MS_w <- ANOVA_4_1$"Mean Sq"[2]
c(MS_b, MS_w)
HideShow
[1] 111.5167  67.3750
HideShow
#> MS_W = 67.375 — matches book p. 165
The omnibus test

The book notes in passing that an omnibus test of these data would return F=1.66F = 1.66, nonsignificant at the .05 level, and then sets the omnibus question aside in favor of contrasts. The omnibus FF is itself a model comparison: the full cell-means model Yij=μj+εijY_{ij} = \mu_j + \varepsilon_{ij} against the restricted model that allows only a grand mean.

HideShow
fit_grand <- lm(bloodpr ~ 1,     data = chapter_4_table_1)   # grand mean only
fit_full  <- lm(bloodpr ~ group, data = chapter_4_table_1)   # one mean per group

anova(fit_grand, fit_full)
HideShow
Analysis of Variance Table

Model 1: bloodpr ~ 1
Model 2: bloodpr ~ group
  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1     19 1412.5                           
2     16 1078.0  3    334.55 1.6552 0.2165
HideShow
#> F = 1.66 on 3 and 16 df — matches book p. 164

The same omnibus analysis as an APA-style table — sums of squares, df, MS, FF, pp, and the proportion of total variability associated with the group effect. The table is built with gt from the anova() output rather than from a tidying helper, which keeps the chapter’s dependency stack to the packages it actually needs. The last column is R2=SSB/SSTotalR^2 = SS_B/SS_{Total} of the book’s Equation 4.45 (p. 182), which in a one-way design is also what software labels partial η2\eta^2.

HideShow
anova_table <- data.frame(
  Source = c("Between (Treatment)", "Within (Error)"),
  SS     = ANOVA_4_1$"Sum Sq",
  df     = ANOVA_4_1$"Df",
  MS     = ANOVA_4_1$"Mean Sq",
  Fstat  = ANOVA_4_1$"F value",
  p      = ANOVA_4_1$"Pr(>F)",
  R2     = c(SS_b / (SS_b + SS_w), NA_real_)
)

anova_table |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = R2, decimals = 3) |>
  fmt_number(columns = p,  decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"), R2 = md("*R*<sup>2</sup>")) |>
  tab_header(title = md("**Omnibus analysis of variance for the Table 4.1 blood pressure data**")) |>
  cols_align(align = "center", columns = -Source)
Omnibus analysis of variance for the Table 4.1 blood pressure data
Source SS df MS F p R2
Between (Treatment) 334.55 3 111.52 1.66 0.2165 0.237
Within (Error) 1,078.00 16 67.38


modelsummary places the restricted and full models side by side, with the fit statistics at the foot:

HideShow
modelsummary(
  list("Restricted (grand mean)" = fit_grand, "Full (group means)" = fit_full),
  estimate  = "{estimate}",
  statistic = "({std.error})",   # standard errors in parentheses, APA style
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  stars     = TRUE,
  output    = "gt"
)
Restricted (grand mean) Full (group means)
(Intercept) 89.850 94.000
(1.928) (4.104)
groupBiofeedback -3.000
(5.298)
groupDiet -2.000
(5.506)
groupCombination -11.000
(5.506)
Num.Obs. 20 20
AIC 145.9 146.5
BIC 147.9 151.5
Log.Lik. -70.953 -68.250
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

The same two models as a gtsummary table, each under its own spanning header. The full model adds the three group-difference terms — each treatment relative to Drug Therapy, the first level of group — that the restricted model leaves out:

HideShow
t_restricted <- tbl_regression(fit_grand, intercept = TRUE)
t_full       <- tbl_regression(fit_full,  intercept = TRUE)
# quiet = TRUE: the two models have different numbers of coefficient rows, which
# is expected here (the full model adds the group terms).
tbl_merge(list(t_restricted, t_full),
          tab_spanner = c("**Restricted (grand mean)**", "**Full (group means)**"),
          quiet = TRUE)
Characteristic
Restricted (grand mean)
Full (group means)
Beta 95% CI p-value Beta 95% CI p-value
(Intercept) 90 86, 94 <0.001 94 85, 103 <0.001
group





    Drug Therapy


— —
    Biofeedback


-3.0 -14, 8.2 0.6
    Diet


-2.0 -14, 9.7 0.7
    Combination


-11 -23, 0.67 0.063
Abbreviation: CI = Confidence Interval
Testing the pairwise comparison of Table 4.2

The hypothesis the book tests is whether drug therapy and biofeedback are equally effective, H0:μ1=μ2H_0\!: \mu_1 = \mu_2. Table 4.2 (p. 165) shows two equivalent routes to it, and two further routes are added here. All four use only base R.

Approach 1: the definitional formulas of Equation 4.12 (p. 162). Although this approach does not take advantage of some features of R and packages, it is useful to see the analysis in this way, as it corresponds with the book and allows one to more fully investigate aspects of data that might be missed using a more automated approach.

HideShow
# Corresponds to the lower half of Table 4.2 in the book.

# For ease, separate the data into their corresponding groups
# (so that the summary statistics can be used).
Group_1 <- chapter_4_table_1[chapter_4_table_1$cond == 1, "bloodpr"]
Group_2 <- chapter_4_table_1[chapter_4_table_1$cond == 2, "bloodpr"]
Group_3 <- chapter_4_table_1[chapter_4_table_1$cond == 3, "bloodpr"]
Group_4 <- chapter_4_table_1[chapter_4_table_1$cond == 4, "bloodpr"]

# Descriptive statistics.
Y_bar1 <- mean(Group_1); s2_1 <- var(Group_1); n_1 <- length(Group_1)
Y_bar2 <- mean(Group_2); s2_2 <- var(Group_2); n_2 <- length(Group_2)
Y_bar3 <- mean(Group_3); s2_3 <- var(Group_3); n_3 <- length(Group_3)
Y_bar4 <- mean(Group_4); s2_4 <- var(Group_4); n_4 <- length(Group_4)

# Under the restricted model groups 1 and 2 share one mean, Y-bar-star.
Y_bar_Star <- mean(c(Group_1, Group_2))
Y_bar_Star
HideShow
[1] 92.2
HideShow
#> 92.2 — matches book p. 165

N <- nrow(chapter_4_table_1)
a <- length(unique(chapter_4_table_1$cond))

# Model comparisons.
df_R <- N - (a - 1)
df_F <- N - a
c(df_R, df_F)
HideShow
[1] 17 16
HideShow
#> 17 and 16 — matches book p. 165

E_F <- sum((Group_1 - Y_bar1)^2) + sum((Group_2 - Y_bar2)^2) +
  sum((Group_3 - Y_bar3)^2) + sum((Group_4 - Y_bar4)^2)
E_F
HideShow
[1] 1078
HideShow
#> 1078.00 — matches book p. 165

E_R <- sum((Group_1 - Y_bar_Star)^2) + sum((Group_2 - Y_bar_Star)^2) +
  sum((Group_3 - Y_bar3)^2) + sum((Group_4 - Y_bar4)^2)
E_R
HideShow
[1] 1099.6
HideShow
#> 1099.60 — matches book p. 165

# The four component sums the book prints on the way to E_R.
c(sum((Group_1 - Y_bar_Star)^2), sum((Group_2 - Y_bar_Star)^2),
  sum((Group_3 - Y_bar3)^2),     sum((Group_4 - Y_bar4)^2))
HideShow
[1] 214.96 668.64 110.00 106.00
HideShow
#> 214.96, 668.64, 110.00, 106.00 — matches book p. 165

# Named F_obs rather than F: R reads a bare `F` as an abbreviation for FALSE,
# so assigning to it would mask the built-in constant for the rest of the session.
F_obs <- ((E_R - E_F) / (df_R - df_F)) / (E_F / df_F)
F_obs
HideShow
[1] 0.3205937
HideShow
#> 0.32 — matches book p. 165 (Table 4.2)

# A single contrast is tested against an F with df_R - df_F = 1 numerator df and
# df_F = N - a = 16 denominator df (the book, p. 164, reports "1 and 16 degrees
# of freedom"), not against the omnibus F(a - 1, N - 1).
1 - pf(F_obs, df_R - df_F, df_F)
HideShow
[1] 0.579107
HideShow
#> .579 — matches Table 4.4, book p. 177

qf(0.95, 1, N - a)
HideShow
[1] 4.493998
HideShow
#> 4.49 — matches the critical value quoted on book p. 164

Approach 2: Equation 4.18 (p. 163), the computationally simpler form available whenever the comparison is pairwise.

HideShow
F_obs <- ((n_1 * n_2) * (Y_bar1 - Y_bar2)^2) / ((n_1 + n_2) * MS_w)
F_obs
HideShow
[1] 0.3205937
HideShow
#> 0.32 — matches book p. 165 (upper half of Table 4.2)
1 - pf(F_obs, 1, N - a)
HideShow
[1] 0.579107

Approach 3: the restricted model read off the dplyr summary table. Some of the values from above are repeated here for completeness. Note that the way objects are extracted from the summary table Summary_4_1 requires the conversion of the dplyr tibble to a data frame (see the descriptive-statistics chunk above).

HideShow
Y_bar_star <- mean(chapter_4_table_1[chapter_4_table_1$group %in%
                                       c("Drug Therapy", "Biofeedback"),
                                     "bloodpr"])

E_R <- sum((chapter_4_table_1[chapter_4_table_1$group %in%
                                c("Drug Therapy", "Biofeedback"),
                              "bloodpr"] - Y_bar_star)^2) +
  sum((chapter_4_table_1[chapter_4_table_1$group == "Diet", "bloodpr"] -
         Summary_4_1[Summary_4_1$group == "Diet", "mean"])^2) +
  sum((chapter_4_table_1[chapter_4_table_1$group == "Combination", "bloodpr"] -
         Summary_4_1[Summary_4_1$group == "Combination", "mean"])^2)

# From the previously performed ANOVA.
E_F <- SS_w

F_obs <- ((E_R - E_F) / (df_R - df_F)) / (E_F / df_F)
c(E_R, E_F, F_obs)
HideShow
[1] 1099.6000000 1078.0000000    0.3205937
HideShow
#> 1099.60, 1078.00, 0.32 — matches book p. 165

# Same single-contrast reference distribution as above: F(1, N - a) = F(1, 16).
1 - pf(F_obs, df_R - df_F, df_F)
HideShow
[1] 0.579107

Approach 4: c-weights, Equation 4.32 (p. 170), with the mean square within obtained earlier from the ANOVA. Equation 4.32 is developed in §4.5 for contrasts in general; applied to a pairwise contrast it returns the Table 4.2 result.

HideShow
c_weights <- c(1, -1, 0, 0)
Ybar      <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
n         <- c(n_1, n_2, n_3, n_4)

Psi <- sum(c_weights * Ybar)
Psi
HideShow
[1] 3
HideShow
#> psi-hat = 3.00 — matches Table 4.4, book p. 177

F_obs <- (Psi^2 / sum(c_weights^2 / n)) / MS_w
F_obs
HideShow
[1] 0.3205937
HideShow
#> 0.32 — matches book p. 165 (Table 4.2)

# A contrast carries 1 numerator df, tested against F(1, N - a) = F(1, 16).
1 - pf(F_obs, 1, N - a)
HideShow
[1] 0.579107
The same comparison as an explicit model comparison

The book’s point is that a contrast is a comparison of two models, so it is worth fitting both models and handing them to anova(). The restricted model that forces μ1=μ2\mu_1 = \mu_2 is simply the cell-means model with groups 1 and 2 collapsed into one level, and anova() then reports ERE_R, EFE_F, their difference, and the FF of Table 4.2 in one line.

HideShow
chapter_4_table_1 <- chapter_4_table_1 |>
  mutate(group_R = case_when(
    cond %in% c(1, 2) ~ "Drug Therapy or Biofeedback",
    cond == 3         ~ "Diet",
    cond == 4         ~ "Combination"
  ))

fit_full_cells <- lm(bloodpr ~ group   - 1, data = chapter_4_table_1)
fit_restricted <- lm(bloodpr ~ group_R - 1, data = chapter_4_table_1)

anova(fit_restricted, fit_full_cells)
HideShow
Analysis of Variance Table

Model 1: bloodpr ~ group_R - 1
Model 2: bloodpr ~ group - 1
  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1     17 1099.6                           
2     16 1078.0  1      21.6 0.3206 0.5791
HideShow
#> RSS 1099.60 and 1078.00, SS = 21.60, F = 0.32, p = .579
#> — matches book p. 165 (Table 4.2) and Table 4.4, book p. 177
The same comparison with emmeans

emmeans is the mainstream route to contrasts of fitted means, and it reproduces the “assumes equal variances” half of the book’s Table 4.4 (p. 177) directly: the value of the contrast, its standard error, tt, its degrees of freedom, and the two-tailed pp value. Squaring tt returns the FF of Table 4.2, exactly as the book notes on p. 177.

HideShow
emm_groups <- emmeans(fit_full, specs = "group")
emm_groups
HideShow
 group        emmean   SE df lower.CL upper.CL
 Drug Therapy     94 4.10 16     85.3    102.7
 Biofeedback      91 3.35 16     83.9     98.1
 Diet             92 3.67 16     84.2     99.8
 Combination      83 3.67 16     75.2     90.8

Confidence level used: 0.95 
HideShow
contrast_pairwise <- contrast(emm_groups,
  method = list("Drug Therapy vs. Biofeedback" = c(1, -1, 0, 0)),
  adjust = "none")
contrast_pairwise
HideShow
 contrast                     estimate  SE df t.ratio p.value
 Drug Therapy vs. Biofeedback        3 5.3 16   0.566  0.5791
HideShow
# The same result at full precision, so the standard error can be read against
# the book's.
as.data.frame(contrast_pairwise)
HideShow
 contrast                     estimate       SE df t.ratio p.value
 Drug Therapy vs. Biofeedback        3 5.298388 16   0.566  0.5791
HideShow
#> estimate 3.00, SE 5.298, df 16, t = 0.566, p = .579
#> — matches Table 4.4, book p. 177

summary(contrast_pairwise)$t.ratio^2
HideShow
[1] 0.3205937
HideShow
#> 0.32 — the F of Table 4.2 (book p. 165), as noted on book p. 177
A standardized contrast and its interval in DMAR

The tests above answer only whether the contrast differs from zero. DMAR’s ci_sc() adds what none of them gives: a confidence interval on the standardized contrast, built by inverting the noncentral tt distribution. The interval includes zero, consistent with the nonsignificant FF above; the point estimate is the standardized difference the book reports in §4.8.1.2.

HideShow
Ybar_groups <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
n_groups    <- c(n_1, n_2, n_3, n_4)

ci_sc(
  means       = Ybar_groups,
  s_anova     = sqrt(MS_w),
  c_weights   = c(1, -1, 0, 0),
  n_per_group = n_groups,
  N           = sum(n_groups),
  conf_level  = 0.95
)
term value
ci_lower -0.911
std_contrast 0.365
ci_upper 1.631

Confidence level: 95%

HideShow
#> standardized contrast 0.365 — matches the 0.37 on book p. 181

4.5 — Complex Comparisons

4.5.2 — Numerical Example

The complex comparison of Table 4.3

The contrast of interest is now the combined treatment against the average of the other three. Other than the c-weights, the code is the same as for the pairwise contrast.

HideShow
# Corresponds to the upper half of Table 4.3.

c_weights <- c(1/3, 1/3, 1/3, -1)
Ybar      <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
n         <- c(n_1, n_2, n_3, n_4)

Psi <- sum(c_weights * Ybar)
Psi
HideShow
[1] 9.333333
HideShow
#> 9.33 — the contrast Table 4.3 writes as (92.33 - 83), book p. 171; the
#> value 9.33 itself is printed on p. 180

sum(c_weights^2 / n)
HideShow
[1] 0.2685185
HideShow
#> 0.2685 — matches book p. 171 (Table 4.3)

F_obs <- (Psi^2 / sum(c_weights^2 / n)) / MS_w
F_obs
HideShow
[1] 4.815047
HideShow
#> 4.82 — matches book p. 171 (Table 4.3)

# Like every single contrast, this one is tested against F(1, N - a) = F(1, 16).
# The book (p. 171) notes F = 4.82 exceeds the critical value of 4.49 for 1 and
# 16 df, so the complex comparison is significant; testing against F(a - 1, N - 1)
# would use the wrong reference distribution.
1 - pf(F_obs, 1, N - a)
HideShow
[1] 0.04332063
HideShow
#> .043 — matches Table 4.4, book p. 177
The complex comparison as an explicit model comparison

The lower half of Table 4.3 works the same contrast through Equation 4.12, and the book remarks that the least squares estimates under the restricted model are tedious to find by hand. They are not tedious for lm(). The restriction 13(μ1+μ2+μ3)−μ4=0\tfrac{1}{3}(\mu_1 + \mu_2 + \mu_3) - \mu_4 = 0 says μ4=13(μ1+μ2+μ3)\mu_4 = \tfrac{1}{3}(\mu_1 + \mu_2 + \mu_3); substituting that into the cell-means model leaves three free parameters, whose predictors are the group-1, group-2, and group-3 indicators each plus one third of the group-4 indicator.

HideShow
X_cells <- model.matrix(~ group - 1, data = chapter_4_table_1)

chapter_4_table_1$x1 <- X_cells[, 1] + X_cells[, 4] / 3
chapter_4_table_1$x2 <- X_cells[, 2] + X_cells[, 4] / 3
chapter_4_table_1$x3 <- X_cells[, 3] + X_cells[, 4] / 3

fit_restricted_complex <- lm(bloodpr ~ x1 + x2 + x3 - 1, data = chapter_4_table_1)

# The three coefficients are mu-hat 1 to 3 under the restriction, and the fourth
# mean is their average.
mu_restricted <- unname(c(coef(fit_restricted_complex),
                          mean(coef(fit_restricted_complex))))
round(mu_restricted, 3)
HideShow
[1] 91.103 89.069 89.683 89.952
HideShow
#> 91.103, 89.069, 89.683, 89.952 — matches book p. 172

sum(c(1/3, 1/3, 1/3, -1) * mu_restricted)
HideShow
[1] 0
HideShow
#> zero, to within floating-point rounding: the restriction the book checks
#>   on p. 172

anova(fit_restricted_complex, fit_full_cells)
HideShow
Analysis of Variance Table

Model 1: bloodpr ~ x1 + x2 + x3 - 1
Model 2: bloodpr ~ group - 1
  Res.Df    RSS Df Sum of Sq     F  Pr(>F)  
1     17 1402.4                             
2     16 1078.0  1    324.41 4.815 0.04332 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> E_R = 1402.41, E_F = 1078.00, SS = 324.41, F = 4.82, p = .043
#> — matches book p. 171 (Table 4.3); the book's 1402.43 is the sum of its own
#>   rounded component sums (235.57 + 682.37 + 136.84 + 347.65)
The same complex comparison with emmeans

The book’s Table 4.4 enters this contrast with the whole-number weights 1, 1, 1, −3-3, which multiply both the contrast and its standard error by three. Entering both weightings in emmeans shows that tt, the degrees of freedom, and pp are unchanged, while only the scale of the estimate moves.

HideShow
contrast_complex <- contrast(emm_groups,
  method = list(
    "Combination vs. others (1, 1, 1, -3)"       = c(1, 1, 1, -3),
    "Combination vs. others (1/3, 1/3, 1/3, -1)" = c(1/3, 1/3, 1/3, -1)
  ),
  adjust = "none")
contrast_complex
HideShow
 contrast                                   estimate    SE df t.ratio p.value
 Combination vs. others (1, 1, 1, -3)          28.00 12.80 16   2.194  0.0433
 Combination vs. others (1/3, 1/3, 1/3, -1)     9.33  4.25 16   2.194  0.0433
HideShow
as.data.frame(contrast_complex)
HideShow
 contrast                                    estimate        SE df t.ratio
 Combination vs. others (1, 1, 1, -3)       28.000000 12.760208 16   2.194
 Combination vs. others (1/3, 1/3, 1/3, -1)  9.333333  4.253403 16   2.194
 p.value
  0.0433
  0.0433
HideShow
#> 28.00 with SE 12.760, t = 2.194 on 16 df, p = .043 — matches Table 4.4,
#> book p. 177. The second row (9.33 with SE 4.253) is the same contrast
#> rescaled by 1/3 as explained above, and is not itself in the book; the
#> t, df, and p are unchanged by the rescaling, which is the point.
Confidence intervals for the complex contrast in DMAR

DMAR’s ci_c() and ci_sc() add intervals on the raw and the standardized contrast. Both exclude zero, consistent with the significant FF.

HideShow
c_complex <- c(1/3, 1/3, 1/3, -1)

# Raw (unstandardized) contrast, in mm Hg:
ci_c(
  means       = Ybar_groups,
  s_anova     = sqrt(MS_w),
  c_weights   = c_complex,
  n_per_group = n_groups,
  N           = sum(n_groups),
  conf_level  = 0.95
)
term value
ci_lower 0.317
contrast 9.333
ci_upper 18.350

Confidence level: 95%

HideShow
#> 9.33, with limits 0.317 and 18.350 — matches the 9.33 +/- 9.01 on book p. 180

# Standardized contrast (psi / sigma):
ci_sc(
  means       = Ybar_groups,
  s_anova     = sqrt(MS_w),
  c_weights   = c_complex,
  n_per_group = n_groups,
  N           = sum(n_groups),
  conf_level  = 0.95
)
term value
ci_lower 0.033
std_contrast 1.137
ci_upper 2.210

Confidence level: 95%

HideShow
#> standardized contrast 1.137 — matches the 1.14 on book p. 181

4.7 — Unequal Population Variances

4.7.1 — Numerical Example

Separate-variance tests of both contrasts

Here we do not assume homogeneity of variance for a contrast. We repeat some of the code from above for completeness. Note that the way we write the code, which matches how it is displayed in the book, is due to R’s “vectorized arithmetic” (and thus making the equations in the R code mimic those in the book). Equation 4.33 (p. 174) supplies the denominator and Equation 4.34 (p. 174) the Satterthwaite degrees of freedom. The two contrasts are the ones in the lower half of the book’s Table 4.4.

HideShow
Ybar <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
s2   <- c(s2_1, s2_2, s2_3, s2_4)
n    <- c(n_1, n_2, n_3, n_4)

# Contrast 1: the pairwise comparison.
c1       <- c(1, -1, 0, 0)
Psi1     <- sum(Ybar * c1)
var_Psi1 <- sum((c1^2 / n) * s2)
F1       <- Psi1^2 / var_Psi1
df1      <- sum(c1^2 * s2 / n)^2 / sum((c1^2 * s2 / n)^2 / (n - 1))

c(Psi1, sqrt(var_Psi1), sqrt(F1), df1)
HideShow
[1] 3.0000000 6.2316397 0.4814142 7.8849599
HideShow
#> 3.00, SE 6.232, t = 0.481, df 7.885 — matches Table 4.4, book p. 177
1 - pf(F1, 1, df1)
HideShow
[1] 0.6432981
HideShow
#> .643 — matches Table 4.4, book p. 177

# Contrast 2: the complex comparison.
# Notice we use fractional c-weights, whereas the book uses whole numbers; the
# scale of the weights cancels out of F and out of the degrees of freedom.
c2       <- c(1/3, 1/3, 1/3, -1)
Psi2     <- sum(Ybar * c2)
var_Psi2 <- sum((c2^2 / n) * s2)
F2       <- Psi2^2 / var_Psi2
df2      <- sum(c2^2 * s2 / n)^2 / sum((c2^2 * s2 / n)^2 / (n - 1))

c(Psi2 * 3, sqrt(var_Psi2) * 3, sqrt(F2), df2)
HideShow
[1] 28.000000  9.593401  2.918673 11.034012
HideShow
#> 28.00, SE 9.593, t = 2.919, df 11.034 — matches Table 4.4, book p. 177
1 - pf(F2, 1, df2)
HideShow
[1] 0.01392933
HideShow
#> .014 — matches Table 4.4, book p. 177

The pairwise comparison stays nonsignificant and loses both tt and degrees of freedom, while the complex comparison becomes more significant, its tt rising from 2.19 to 2.92. The book explains why on pp. 177–178: the complex contrast puts the largest weight on group 4, which has the smallest variance in these data, so the separate-variance denominator is smaller than MSWMS_W here. The approach is not uniformly more conservative; only its denominator degrees of freedom necessarily are.

The pairwise case in base R: Welch’s tt test

When the contrast is pairwise, the separate-variance test is exactly Welch’s two-sample tt test, so base R gives it with no hand computation at all. The arguments are spelled out rather than left to defaults, so the call documents the analyst’s choices.

HideShow
drug <- chapter_4_table_1[chapter_4_table_1$cond == 1, "bloodpr"]
bio  <- chapter_4_table_1[chapter_4_table_1$cond == 2, "bloodpr"]

t.test(
  x           = drug,
  y           = bio,
  alternative = "two.sided",
  paired      = FALSE,
  var.equal   = FALSE,
  conf.level  = 0.95
)
HideShow

    Welch Two Sample t-test

data:  drug and bio
t = 0.48141, df = 7.885, p-value = 0.6433
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -11.40676  17.40676
sample estimates:
mean of x mean of y 
       94        91 
HideShow
#> t = 0.48141, df = 7.885, p = .6433 — matches Table 4.4, book p. 177
The same Welch test in DMAR

DMAR’s welch_t() returns the identical test as a tidy data.frame rather than as a printed htest object, which is what it adds: the result composes with dplyr when many such tests are collected into one table, and it reports the two group standard deviations and sample sizes alongside the test.

HideShow
welch_t(x = drug, y = bio, conf_level = 0.95)
term value
mean_difference 3.000
t_value 0.481
df 7.885
p_value 0.6433
ci_lower -11.407
ci_upper 17.407
mean_x 94.000
mean_y 91.000
sd_x 8.206
sd_y 11.489
n_x 4
n_y 6

Confidence level: 95%

HideShow
#> t = 0.481 on df 7.885, p = .6433 — the same numbers as t.test() above
#>   and as Table 4.4, book p. 177

4.8 — Measures of Effect

4.8.1 — Measures of Effect Size

4.8.1.1 — Confidence Intervals
The intervals by hand from Equations 4.40 and 4.41

Equation 4.40 (p. 179) builds the interval from the contrast, the critical FF, and the standard error of the contrast under homogeneity of variance. The book works both intervals this way on p. 180 from the Table 4.4 output.

HideShow
F_crit   <- qf(0.95, 1, N - a)
se_Psi1  <- sqrt(MS_w * sum(c1^2 / n))
se_Psi2  <- sqrt(MS_w * sum(c2^2 / n))

c(se_Psi1, se_Psi2 * 3)
HideShow
[1]  5.298388 12.760208
HideShow
#> 5.298 and 12.760 — matches Table 4.4, book p. 177

# Pairwise comparison.
c(Psi1, sqrt(F_crit) * se_Psi1)
HideShow
[1]  3.00000 11.23208
HideShow
#> 3.00 +/- 11.23 — matches book p. 180
Psi1 + c(-1, 1) * sqrt(F_crit) * se_Psi1
HideShow
[1] -8.232081 14.232081
HideShow
#> -8.23 to 14.23 — matches book p. 180

# Complex comparison, in the metric in which the coefficients sum in absolute
# value to 2, which is what makes the interval a difference between means.
c(Psi2, sqrt(F_crit) * se_Psi2)
HideShow
[1] 9.333333 9.016811
HideShow
#> 9.33 +/- 9.01 — matches book p. 180
Psi2 + c(-1, 1) * sqrt(F_crit) * se_Psi2
HideShow
[1]  0.3165222 18.3501444
HideShow
#> 0.32 to 18.35 — matches the 0.32 to 18.34 on book p. 180, which the book
#>   obtains by adding its rounded 9.33 and 9.01

Equation 4.41 (p. 179) relaxes homogeneity of variance by replacing the error term with the separate-variance denominator and the degrees of freedom with the Satterthwaite value. The book is deliberately slightly conservative on p. 180, using 7 denominator degrees of freedom for the pairwise contrast instead of 7.885.

HideShow
# Pairwise comparison, with the book's conservative 7 df.
sqrt(qf(0.95, 1, 7)) * sqrt(var_Psi1)
HideShow
[1] 14.73549
HideShow
#> half-width 14.73, so 3.0 +/- 14.73 — matches book p. 180

# Complex comparison, at the Satterthwaite df of 11.034.
sqrt(qf(0.95, 1, df2)) * sqrt(var_Psi2)
HideShow
[1] 7.035665
HideShow
#> half-width 7.04, so 9.33 +/- 7.04 — matches book p. 180
Confidence intervals for contrasts in DMAR

DMAR’s ci_c() computes the two equal-variance intervals directly from the group summaries.

HideShow
groups <- split(chapter_4_table_1$bloodpr, chapter_4_table_1$cond)
Y_bar  <- sapply(groups, mean)
n      <- sapply(groups, length)

ci_c(
  means       = Y_bar,
  c_weights   = c(1, -1, 0, 0),
  n_per_group = n,
  N           = N,
  s_anova     = sqrt(MS_w),
  conf_level  = 0.95
)
term value
ci_lower -8.232
contrast 3.000
ci_upper 14.232

Confidence level: 95%

HideShow
#> -8.232 to 14.232 — matches book p. 180

ci_c(
  means       = Y_bar,
  c_weights   = c(1/3, 1/3, 1/3, -1),
  n_per_group = n,
  N           = N,
  s_anova     = sqrt(MS_w),
  conf_level  = 0.95
)
term value
ci_lower 0.317
contrast 9.333
ci_upper 18.350

Confidence level: 95%

HideShow
#> 0.317 to 18.350 — book p. 180 reports 0.32 and 18.34 using rounded components
4.8.1.2 — Standardized Difference
Equation 4.44 by hand

Equation 4.44 (p. 181) standardizes a contrast by MSW\sqrt{MS_W}, with the factor 2/∑j|cj|2 / \sum_j |c_j| that keeps the result a difference between means however the coefficients happen to be scaled.

HideShow
d_pairwise <- 2 * Psi1 / (sqrt(MS_w) * sum(abs(c1)))
d_pairwise
HideShow
[1] 0.3654869
HideShow
#> 0.37 — matches book p. 181

d_complex <- 2 * Psi2 / (sqrt(MS_w) * sum(abs(c2)))
d_complex
HideShow
[1] 1.13707
HideShow
#> 1.14 — matches book p. 181
Confidence intervals for standardized contrasts

DMAR’s ci_sc() inverts the noncentral tt distribution to give a confidence interval on the standardized scale.

HideShow
ci_sc(
  means       = Y_bar,
  c_weights   = c(1, -1, 0, 0),
  n_per_group = n,
  N           = N,
  s_anova     = sqrt(MS_w),
  conf_level  = 0.95
)
term value
ci_lower -0.911
std_contrast 0.365
ci_upper 1.631

Confidence level: 95%

HideShow
#> 0.365, limits -0.911 to 1.631

ci_sc(
  means       = Y_bar,
  c_weights   = c(1/3, 1/3, 1/3, -1),
  n_per_group = n,
  N           = N,
  s_anova     = sqrt(MS_w),
  conf_level  = 0.95
)
term value
ci_lower 0.033
std_contrast 1.137
ci_upper 2.210

Confidence level: 95%

HideShow
#> 1.137, limits 0.033 to 2.210

The book cautions on p. 181 against reading a verbal label off a standardized difference: the interval for the pairwise contrast includes zero, so describing that difference as “small to medium” would overstate what the data support. The intervals above are what makes that caution checkable.

Companion scales for the standardized difference in DMAR

For the pairwise comparison, DMAR translates the same standardized difference into scales an applied audience reads more easily: the proportion of superiority (U3), the common-language effect size (CLES), and the number needed to treat (NNT). Each is a function of dd, so each carries the same uncertainty, which the accompanying intervals make explicit.

HideShow
proportion_of_superiority(smd = d_pairwise, n_1 = n_1, n_2 = n_2, conf_level = 0.95)
term value
smd 0.365
proportion_of_superiority 0.643
smd_ci_lower -0.923
smd_ci_upper 1.632
ci_lower 0.178
ci_upper 0.949

Confidence level: 95%

HideShow
cles(smd = d_pairwise, n_1 = n_1, n_2 = n_2, conf_level = 0.95)
term value
smd 0.365
cles 0.602
smd_ci_lower -0.923
smd_ci_upper 1.632
cles_ci_lower 0.257
cles_ci_upper 0.876

Confidence level: 95%

HideShow
nnt_from_smd(smd = d_pairwise, n_1 = n_1, n_2 = n_2, conf_level = 0.95)
term value
smd 0.365
srd 0.204
nnt 4.904
smd_ci_lower -0.923
smd_ci_upper 1.632
nnt_ci_lower NA
nnt_ci_upper NA
srd_ci_lower -0.486
srd_ci_upper 0.751

Confidence level: 95%

The interval for the SRD includes 0, so the confidence set for the NNT is two intervals: NNT <= -2.058 (harm) or NNT >= 1.331 (benefit), joined at infinity (Altman, 1998)

4.8.2 — Measures of Association Strength

The three measures of association strength for a contrast share the numerator SS(ψ)SS(\psi) and differ in the denominator, so the sums of squares for the two contrasts are computed once here and reused.

HideShow
Y_bars <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
n      <- c(n_1, n_2, n_3, n_4)

c_weights_1 <- c(1, -1, 0, 0)
Psi_1       <- sum(c_weights_1 * Y_bars)
SS_Psi_1    <- Psi_1^2 / sum(c_weights_1^2 / n)
SS_Psi_1
HideShow
[1] 21.6
HideShow
#> 21.60 — matches book p. 182

c_weights_2 <- c(1/3, 1/3, 1/3, -1)
Psi_2       <- sum(c_weights_2 * Y_bars)
SS_Psi_2    <- Psi_2^2 / sum(c_weights_2^2 / n)
SS_Psi_2
HideShow
[1] 324.4138
HideShow
#> 324.41 — matches book p. 182
Ralerting2R^2_{\text{alerting}}

Equation 4.46 (p. 182) divides the contrast’s sum of squares by the between-group sum of squares, which says how much of the difference among the groups that one contrast has captured.

HideShow
SS_b
HideShow
[1] 334.55
HideShow
#> 334.55 — matches book p. 182

R2_alerting_1 <- SS_Psi_1 / SS_b
R2_alerting_2 <- SS_Psi_2 / SS_b
c(R2_alerting_1, R2_alerting_2)
HideShow
[1] 0.06456434 0.96970197
HideShow
#> .0646 and .9697 — matches the 6.46% and 96.97% on book p. 182

Almost all of the variability among the four groups is captured by the fact that the combined group differs from the other three. The two percentages sum to more than 100%, which the book flags on pp. 182–183 as a case where adding them is not meaningful, and takes up again in §4.10.3 below.

Reffect size2R^2_{\text{effect size}}

Equation 4.47 (p. 183) keeps the same numerator and divides instead by the total sum of squares, so it reports the share of total variability associated with the contrast.

HideShow
SS_T <- SS_b + SS_w
SS_T
HideShow
[1] 1412.55
HideShow
#> 1412.55 — matches book p. 183

R2_effect_size_1 <- SS_Psi_1 / SS_T
R2_effect_size_2 <- SS_Psi_2 / SS_T
c(R2_effect_size_1, R2_effect_size_2)
HideShow
[1] 0.01529149 0.22966535
HideShow
#> .0153 and .2297 — matches book p. 183
Rcontrast2R^2_{\text{contrast}}

Equation 4.48 (p. 184) divides by the contrast’s own sum of squares plus the within-group sum of squares, which removes the influence of groups that the contrast does not involve.

HideShow
R2_contrast_1 <- SS_Psi_1 / (SS_Psi_1 + SS_w)
R2_contrast_2 <- SS_Psi_2 / (SS_Psi_2 + SS_w)
c(R2_contrast_1, R2_contrast_2)
HideShow
[1] 0.01964351 0.23132530
HideShow
#> .0196 and .2313 — matches the 1.96% on book p. 184 and the .23 on book p. 184

The step the book takes next is to compute SSWSS_W from only the groups the contrast involves. The sum of squares for the contrast does not change with the reduction in groups, but the sum of squares within does; _12 marks the objects that concern only groups 1 and 2. As the book states, “our general preference is to base Rcontrast2R^2_{\text{contrast}} only on the groups actually involved in the comparison” (p. 184).

HideShow
ANOVA_Object_12 <- aov(bloodpr ~ group,
                       data = chapter_4_table_1[chapter_4_table_1$cond %in% c(1, 2), ])
ANOVA_4_1_12    <- anova(ANOVA_Object_12)

SS_w_12 <- ANOVA_4_1_12$"Sum Sq"[2]

R2_contrast_1_12 <- SS_Psi_1 / (SS_Psi_1 + SS_w_12)
R2_contrast_1_12
HideShow
[1] 0.02444545
HideShow
#> .0244 — matches the 2.44% on book p. 184

4.9 — Statistical Power

Power for a specific contrast

The book plans a study with 20 participants per group and the population means μ1=90\mu_1 = 90, μ2=92\mu_2 = 92, μ3=88\mu_3 = 88, μ4=81\mu_4 = 81, with σε=12\sigma_\varepsilon = 12. Equation 4.52 (p. 186) gives FpopF_{pop} for the “exemplary dataset”, and Equation 4.53 says that for a contrast the noncentrality parameter is just FpopF_{pop}, because the numerator has a single degree of freedom.

HideShow
# Population parameters.
mu_Drug  <- 90
mu_Bio   <- 92
mu_Diet  <- 88
mu_Combo <- 81
sigma    <- 12
n        <- 20

# Define the contrast weights.
c_weights <- c(1/3, 1/3, 1/3, -1)
mu_vector <- c(mu_Drug, mu_Bio, mu_Diet, mu_Combo)

# The value of the contrast in the population.
psi <- sum(c_weights * mu_vector)
psi
HideShow
[1] 9
HideShow
#> 9 — matches book p. 186

# The noncentrality parameter, Equations 4.52 and 4.53.
sum_c_squared <- sum(c_weights^2)
lambda        <- (n * psi^2) / (sum_c_squared * sigma^2)
lambda
HideShow
[1] 8.4375
HideShow
#> 8.4375 — matches book p. 186

# Degrees of freedom: numerator 1, denominator N - a = 80 - 4 = 76.
df1   <- 1
df2   <- (4 * n) - 4
alpha <- 0.05

F_crit <- qf(1 - alpha, df1, df2)
F_crit
HideShow
[1] 3.96676
HideShow
#> 3.96676 — matches book p. 187

power <- 1 - pf(F_crit, df1, df2, ncp = lambda)
power
HideShow
[1] 0.8180309
HideShow
#> 0.8180309 — matches book p. 187

The book contrasts this with the power of the omnibus test under the same population parameters, which is lower.

HideShow
sigma_m       <- sqrt(sum((mu_vector - mean(mu_vector))^2) / 4)   # Equation 3.90
f_omnibus     <- sigma_m / sigma                                  # Equation 3.91
lambda_omnibus <- (4 * n) * f_omnibus^2                           # Equation 4.49
1 - pf(qf(0.95, 3, 4 * n - 4), 3, 4 * n - 4, ncp = lambda_omnibus)
HideShow
[1] 0.7149725
HideShow
#> .715 — matches book p. 187

Equation 4.56 (p. 188) rewrites the same information as an effect size ff for the contrast, which is what power software such as G*Power or WebPower asks for.

HideShow
f_contrast <- sqrt((psi^2 / sum_c_squared) / (4 * sigma^2))
f_contrast
HideShow
[1] 0.3247595
HideShow
#> 0.3248 — matches book p. 188
The same power computation in DMAR

DMAR’s ss_power_contrast() takes the expected means, the within-group variance, and the contrast weights, and returns the power at a stated per-group sample size together with the noncentral tt parameter and the implied ff — so the three hand computations above arrive in one object. Replacing specified_n_per_group with desired_power turns the same planner around and solves for the sample size instead, which the book notes (p. 187) is the harder direction by hand because the denominator degrees of freedom depend on the answer.

HideShow
ss_power_contrast(
  c_weights             = c(1/3, 1/3, 1/3, -1),
  true_means            = mu_vector,
  true_var_error        = sigma^2,
  specified_n_per_group = n,
  alpha_level           = 0.05
)
term value
specified_n_per_group 20
total_N 80
actual_power 0.818
noncentral_t_parm 2.905
true_f 0.325
HideShow
#> actual_power 0.818 and true_f 0.325 — matches book pp. 187-188

ss_power_contrast(
  c_weights      = c(1/3, 1/3, 1/3, -1),
  true_means     = mu_vector,
  true_var_error = sigma^2,
  desired_power  = 0.80,
  alpha_level    = 0.05
)
term value
necessary_n_per_group 20
total_N 80
actual_power 0.818
noncentral_t_parm 2.905
true_f 0.325
HideShow
#> necessary_n_per_group 20 — the sample size the book adopts on p. 187
Sample size for a sufficiently narrow interval

For accuracy in parameter estimation, the book asks for 90% assurance that the full width of the 95% confidence interval is at most 5 points (half-width 2.5). DMAR’s ss_aipe_c() computes the group size for each contrast.

HideShow
ss_aipe_c(
  true_var_error = 12^2,
  c_weights      = c(0, 1, -1, 0),
  width          = 5,
  conf_level     = 0.95,
  assurance      = 0.90
)
term value
necessary_n_per_group 190

Confidence level: 95%

HideShow
#> 190 per group — 760 in total, as on book p. 188

ss_aipe_c(
  true_var_error = 12^2,
  c_weights      = c(1/3, 1/3, 1/3, -1),
  width          = 5,
  conf_level     = 0.95,
  assurance      = 0.90
)
term value
necessary_n_per_group 129

Confidence level: 95%

HideShow
#> 129 per group — 516 in total, as on book p. 189

4.10 — Testing More Than One Contrast

4.10.3 — Orthogonality of Contrasts

Checking orthogonality in base R

Equation 4.61 (p. 191) defines two contrasts as orthogonal, with equal sample sizes, when the sum of the products of their coefficients is zero. Here we define a matrix in which the rows represent contrasts of interest, for a=3a = 3 and two contrasts. These are the ψ1\psi_1 and ψ2\psi_2 of the book’s Equation 4.60.

HideShow
C_Matrix <- rbind(Psi1 = c(1, -1, 0), Psi2 = c(1, 0, -1))

# First, verify that the sum of the c-weights is zero (it is below, continue).
apply(C_Matrix, MARGIN = 1, FUN = sum)
HideShow
Psi1 Psi2 
   0    0 
HideShow
# Check if the sum of the products of c-weights is zero (it is not below;
# these are nonorthogonal contrasts).
sum(C_Matrix["Psi1", ] * C_Matrix["Psi2", ])
HideShow
[1] 1
HideShow
#> 1 — matches book p. 191, where (1)(1) + (-1)(0) + (0)(-1) = 1

Replacing ψ2\psi_2 with the book’s ψ3=12(μ1+μ2)−μ3\psi_3 = \tfrac{1}{2}(\mu_1 + \mu_2) - \mu_3 gives an orthogonal pair instead.

HideShow
C_Matrix2 <- rbind(Psi1 = c(1, -1, 0), Psi3 = c(1/2, 1/2, -1))

# First, verify that the sum of the c-weights is zero.
apply(C_Matrix2, MARGIN = 1, FUN = sum)
HideShow
Psi1 Psi3 
   0    0 
HideShow
# Check if the sum of the products of c-weights is zero (it is below; these are
# orthogonal contrasts).
sum(C_Matrix2["Psi1", ] * C_Matrix2["Psi3", ])
HideShow
[1] 0
HideShow
#> 0 — matches book p. 192, where (1)(1/2) + (-1)(1/2) + (0)(-1) = 0
Checking a whole set in DMAR

For a set of more than two contrasts, Equation 4.61 has to be applied C(C−1)/2C(C-1)/2 times, once per distinct pair. DMAR’s is_orthogonal_set() does that bookkeeping: it reports every pairwise inner product, confirms that each contrast’s weights sum to zero, and returns a single flag for whether the whole set is mutually orthogonal. Following the DMAR convention, the contrasts are the columns of the matrix. Below are the two pairs from above, and then the three-contrast set on four groups that the book works through on p. 192.

HideShow
# The nonorthogonal pair from above (a = 3):
C_nonorth <- cbind(Psi1 = c(1, -1, 0), Psi2 = c(1, 0, -1))
is_orthogonal_set(C_nonorth)
term value
all_orthogonal 0
all_contrasts_sum_to_zero 1
n_contrasts 2
dot[Psi1 . Psi2] 1
HideShow
#> all_orthogonal 0, inner product 1 — agrees with the base R check and book p. 191

# The orthogonal pair from above (a = 3):
C_orth <- cbind(Psi1 = c(1, -1, 0), Psi3 = c(1/2, 1/2, -1))
is_orthogonal_set(C_orth)
term value
all_orthogonal 1
all_contrasts_sum_to_zero 1
n_contrasts 2
dot[Psi1 . Psi3] 0
HideShow
#> all_orthogonal 1, inner product 0 — agrees with the base R check and book p. 192

# The book's orthogonal set of three contrasts on four groups (p. 192):
C_three <- cbind(
  Psi1 = c(1,   -1,    0,   0),
  Psi2 = c(1/2,  1/2, -1,   0),
  Psi3 = c(1/3,  1/3,  1/3, -1)
)
is_orthogonal_set(C_three)
term value
all_orthogonal 1
all_contrasts_sum_to_zero 1
n_contrasts 3
dot[Psi1 . Psi2] 0
dot[Psi1 . Psi3] 0
dot[Psi2 . Psi3] 0
HideShow
#> all three pairwise inner products 0, so all_orthogonal 1 — matches book p. 192

A set of aa groups admits at most a−1a - 1 mutually orthogonal contrasts, so three is the maximum here, and the book proves that bound on p. 192.

That bound also settles the loose end left in §4.8.2, where the two Ralerting2R^2_{\text{alerting}} values summed to more than 100%. Orthogonality is the reason, and which condition applies depends on the sample sizes: with equal nn the test is Equation 4.61, but the Table 4.1 group sizes are unequal, so the condition is Equation 4.62 (p. 191), ∑jc1jc2j/nj=0\sum_j c_{1j} c_{2j} / n_j = 0. Passing n_per_group to is_orthogonal_set() switches it to that condition.

HideShow
C_chapter <- cbind(Psi1 = c(1, -1, 0, 0), Psi2 = c(1/3, 1/3, 1/3, -1))

# Equation 4.61, the equal-n condition:
is_orthogonal_set(C_chapter)
term value
all_orthogonal 1
all_contrasts_sum_to_zero 1
n_contrasts 2
dot[Psi1 . Psi2] 0
HideShow
# Equation 4.62, the condition that actually applies to these data:
is_orthogonal_set(C_chapter, n_per_group = c(n_1, n_2, n_3, n_4))
term value
all_orthogonal 0
all_contrasts_sum_to_zero 1
n_contrasts 2
dot[Psi1 . Psi2] 0.028

The chapter’s two contrasts would be orthogonal under equal sample sizes, but with n=4,6,5,5n = 4, 6, 5, 5 they are not, so they carry overlapping information about how the groups differ and their Ralerting2R^2_{\text{alerting}} values cannot be added.

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 4: Individual Comparisons of Means (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

Chapter 5: Testing Several Contrasts: The Multiple-Comparisons Problem

Open the separate reading

Code
Results
On this page

Chapter 5 takes up the multiple-comparisons problem: any time several tests are performed on the same data, the probability of at least one Type I error somewhere in the experiment exceeds the alpha level used for each single test. The chapter develops methods that control that experimentwise rate, and matches each method to the kind of question being asked — Bonferroni for a planned set of contrasts, Tukey’s HSD for all pairwise comparisons, Scheffé for complex contrasts chosen after seeing the data, Dunnett for comparisons against a control, Hsu’s modification of Dunnett for identifying the best treatment, and the false discovery rate as a different way of defining error control altogether. It closes by showing what each of these choices costs in statistical power.

These notes build on Chapters 1, 3, and 4; see Chapter 1 for how to obtain the book’s data sets from the AMCP package and how those data sets are named. Chapter 5 uses one of them, chapter_5_table_4, the blood pressure data of Table 5.4.

HideShow
# Load all of the packages used.
library(dplyr)          # data manipulation
library(ggplot2)        # figures
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(multcomp)       # multiple-comparison procedures (glht)
library(gt)             # polished HTML tables
library(modelsummary)   # side-by-side model-comparison tables

5.3 — Multiple Comparisons

5.3.1 — Experimentwise and Per-Comparison Error Rates

The book’s starting point is the four-treatment hypertension study with three orthogonal contrasts, each tested at α=.05\alpha = .05. Equation 5.1 gives the probability of at least one Type I error across an orthogonal set of CC contrasts,

Pr⁡(at least one Type I error)=1−(1−α)C.\Pr(\text{at least one Type I error}) = 1 - (1 - \alpha)^{C}.

HideShow
alpha_PC <- 0.05   # per-comparison alpha used for each single contrast
C        <- 3      # number of orthogonal contrasts tested

# Equation 5.1.
alpha_EW <- 1 - (1 - alpha_PC)^C
alpha_EW
HideShow
[1] 0.142625
HideShow
#> 0.1426 — the .143 reported on book p. 208

# Equation 5.7: the expected number of errors per experiment, ENEPE.
C * alpha_PC
HideShow
[1] 0.15
HideShow
#> 0.15 — matches book p. 209

Three quantities that are easy to confuse have three different values here: the per-comparison rate αPC\alpha_{PC} is .05, the expected number of errors per experiment is .15, and the experimentwise rate αEW\alpha_{EW} is .143. Only one of them can be set to .05, and the book’s preference is to control αEW\alpha_{EW}. In single-factor designs αEW\alpha_{EW} and the familywise rate αFW\alpha_{FW} are identical, so this chapter works with αEW\alpha_{EW} throughout; the distinction between them waits until Chapter 7.

The figure below is a companion illustration of why the uncorrected rate is a problem: as the number of orthogonal contrasts grows, the probability of at least one spurious “significant” result climbs away from the nominal .05.

HideShow
error_inflation <- data.frame(
  C        = 1:20,
  alpha_EW = 1 - (1 - 0.05)^(1:20)
)

ggplot(error_inflation, aes(x = C, y = alpha_EW)) +
  geom_hline(yintercept = 0.05, linetype = "dashed", colour = "#0C2340") +
  annotate("text", x = 11, y = 0.10, label = "alpha[plain(PC)] == 0.05",
           parse = TRUE, colour = "#0C2340") +
  geom_line() +
  geom_point() +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x     = expression("Number of orthogonal contrasts" ~ (italic(C))),
       y     = expression("Experimentwise error rate" ~ (alpha[plain(EW)])),
       title = "Inflation of the experimentwise Type I error rate")

Pushing the logic to its limit, the book quotes R. G. Miller’s “ultraconservative statistician” who treats every test of a lifetime — say 1,000 of them — as a single family. Equation 5.2 solves for the per-comparison alpha that such a statistician would need.

HideShow
# Equation 5.2: alpha_PC = 1 - (1 - alpha_EW)^(1 / C).
1 - (1 - 0.05)^(1 / 1000)
HideShow
[1] 5.129198e-05
HideShow
#> 5.129e-05 — the .0000513 reported on book p. 210

The price of that protection is power, which the next companion figure traces. Each point holds αEW\alpha_{EW} at .05 across CC tests and asks what power remains for a two-sample comparison with n=64n = 64 per group and a population standardized mean difference of δ=0.5\delta = 0.5.

HideShow
C_values <- seq(1, 1000, by = 10)

# Equation 5.2 again: the per-comparison alpha that holds alpha_EW at .05.
alpha_PC_adjusted <- 1 - (1 - 0.05)^(1 / C_values)

power_values <- vapply(
  alpha_PC_adjusted,
  function(a) power.t.test(n           = 64,
                           delta       = 0.5,
                           sd          = 1,
                           sig.level   = a,
                           type        = "two.sample",
                           alternative = "two.sided",
                           strict      = TRUE)$power,
  numeric(1)
)

# Power at C = 1, the uncorrected single-test benchmark.
power_values[1]
HideShow
[1] 0.8014596
HideShow
power_cost <- data.frame(C = C_values, power = power_values)

ggplot(power_cost, aes(x = C, y = power)) +
  geom_hline(yintercept = power_values[1], linetype = "dashed",
             colour = "#0C2340") +
  annotate("text", x = 600, y = power_values[1] + 0.04,
           label = "Power with no correction", colour = "#0C2340") +
  geom_line(linewidth = 1) +
  scale_y_continuous(limits = c(0, 0.9)) +
  labs(x     = expression("Number of tests" ~ (italic(C))),
       y     = "Power for a single contrast",
       title = "The power cost of controlling a very large family")

5.4 — Simultaneous Confidence Intervals

Every procedure in this chapter is built from one formula. Equation 5.3 writes a confidence interval for a contrast under homogeneity of variance as

ψ̂±CVMSW∑j=1a(cj2/nj),\hat\psi \pm CV \sqrt{MS_W \sum_{j=1}^{a} (c_j^2 / n_j)},

and Equation 5.12 states the same thing in words: estimate ±\pm (critical value)(estimated standard error). What separates Bonferroni from Tukey from Scheffé from Dunnett is only the critical value CVCV. So the estimate and its standard error are built once here, and each later section supplies its own CVCV.

The data of Table 5.4
HideShow
data(chapter_5_table_4)

# Table 5.4 names the four groups, so each code is mapped to its treatment
# explicitly; factor() is then used only to fix the order of the levels.
blood_pressure <- chapter_5_table_4 |>
  mutate(Treatment = case_when(
    group == 1 ~ "Drug Therapy",
    group == 2 ~ "Biofeedback",
    group == 3 ~ "Diet",
    group == 4 ~ "Combination"
  )) |>
  mutate(Treatment = factor(
    Treatment,
    levels = c("Drug Therapy", "Biofeedback", "Diet", "Combination")
  ))

blood_pressure
HideShow
   group sbp    Treatment
1      1  84 Drug Therapy
2      1  95 Drug Therapy
3      1  93 Drug Therapy
4      1 104 Drug Therapy
5      1  99 Drug Therapy
6      1 106 Drug Therapy
7      2  81  Biofeedback
8      2  84  Biofeedback
9      2  92  Biofeedback
10     2 101  Biofeedback
11     2  80  Biofeedback
12     2 108  Biofeedback
13     3  98         Diet
14     3  95         Diet
15     3  86         Diet
16     3  87         Diet
17     3  94         Diet
18     3 101         Diet
19     4  91  Combination
20     4  78  Combination
21     4  85  Combination
22     4  80  Combination
23     4  81  Combination
24     4  76  Combination
HideShow
Summary_5_4 <- blood_pressure |>
  group_by(Treatment) |>
  summarize(mean = mean(sbp), sd = sd(sbp), s2 = var(sbp), n = n()) |>
  as.data.frame()

Summary_5_4
HideShow
     Treatment     mean        sd        s2 n
1 Drug Therapy 96.83333  8.035339  64.56667 6
2  Biofeedback 91.00000 11.489125 132.00000 6
3         Diet 93.50000  5.958188  35.50000 6
4  Combination 81.83333  5.419102  29.36667 6
HideShow
#> means 96.833, 91.000, 93.500, 81.833 and variances 64.567, 132.000,
#> 35.500, 29.367 — match Table 5.4, book p. 220
The omnibus analysis of variance and its error term

The contrasts themselves are the point of the chapter, but the omnibus analysis supplies the pooled error term MSWMS_W and its degrees of freedom, which every procedure that assumes homogeneity of variance uses.

HideShow
ANOVA_Object <- aov(sbp ~ Treatment, data = blood_pressure)
ANOVA_Result <- anova(ANOVA_Object)
ANOVA_Result
HideShow
Analysis of Variance Table

Response: sbp
          Df  Sum Sq Mean Sq F value  Pr(>F)  
Treatment  3  744.79 248.264  3.7985 0.02637 *
Residuals 20 1307.17  65.358                  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
MS_W <- ANOVA_Result$"Mean Sq"[2]
MS_W
HideShow
[1] 65.35833
HideShow
#> 65.358 — matches the error term printed beneath Table 5.7, book p. 228

df_between <- ANOVA_Result$"Df"[1]
df_error   <- ANOVA_Result$"Df"[2]
c(df_between = df_between, df_error = df_error)
HideShow
df_between   df_error 
         3         20 

The book does not print the omnibus test for the Table 5.4 data, so only MSWMS_W is checked against the printed page here; the remaining entries of the table follow from it.

This is a model-comparison text, so it is worth making the comparison behind that table explicit. The restricted model gives every participant the grand mean; the full model gives each treatment its own mean. The FF from comparing them is the omnibus FF above.

HideShow
fit_restricted <- lm(sbp ~ 1,         data = blood_pressure)  # grand mean only
fit_full       <- lm(sbp ~ Treatment, data = blood_pressure)  # group means
anova(fit_restricted, fit_full)
HideShow
Analysis of Variance Table

Model 1: sbp ~ 1
Model 2: sbp ~ Treatment
  Res.Df    RSS Df Sum of Sq      F  Pr(>F)  
1     23 2052.0                              
2     20 1307.2  3    744.79 3.7985 0.02637 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The same omnibus analysis as an APA-style table, built with gt so the formatting carries over to HTML. The numbers are exactly those in the anova() printout above.

HideShow
anova_table <- data.frame(
  Source = c("Treatment (between groups)", "Within (error)"),
  SS     = ANOVA_Result$"Sum Sq",
  df     = ANOVA_Result$"Df",
  MS     = ANOVA_Result$"Mean Sq",
  Fstat  = ANOVA_Result$"F value",
  p      = ANOVA_Result$"Pr(>F)"
)

# Partial eta-squared: the effect's share of effect-plus-error variance.
anova_table$peta <- c(
  anova_table$SS[1] / (anova_table$SS[1] + anova_table$SS[2]),
  NA_real_
)

anova_table |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("**Table 1**. Analysis of Variance for Systolic Blood Pressure")) |>
  cols_align(align = "center", columns = -Source)
Table 1. Analysis of Variance for Systolic Blood Pressure
Source SS df MS F p Partial η2
Treatment (between groups) 744.79 3 248.26 3.80 0.0264 0.363
Within (error) 1,307.17 20 65.36


A side-by-side modelsummary table places the two models in adjacent columns, with standard errors in parentheses (APA style) and fit statistics at the foot:

HideShow
modelsummary(
  list("Grand mean" = fit_restricted, "Group means" = fit_full),
  estimate  = "{estimate}",
  statistic = "({std.error})",
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  output    = "gt"
)
Grand mean Group means
(Intercept) 90.792 96.833
(1.928) (3.300)
TreatmentBiofeedback -5.833
(4.668)
TreatmentDiet -3.333
(4.668)
TreatmentCombination -15.000
(4.668)
Num.Obs. 24 24
AIC 178.9 174.1
BIC 181.2 179.9
Log.Lik. -87.436 -82.025
The four contrasts and the machinery they share

Before collecting the data the investigator decided on four contrasts (book p. 220): drug versus biofeedback, drug versus diet, biofeedback versus diet, and the average of the three single treatments versus the combination.

HideShow
C1 <- c(1, -1, 0, 0)        # drug versus biofeedback
C2 <- c(1, 0, -1, 0)        # drug versus diet
C3 <- c(0, 1, -1, 0)        # biofeedback versus diet
C4 <- c(1/3, 1/3, 1/3, -1)  # average of the three single treatments versus the combination

Contrasts <- list(
  "Drug - Biofeedback"     = C1,
  "Drug - Diet"            = C2,
  "Biofeedback - Diet"     = C3,
  "Mean(1, 2, 3) - Combin" = C4
)

The function below is Equation 5.12 written out: it returns ψ̂\hat\psi, its standard error under homogeneity of variance, and the interval for whatever critical value is handed to it. It is defined here, on the page, so that code copied from any later section runs as it stands.

HideShow
contrast_ci <- function(c_weights, means, n, MS_W, critical_value) {
  psi_hat <- sum(c_weights * means)
  se      <- sqrt(MS_W * sum(c_weights^2 / n))
  data.frame(
    psi_hat = psi_hat,
    se      = se,
    lower   = psi_hat - critical_value * se,
    upper   = psi_hat + critical_value * se
  )
}
Per-interval confidence intervals, the baseline

Choosing CV=Fα;1,N−aCV = \sqrt{F_{\alpha;1,N-a}} gives Equation 4.40 from Chapter 4, which controls confidence at the per-interval level rather than simultaneously. Note the numerator degrees of freedom: a contrast is a single-degree-of-freedom question, so df1=1df_1 = 1, and the multiplier is equivalently a central tt quantile because t2=Ft^2 = F.

HideShow
CV_per_interval <- sqrt(qf(1 - 0.05, df1 = 1, df2 = df_error))
c(from_F = CV_per_interval, from_t = qt(1 - 0.05 / 2, df = df_error))
HideShow
  from_F   from_t 
2.085963 2.085963 
HideShow
#> 2.0860 both ways

per_interval <- do.call(rbind, lapply(
  Contrasts, contrast_ci,
  means = Summary_5_4$mean, n = Summary_5_4$n, MS_W = MS_W,
  critical_value = CV_per_interval
))
per_interval
HideShow
                         psi_hat       se      lower     upper
Drug - Biofeedback      5.833333 4.667559  -3.903025 15.569692
Drug - Diet             3.333333 4.667559  -6.403025 13.069692
Biofeedback - Diet     -2.500000 4.667559 -12.236358  7.236358
Mean(1, 2, 3) - Combin 11.944444 3.811046   3.994741 19.894148
HideShow
#> psi_hat 5.833, 3.333, -2.500, 11.944 and se 4.668, 4.668, 4.668, 3.811 —
#> match the "Assumes equal variances" rows of Table 5.5, book p. 221. The
#> book's fourth contrast was given to SPSS as 1, 1, 1, -3, so its printed
#> estimate (35.83) and standard error (11.4331) are three times these.

DMAR’s ci_c() also gives the 95% interval for each contrast from the group means, sample sizes, and pooled within-group standard deviation.

HideShow
ci_c(means = Summary_5_4$mean, s_anova = sqrt(MS_W), c_weights = C1,
     n_per_group = Summary_5_4$n, N = sum(Summary_5_4$n), conf_level = 0.95)
term value
ci_lower -3.903
contrast 5.833
ci_upper 15.570

Confidence level: 95%

HideShow
#> -3.903 to 15.570 — agrees with the hand computation.

# Collect all four contrasts in one table.
bind_rows(lapply(Contrasts, function(cw) {
  fit <- ci_c(means = Summary_5_4$mean, s_anova = sqrt(MS_W),
              c_weights = cw, n_per_group = Summary_5_4$n,
              N = sum(Summary_5_4$n), conf_level = 0.95)
  rows <- generics::tidy(fit)
  tibble::tibble(estimate = rows$estimate[rows$term == "contrast"],
                 lower = rows$estimate[rows$term == "ci_lower"],
                 upper = rows$estimate[rows$term == "ci_upper"])
}), .id = "comparison")
HideShow
# A tibble: 4 × 4
  comparison             estimate  lower upper
  <chr>                     <dbl>  <dbl> <dbl>
1 Drug - Biofeedback         5.83  -3.90 15.6 
2 Drug - Diet                3.33  -6.40 13.1 
3 Biofeedback - Diet        -2.5  -12.2   7.24
4 Mean(1, 2, 3) - Combin    11.9    3.99 19.9 

5.5 — Multiple Planned Comparisons

5.5.1 — Bonferroni Adjustment

The Bonferroni adjustment sets αPC=αEW/C\alpha_{PC} = \alpha_{EW}/C. The book illustrates it with the strategy-training study: four groups, 11 participants per group, three planned contrasts, and an observed FF of 4.23 on 1 and 40 degrees of freedom.

HideShow
C        <- 3
alpha_EW <- 0.05
alpha_PC <- alpha_EW / C
alpha_PC
HideShow
[1] 0.01666667
HideShow
#> 0.01667 — the .0167 of book p. 216

# Critical F without adjustment.
qf(1 - alpha_EW, df1 = 1, df2 = 40)
HideShow
[1] 4.084746
HideShow
#> 4.0847 — the 4.08 of book p. 216

# Critical F with the Bonferroni adjustment. This is the single line of R the
# book itself prints on p. 217.
qf(1 - alpha_PC, df1 = 1, df2 = 40)
HideShow
[1] 6.24428
HideShow
#> 6.2443 — the 6.24 of book pp. 216 and 217, so the observed F of 4.23 is
#> not significant once alpha_EW is controlled

# The matching critical t, since t^2 = F.
qt(1 - alpha_PC / 2, df = 40)
HideShow
[1] 2.498856
HideShow
#> 2.4989 — the square root of 6.2443
Checking the Bonferroni inequality

Equation 5.5 is an inequality, 1−(1−α)C≤Cα1 - (1-\alpha)^C \le C\alpha, so the actual experimentwise rate under the Bonferroni adjustment could in principle fall well below .05. Table 5.3 shows that for orthogonal contrasts it does not: the inequality is an equality for practical purposes, and the adjustment is therefore not conservative here.

HideShow
C_values <- c(1, 2, 3, 4, 5, 10, 20, 50)

# Actual probability of at least one Type I error when each of C orthogonal
# contrasts is tested at .05/C.
data.frame(
  C                   = C_values,
  Actual_Probability  = round(1 - (1 - (0.05 / C_values))^C_values, 6),
  Bonferroni_Limit    = 0.05
)
HideShow
   C Actual_Probability Bonferroni_Limit
1  1           0.050000             0.05
2  2           0.049375             0.05
3  3           0.049171             0.05
4  4           0.049070             0.05
5  5           0.049010             0.05
6 10           0.048890             0.05
7 20           0.048830             0.05
8 50           0.048794             0.05
HideShow
#> .050000 .049375 .049171 .049070 .049010 .048890 .048830 .048794 —
#> matches Table 5.3, book p. 218

5.5.2 — Modification of the Bonferroni Approach with Unequal Variances

When the group variances are not pooled, the contrast’s standard error uses each group’s own variance (Equation 5.10) and its denominator degrees of freedom come from the Welch–Satterthwaite expression given as Equation 5.14 and in the footnote to Table 5.17. Both are written out below as functions of the cc-weights.

HideShow
# Standard error of a contrast without pooling (Equations 5.10 and 5.11).
contrast_se_heterogeneous <- function(c_weights, s2, n) {
  sqrt(sum(c_weights^2 * s2 / n))
}

# Denominator degrees of freedom for that standard error (Equation 5.14; the
# same expression appears as Chapter 4's Equation 4.34).
contrast_df_heterogeneous <- function(c_weights, s2, n) {
  components <- c_weights^2 * s2 / n
  sum(components)^2 / sum(components^2 / (n - 1))
}

se_heterogeneous <- vapply(Contrasts, contrast_se_heterogeneous, numeric(1),
                           s2 = Summary_5_4$s2, n = Summary_5_4$n)
df_heterogeneous <- vapply(Contrasts, contrast_df_heterogeneous, numeric(1),
                           s2 = Summary_5_4$s2, n = Summary_5_4$n)

round(rbind(se = se_heterogeneous, df = df_heterogeneous), 3)
HideShow
   Drug - Biofeedback Drug - Diet Biofeedback - Diet Mean(1, 2, 3) - Combin
se              5.724       4.084              5.284                  3.032
df              8.947       9.222              7.508                 13.288
HideShow
#> standard errors 5.724, 4.084, 5.284, 3.032 and df 8.947, 9.222, 7.508,
#> 13.288 — match the "Does not assume equal variances" rows of Table 5.5,
#> book p. 221 (the printed standard error for the fourth contrast, 9.0955,
#> is three times 3.032 because of its 1, 1, 1, -3 scaling)

5.5.3 — Numerical Example

The contrast tests of Table 5.5

With the estimates and both kinds of standard error in hand, the tests at the top of Table 5.5 follow directly. The Bonferroni decision rule is to compare each pp value with αPC=.05/C=.0125\alpha_{PC} = .05/C = .0125, and only the fourth contrast clears it, whether or not homogeneity is assumed.

HideShow
psi_hat <- vapply(Contrasts, function(cw) sum(cw * Summary_5_4$mean), numeric(1))
se_pooled <- vapply(Contrasts, function(cw) sqrt(MS_W * sum(cw^2 / Summary_5_4$n)),
                    numeric(1))

contrast_tests <- data.frame(
  psi_hat        = round(psi_hat, 3),
  se_equal       = round(se_pooled, 3),
  t_equal        = round(psi_hat / se_pooled, 3),
  df_equal       = df_error,
  p_equal        = round(2 * pt(-abs(psi_hat / se_pooled), df = df_error), 3),
  se_unequal     = round(se_heterogeneous, 3),
  t_unequal      = round(psi_hat / se_heterogeneous, 3),
  df_unequal     = round(df_heterogeneous, 3),
  p_unequal      = round(2 * pt(-abs(psi_hat / se_heterogeneous),
                                df = df_heterogeneous), 3)
)
contrast_tests
HideShow
                       psi_hat se_equal t_equal df_equal p_equal se_unequal
Drug - Biofeedback       5.833    4.668   1.250       20   0.226      5.724
Drug - Diet              3.333    4.668   0.714       20   0.483      4.084
Biofeedback - Diet      -2.500    4.668  -0.536       20   0.598      5.284
Mean(1, 2, 3) - Combin  11.944    3.811   3.134       20   0.005      3.032
                       t_unequal df_unequal p_unequal
Drug - Biofeedback         1.019      8.947     0.335
Drug - Diet                0.816      9.222     0.435
Biofeedback - Diet        -0.473      7.508     0.650
Mean(1, 2, 3) - Combin     3.940     13.288     0.002
HideShow
#> equal-variance t 1.250, 0.714, -0.536, 3.134 with p .226, .483, .598, .005
#> and separate-variance t 1.019, 0.816, -0.473, 3.940 with p .335, .435,
#> .650, .002 — all match Table 5.5, book p. 221
Simultaneous intervals assuming homogeneity of variance

For the Bonferroni method the critical value is CV=F.05/C;1,dferrorCV = \sqrt{F_{.05/C;1,df_{error}}} with C=4C = 4.

HideShow
CV_bonferroni <- sqrt(qf(1 - 0.05 / 4, df1 = 1, df2 = df_error))
c(F_value = CV_bonferroni^2, CV = CV_bonferroni)
HideShow
 F_value       CV 
7.531602 2.744376 
HideShow
#> F 7.5316 — the 7.53 of Table 5.5 (book p. 221) and the df = 20, C = 4
#> entry of Appendix Table A.3 (book p. 985); CV 2.7444

bonferroni_homogeneous <- do.call(rbind, lapply(
  Contrasts, contrast_ci,
  means = Summary_5_4$mean, n = Summary_5_4$n, MS_W = MS_W,
  critical_value = CV_bonferroni
))
round(bonferroni_homogeneous, 2)
HideShow
                       psi_hat   se  lower upper
Drug - Biofeedback        5.83 4.67  -6.98 18.64
Drug - Diet               3.33 4.67  -9.48 16.14
Biofeedback - Diet       -2.50 4.67 -15.31 10.31
Mean(1, 2, 3) - Combin   11.94 3.81   1.49 22.40
HideShow
#> -6.98 to 18.64, -9.48 to 16.14, -15.31 to 10.31, 1.49 to 22.40 — matches
#> the upper half of Table 5.5, book p. 221, to rounding

The first two lower limits print as −6.98-6.98 and −9.48-9.48 where the book shows −6.97-6.97 and −9.47-9.47. The difference is where the rounding happens, not in the method: Table 5.5 does the arithmetic from the rounded intermediate values it displays, 5.8333±7.53(4.6676)5.8333 \pm \sqrt{7.53}\,(4.6676), while the code above carries the unrounded critical value and standard error through to the end. Substituting the book’s own displayed values reproduces its printed endpoints exactly.

HideShow
# The book's literal intermediate values for the first contrast.
5.8333 + c(-1, 1) * sqrt(7.53) * 4.6676
HideShow
[1] -6.974989 18.641589
HideShow
#> -6.97 and 18.64 — matches Table 5.5, book p. 221

Only the fourth interval excludes zero, which is the same conclusion the pp values gave: the combination treatment differs from the average of the three single treatments, and nothing else is established.

Simultaneous intervals without assuming homogeneity of variance

Equation 5.11 keeps the Bonferroni critical value but evaluates it at each contrast’s own heterogeneous degrees of freedom. Two versions are worth seeing. The first uses the exact, non-integer degrees of freedom, which is what the book recommends when a program is available (p. 222). The second rounds those degrees of freedom down to the integers that Appendix Table A.3 is indexed by, which is what produces the printed intervals.

HideShow
contrast_ci_heterogeneous <- function(c_weights, means, s2, n, critical_value) {
  psi_hat <- sum(c_weights * means)
  se      <- contrast_se_heterogeneous(c_weights, s2, n)
  data.frame(
    psi_hat = psi_hat,
    se      = se,
    lower   = psi_hat - critical_value * se,
    upper   = psi_hat + critical_value * se
  )
}

# Exact (non-integer) denominator degrees of freedom.
CV_exact <- sqrt(qf(1 - 0.05 / 4, df1 = 1, df2 = df_heterogeneous))
round(CV_exact^2, 2)
HideShow
    Drug - Biofeedback            Drug - Diet     Biofeedback - Diet 
                  9.71                   9.57                  10.66 
Mean(1, 2, 3) - Combin 
                  8.33 
HideShow
bonferroni_exact_df <- do.call(rbind, Map(
  function(cw, cv) contrast_ci_heterogeneous(
    cw, Summary_5_4$mean, Summary_5_4$s2, Summary_5_4$n, cv),
  Contrasts, CV_exact
))
round(bonferroni_exact_df, 2)
HideShow
                       psi_hat   se  lower upper
Drug - Biofeedback        5.83 5.72 -12.00 23.66
Drug - Diet               3.33 4.08  -9.30 15.97
Biofeedback - Diet       -2.50 5.28 -19.75 14.75
Mean(1, 2, 3) - Combin   11.94 3.03   3.19 20.70
HideShow
# Degrees of freedom rounded down, as the book's appendix tables require.
CV_table <- sqrt(qf(1 - 0.05 / 4, df1 = 1, df2 = floor(df_heterogeneous)))
round(CV_table^2, 2)
HideShow
    Drug - Biofeedback            Drug - Diet     Biofeedback - Diet 
                 10.28                   9.68                  11.12 
Mean(1, 2, 3) - Combin 
                  8.39 
HideShow
#> 10.28, 9.68, 11.12, 8.39 — match the critical F values shown in the lower
#> half of Table 5.5, book p. 221

bonferroni_table_df <- do.call(rbind, Map(
  function(cw, cv) contrast_ci_heterogeneous(
    cw, Summary_5_4$mean, Summary_5_4$s2, Summary_5_4$n, cv),
  Contrasts, CV_table
))
round(bonferroni_table_df, 2)
HideShow
                       psi_hat   se  lower upper
Drug - Biofeedback        5.83 5.72 -12.52 24.18
Drug - Diet               3.33 4.08  -9.37 16.04
Biofeedback - Diet       -2.50 5.28 -20.12 15.12
Mean(1, 2, 3) - Combin   11.94 3.03   3.16 20.73
HideShow
#> -12.52 to 24.18, -9.37 to 16.04, -20.12 to 15.12, 3.16 to 20.73 — matches
#> the lower half of Table 5.5, book p. 221

As the book notes on p. 223, relaxing homogeneity makes little practical difference in these data: two intervals widen appreciably, two narrow slightly, and the fourth contrast remains the only one that excludes zero.

The same multiplier and intervals in DMAR

The Bonferroni multiplier is a central-tt quantile at αPC\alpha_{PC}, and cv_t() reports both of its tails. Passing 1−αPC1 - \alpha_{PC} to ci_c() as the confidence level gives the simultaneous interval from the summary statistics.

HideShow
cv_t(alpha_level = 0.05 / 4, df = df_error)
term value area_less area_greater
lower_cv -2.744 0.006 0.994
upper_cv 2.744 0.994 0.006
HideShow
#> upper_cv 2.744 — the same multiplier as sqrt(qf(1 - .05/4, 1, 20)) above,
#> and the square root of the 7.53 in Appendix Table A.3 (book p. 985)

ci_c(means = Summary_5_4$mean, s_anova = sqrt(MS_W), c_weights = C1,
     n_per_group = Summary_5_4$n, N = sum(Summary_5_4$n),
     conf_level = 1 - 0.05 / 4)
term value
ci_lower -6.976
contrast 5.833
ci_upper 18.643

Confidence level: 98.75%

HideShow
#> -6.976 to 18.643 — the unrounded form of Table 5.5's -6.97 to 18.64

5.6 — Pairwise Comparisons

5.6.1 — Tukey’s HSD Procedure

Tukey’s HSD judges every pairwise difference against the sampling distribution of the largest one. That distribution is the studentized range, written qq, and the critical value for an observed FF is q2/2q^2/2; equivalently an observed tt is compared with q/2q/\sqrt{2}. Note that the familywise alpha is not split between the two tails here, because the studentized range is already a distribution of an absolute largest difference.

HideShow
a <- nlevels(blood_pressure$Treatment)
a
HideShow
[1] 4
HideShow
# Critical studentized range for the blood pressure data.
q_critical <- qtukey(p = 1 - 0.05, nmeans = a, df = df_error)
q_critical
HideShow
[1] 3.958293
HideShow
#> 3.9583 — the df = 20, r = 4 entry of Appendix Table A.4, book p. 988

# On the t scale and on the F scale.
c(critical_t = q_critical / sqrt(2), critical_F = q_critical^2 / 2)
HideShow
critical_t critical_F 
  2.798936   7.834044 

Table 5.6 sets the Tukey critical value beside the unadjusted and the Bonferroni critical values for all pairwise comparisons, holding dferrordf_{error} at 12. For aa groups there are a(a−1)/2a(a-1)/2 pairs, and that count is the CC the Bonferroni column uses.

HideShow
groups      <- 2:6
comparisons <- groups * (groups - 1) / 2

data.frame(
  Number_of_Groups      = groups,
  Number_of_Comparisons = comparisons,
  Per_Comparison        = round(qf(1 - 0.05, df1 = 1, df2 = 12), 2),
  Tukey                 = round(qtukey(1 - 0.05, nmeans = groups, df = 12)^2 / 2, 2),
  Bonferroni            = round(qf(1 - 0.05 / comparisons, df1 = 1, df2 = 12), 2)
)
HideShow
  Number_of_Groups Number_of_Comparisons Per_Comparison Tukey Bonferroni
1                2                     1           4.75  4.75       4.75
2                3                     3           4.75  7.12       7.73
3                4                     6           4.75  8.81       9.94
4                5                    10           4.75 10.16      11.75
5                6                    15           4.75 11.28      13.31
HideShow
#> per-comparison 4.75 throughout; Tukey 4.75, 7.12, 8.81, 10.16, 11.28;
#> Bonferroni 4.75, 7.73, 9.94, 11.75, 13.31 — matches Table 5.6, book p. 225

Whenever a≥3a \ge 3 the Tukey critical value is smaller than the Bonferroni value, which is the sense in which Tukey’s HSD is the more powerful way to test all pairwise comparisons.

5.6.2 — Modifications of Tukey’s HSD

With unequal nn but pooled variances, Kramer’s modification simply computes each observed FF with the general unequal-nn formula and keeps the q2/2q^2/2 critical value. When variances are heterogeneous the book recommends Dunnett’s T3 for small samples, which compares the observed tt of Equation 5.13 — on the degrees of freedom of Equation 5.14 — with a critical value VV from the studentized maximum modulus distribution.

SPSS’s “Tamhane” option is Tamhane’s T2, the close relative of T3 that uses a Sidak-adjusted tt rather than the maximum modulus, and that is what the lower half of Table 5.7 reports. Both pieces are base R: a Welch standard error and degrees of freedom per pair, then a Sidak-adjusted quantile over the C=a(a−1)/2C = a(a-1)/2 pairs.

HideShow
pairs_index <- combn(a, 2)
pair_labels <- paste(levels(blood_pressure$Treatment)[pairs_index[1, ]],
                     levels(blood_pressure$Treatment)[pairs_index[2, ]],
                     sep = " - ")

g <- pairs_index[1, ]
h <- pairs_index[2, ]

difference <- Summary_5_4$mean[g] - Summary_5_4$mean[h]

# Equation 5.13, as a standard error rather than an F.
se_pair <- sqrt(Summary_5_4$s2[g] / Summary_5_4$n[g] +
                Summary_5_4$s2[h] / Summary_5_4$n[h])

# Equation 5.14.
df_pair <- (Summary_5_4$s2[g] / Summary_5_4$n[g] +
            Summary_5_4$s2[h] / Summary_5_4$n[h])^2 /
  ((Summary_5_4$s2[g] / Summary_5_4$n[g])^2 / (Summary_5_4$n[g] - 1) +
   (Summary_5_4$s2[h] / Summary_5_4$n[h])^2 / (Summary_5_4$n[h] - 1))

C_pairwise  <- a * (a - 1) / 2
alpha_sidak <- 1 - (1 - 0.05)^(1 / C_pairwise)
CV_tamhane  <- qt(1 - alpha_sidak / 2, df = df_pair)

data.frame(
  Comparison = pair_labels,
  Difference = round(difference, 2),
  Std_Error  = round(se_pair, 3),
  Sig        = round(1 - (1 - 2 * pt(-abs(difference / se_pair), df = df_pair))^C_pairwise, 3),
  Lower      = round(difference - CV_tamhane * se_pair, 2),
  Upper      = round(difference + CV_tamhane * se_pair, 2)
)
HideShow
                  Comparison Difference Std_Error   Sig  Lower Upper
1 Drug Therapy - Biofeedback       5.83     5.724 0.913 -13.38 25.04
2        Drug Therapy - Diet       3.33     4.084 0.967 -10.26 16.93
3 Drug Therapy - Combination      15.00     3.957 0.027   1.65 28.35
4         Biofeedback - Diet      -2.50     5.284 0.998 -21.17 16.17
5  Biofeedback - Combination       9.17     5.186 0.535  -9.49 27.83
6         Diet - Combination      11.67     3.288 0.032   0.91 22.42
HideShow
#> differences 5.83, 3.33, 15.00, -2.50, 9.17, 11.67 with standard errors
#> 5.724, 4.084, 3.957, 5.284, 5.186, 3.288, significance values .913, .967,
#> .027, .998, .535, .032, and intervals -13.38 to 25.04, -10.26 to 16.93,
#> 1.65 to 28.35, -21.17 to 16.17, -9.49 to 27.83, 0.91 to 22.42 — all match
#> the Tamhane half of Table 5.7, book p. 228

Relaxing homogeneity makes one more pairwise difference statistically significant here: the combination treatment is now distinguishable from diet as well as from drug therapy, exactly as the book reports on p. 227.

DMAR supplies the critical value VV that Dunnett’s T3 needs, through cv_smm(). Its n_comparisons argument is the number of pairs, and it can be checked against Appendix Table A.5, whose columns are indexed by the number of groups.

HideShow
cv_smm(alpha_level = 0.05, df = df_error, n_comparisons = C_pairwise)
term value area_less area_greater
upper_cv 2.897 0.950 0.050
HideShow
#> 2.897 — the df = 20, four-groups entry of Appendix Table A.5 (2.90),
#> book p. 989

cv_smm(alpha_level = 0.05, df = 8, n_comparisons = C_pairwise)
term value area_less area_greater
upper_cv 3.365 0.950 0.050
HideShow
#> 3.365 — the df = 8, four-groups entry of the same table (3.36)

5.6.3 — Numerical Example

TukeyHSD() is base R and needs only the fitted aov() object. It reports every pairwise difference with its simultaneous interval and its adjusted pp value.

HideShow
Tukey_Result <- TukeyHSD(ANOVA_Object)
Tukey_Result
HideShow
  Tukey multiple comparisons of means
    95% family-wise confidence level

Fit: aov(formula = sbp ~ Treatment, data = blood_pressure)

$Treatment
                               diff       lwr       upr     p adj
Biofeedback-Drug Therapy  -5.833333 -18.89753  7.230868 0.6038383
Diet-Drug Therapy         -3.333333 -16.39753  9.730868 0.8903064
Combination-Drug Therapy -15.000000 -28.06420 -1.935799 0.0208593
Diet-Biofeedback           2.500000 -10.56420 15.564201 0.9493084
Combination-Biofeedback   -9.166667 -22.23087  3.897534 0.2345096
Combination-Diet         -11.666667 -24.73087  1.397534 0.0905811
HideShow
#> differences -5.833, -3.333, -15.000, 2.500, -9.167, -11.667 with intervals
#> -18.90 to 7.23, -16.40 to 9.73, -28.06 to -1.94, -10.56 to 15.56, -22.23
#> to 3.90, -24.73 to 1.40 and adjusted p .604, .890, .021, .949, .235, .091
#> — match the Tukey HSD half of Table 5.7, book p. 228. R subtracts the
#> earlier level from the later one, so each difference carries the opposite
#> sign from the book's (I) minus (J) row.

Under the homogeneity assumption the only statistically significant pairwise difference is between drug therapy and the combination treatment. The interval runs from roughly 2 to 28 units, so although the combination therapy is confidently better, the data say little about by how much.

The same intervals as a figure. An interval that crosses the dashed line at zero leaves the direction of that difference unresolved.

HideShow
tukey_df <- as.data.frame(Tukey_Result$Treatment)
tukey_df$Comparison <- factor(rownames(tukey_df),
                              levels = rev(rownames(tukey_df)))

ggplot(tukey_df, aes(x = diff, y = Comparison)) +
  geom_vline(xintercept = 0, linetype = "dashed", colour = "#0C2340") +
  geom_pointrange(aes(xmin = lwr, xmax = upr)) +
  labs(x     = "Difference in mean systolic blood pressure",
       y     = NULL,
       title = "Tukey HSD 95% simultaneous confidence intervals")

The same intervals in DMAR

TukeyHSD() works from a fitted model; ci_tukey_kramer() takes a response vector and a grouping vector instead, and reports the studentized-range statistic for each pair alongside the interval.

HideShow
ci_tukey_kramer(x = blood_pressure$sbp, group = blood_pressure$Treatment)
contrast mean_difference se q_statistic ci_lower ci_upper p_adjusted
Biofeedback - Drug Therapy -5.833 3.300 -1.767 -18.898 7.231 0.6038
Diet - Drug Therapy -3.333 3.300 -1.010 -16.398 9.731 0.8903
Combination - Drug Therapy -15.000 3.300 -4.545 -28.064 -1.936 0.0209
Diet - Biofeedback 2.500 3.300 0.757 -10.564 15.564 0.9493
Combination - Biofeedback -9.167 3.300 -2.777 -22.231 3.898 0.2345
Combination - Diet -11.667 3.300 -3.535 -24.731 1.398 0.0906

Confidence level: 95%, simultaneous interval (Tukey)

HideShow
#> the same six differences, intervals, and adjusted p values as TukeyHSD()
#> above, hence the same agreement with Table 5.7, book p. 228

cv_tukey_hsd(alpha_level = 0.05, df = df_error, n_groups = a)
term value area_less area_greater
upper_cv 2.799 0.950 0.050
HideShow
#> 2.799 — the critical value on the t scale, that is 3.9583 / sqrt(2);
#> squaring it returns the critical F of 7.834 used above

5.7 — Post Hoc Complex Comparisons

Scheffé’s method judges a contrast against the sampling distribution of the largest FF obtainable from any contrast, pairwise or complex. Because SSmax=SSBSS_{max} = SS_B (Section 5.7.1), that distribution is (a−1)(a-1) times a central FF on a−1a-1 and N−aN-a degrees of freedom, so the critical value of Equation 5.22 is (a−1)F.05;a−1,N−a(a-1)F_{.05;a-1,N-a}. The price of being allowed to test infinitely many data-suggested contrasts is that this critical value is large.

HideShow
# The illustration of book p. 232: a = 4 groups, so df numerator = 3, with
# df denominator = 30.
3 * qf(1 - 0.05, df1 = 3, df2 = 30)
HideShow
[1] 8.766832
HideShow
#> 8.77 — the Scheffé column of Table 5.8, book p. 232

5.7.2 — Comparison of Scheffé to Bonferroni and Tukey

Scheffé’s cost is fixed; Bonferroni’s grows with every contrast added. Table 5.8 shows where the two cross for a=4a = 4 and dferror=30df_{error} = 30.

HideShow
a_illustration        <- 4
df_error_illustration <- 30
C_values              <- 1:10

scheffe_cv <- (a_illustration - 1) *
  qf(1 - 0.05, df1 = a_illustration - 1, df2 = df_error_illustration)

table_5_8 <- data.frame(
  C          = C_values,
  Bonferroni = round(qf(1 - 0.05 / C_values, df1 = 1,
                        df2 = df_error_illustration), 2),
  Scheffe    = round(scheffe_cv, 2)
)
table_5_8
HideShow
    C Bonferroni Scheffe
1   1       4.17    8.77
2   2       5.57    8.77
3   3       6.43    8.77
4   4       7.06    8.77
5   5       7.56    8.77
6   6       7.98    8.77
7   7       8.34    8.77
8   8       8.65    8.77
9   9       8.93    8.77
10 10       9.18    8.77
HideShow
#> Bonferroni 4.17, 5.57, 6.43, 7.06, 7.56, 7.98, 8.34, 8.65, 8.93, 9.18
#> against a constant Scheffé 8.77 — matches Table 5.8, book p. 232

# The largest C for which Bonferroni is still the smaller critical value.
max(table_5_8$C[table_5_8$Bonferroni < scheffe_cv])
HideShow
[1] 8
HideShow
#> 8 — matches the a = 4, df_error = 30 entry of Table 5.9, book p. 233

So up to eight planned contrasts can be tested with a smaller critical value under Bonferroni than under Scheffé. Only a researcher who might test more than eight, or who cannot specify the contrasts in advance, gains from Scheffé here. And for pairwise comparisons specifically, Tukey beats both.

5.7.3 — Modifications of Scheffé’s Method

The Brown–Forsythe separate-variances modification keeps the form of Equation 5.22 and substitutes the heterogeneous denominator degrees of freedom already computed in Section 5.5.2.

5.7.4 — Numerical Example

The same four contrasts are now treated as having been chosen after seeing the data, so Scheffé is the method of choice. Nothing about the estimates or their standard errors changes — only the critical value.

HideShow
CV_scheffe <- sqrt(df_between * qf(1 - 0.05, df1 = df_between, df2 = df_error))
c(F_value = CV_scheffe^2, CV = CV_scheffe)
HideShow
 F_value       CV 
9.295174 3.048799 
HideShow
#> F 9.2952 — the 9.30 shown in Table 5.10, book p. 234

scheffe_homogeneous <- do.call(rbind, lapply(
  Contrasts, contrast_ci,
  means = Summary_5_4$mean, n = Summary_5_4$n, MS_W = MS_W,
  critical_value = CV_scheffe
))
round(scheffe_homogeneous, 2)
HideShow
                       psi_hat   se  lower upper
Drug - Biofeedback        5.83 4.67  -8.40 20.06
Drug - Diet               3.33 4.67 -10.90 17.56
Biofeedback - Diet       -2.50 4.67 -16.73 11.73
Mean(1, 2, 3) - Combin   11.94 3.81   0.33 23.56
HideShow
#> -8.40 to 20.06, -10.90 to 17.56, -16.73 to 11.73, 0.33 to 23.56 — matches
#> Table 5.10, book p. 234 (whose complex-contrast row, computed from the
#> rounded sqrt(9.30), prints as 0.32 to 23.57)

Every Scheffé interval is wider than the corresponding Bonferroni interval of Section 5.5.3, which is what choosing contrasts post hoc costs. The conclusion is unchanged: only the complex contrast supports a confident statement of direction.

Without the homogeneity assumption, the critical value becomes (a−1)F.05;a−1,df(a-1)F_{.05;a-1,df} on each contrast’s own degrees of freedom. As in Section 5.5.3 the book reads FF from an appendix table at integer degrees of freedom — its footnote to Table 5.10 spells this out, giving 3F(3,8)=3(4.07)=12.213F(3,8) = 3(4.07) = 12.21 for the first contrast — so rounding the degrees of freedom down reproduces the printed values.

HideShow
# Exact (non-integer) denominator degrees of freedom.
CV_scheffe_exact <- sqrt(df_between * qf(1 - 0.05, df1 = df_between,
                                         df2 = df_heterogeneous))
round(CV_scheffe_exact^2, 2)
HideShow
    Drug - Biofeedback            Drug - Diet     Biofeedback - Diet 
                 11.62                  11.47                  12.58 
Mean(1, 2, 3) - Combin 
                 10.17 
HideShow
round(do.call(rbind, Map(
  function(cw, cv) contrast_ci_heterogeneous(
    cw, Summary_5_4$mean, Summary_5_4$s2, Summary_5_4$n, cv),
  Contrasts, CV_scheffe_exact
)), 2)
HideShow
                       psi_hat   se  lower upper
Drug - Biofeedback        5.83 5.72 -13.67 25.34
Drug - Diet               3.33 4.08 -10.50 17.17
Biofeedback - Diet       -2.50 5.28 -21.24 16.24
Mean(1, 2, 3) - Combin   11.94 3.03   2.28 21.61
HideShow
# Degrees of freedom rounded down, as the book's appendix tables require.
CV_scheffe_table <- sqrt(df_between * qf(1 - 0.05, df1 = df_between,
                                         df2 = floor(df_heterogeneous)))
round(CV_scheffe_table^2, 2)
HideShow
    Drug - Biofeedback            Drug - Diet     Biofeedback - Diet 
                 12.20                  11.59                  13.04 
Mean(1, 2, 3) - Combin 
                 10.23 
HideShow
#> 12.20, 11.59, 13.04, 10.23 — match the 12.21, 11.58, 13.05, 10.23 of
#> Table 5.10, book p. 234

round(do.call(rbind, Map(
  function(cw, cv) contrast_ci_heterogeneous(
    cw, Summary_5_4$mean, Summary_5_4$s2, Summary_5_4$n, cv),
  Contrasts, CV_scheffe_table
)), 2)
HideShow
                       psi_hat   se  lower upper
Drug - Biofeedback        5.83 5.72 -14.16 25.82
Drug - Diet               3.33 4.08 -10.57 17.23
Biofeedback - Diet       -2.50 5.28 -21.58 16.58
Mean(1, 2, 3) - Combin   11.94 3.03   2.25 21.64
HideShow
#> -14.16 to 25.82, -10.57 to 17.23, -21.58 to 16.58, 2.25 to 21.64 —
#> the -14.17 to 25.83, -10.56 to 17.23, -21.59 to 16.59, 2.25 to 21.64 of
#> Table 5.10, book p. 234, to within the hundredth that the book's rounded
#> critical values and standard errors move the endpoints
The same intervals in DMAR

cv_scheffe() returns the multiplier, and ci_scheffe() builds the whole set of simultaneous intervals from the raw data given a matrix whose columns are the cc-weights.

HideShow
cv_scheffe(alpha_level = 0.05, df_numerator = 3, df_denominator = 30)
term value area_less area_greater
upper_cv 2.961 0.950 0.050
HideShow
#> 2.961 — its square, 8.77, is the Scheffé critical value of Table 5.8,
#> book p. 232

Contrast_Matrix <- do.call(cbind, Contrasts)
Contrast_Matrix
HideShow
     Drug - Biofeedback Drug - Diet Biofeedback - Diet Mean(1, 2, 3) - Combin
[1,]                  1           1                  0              0.3333333
[2,]                 -1           0                  1              0.3333333
[3,]                  0          -1                 -1              0.3333333
[4,]                  0           0                  0             -1.0000000
HideShow
ci_scheffe(x = blood_pressure$sbp, group = blood_pressure$Treatment,
           contrasts = Contrast_Matrix)
contrast estimate se F_value ci_lower ci_upper p_adjusted
Drug - Biofeedback 5.833 4.668 0.521 -8.397 20.064 0.6730
Drug - Diet 3.333 4.668 0.170 -10.897 17.564 0.9154
Biofeedback - Diet -2.500 4.668 0.096 -16.730 11.730 0.9616
Mean(1, 2, 3) - Combin 11.944 3.811 3.274 0.325 23.564 0.0424

Confidence level: 95%, simultaneous interval (Scheffé)

HideShow
#> -8.397 to 20.064, -10.897 to 17.564, -16.730 to 11.730, 0.325 to 23.564 —
#> the same intervals the hand computation gives, matching Table 5.10,
#> book p. 234, and adjusted p values of .6730, .9154, .9616 for the three
#> pairwise contrasts, matching that table's .673, .915, .962

5.8 — Other Multiple-Comparison Procedures

5.8.1 — Dunnett’s Procedure for Comparisons with a Control

When every test of interest compares one group with each of the other a−1a-1 groups, Dunnett’s procedure exploits the correlation among those comparisons and so uses a smaller critical value than either Bonferroni or Tukey would.

5.8.2 — Numerical Example

Here the combination treatment plays the role of the control, and the three single treatments are each compared with it. glht() from multcomp takes the fitted aov() object; its Dunnett contrasts are formed against the first level of the factor, so the combination treatment is released to that position first. The adjusted pp values and simultaneous limits are obtained by numerical integration over a multivariate tt, which involves random sampling, so the seed is set on the page.

HideShow
set.seed(113)

blood_pressure_control <- blood_pressure |>
  mutate(Treatment = relevel(Treatment, ref = "Combination"))

ANOVA_Control    <- aov(sbp ~ Treatment, data = blood_pressure_control)
Results_Dunnett  <- glht(ANOVA_Control, linfct = mcp(Treatment = "Dunnett"))
summary(Results_Dunnett)
HideShow

     Simultaneous Tests for General Linear Hypotheses

Multiple Comparisons of Means: Dunnett Contrasts


Fit: aov(formula = sbp ~ Treatment, data = blood_pressure_control)

Linear Hypotheses:
                                Estimate Std. Error t value Pr(>|t|)  
Drug Therapy - Combination == 0   15.000      4.668   3.214   0.0117 *
Biofeedback - Combination == 0     9.167      4.668   1.964   0.1527  
Diet - Combination == 0           11.667      4.668   2.500   0.0544 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Adjusted p values reported -- single-step method)
HideShow
confint(Results_Dunnett)
HideShow

     Simultaneous Confidence Intervals

Multiple Comparisons of Means: Dunnett Contrasts


Fit: aov(formula = sbp ~ Treatment, data = blood_pressure_control)

Quantile = 2.5391
95% family-wise confidence level
 

Linear Hypotheses:
                                Estimate lwr     upr    
Drug Therapy - Combination == 0 15.0000   3.1484 26.8516
Biofeedback - Combination == 0   9.1667  -2.6849 21.0183
Diet - Combination == 0         11.6667  -0.1849 23.5183
HideShow
#> the drug-versus-combination interval runs from about 3 to 27, the
#> "approximately 3 to 27" of book p. 235 for Table 5.11

The Dunnett intervals are narrower than the corresponding Tukey intervals of Table 5.7, which is the gain from giving up all comparisons among the three single treatments.

The same intervals in DMAR

cv_dunnett() gives the critical value, which can be checked against the book’s appendix. ci_dunnett() builds the intervals from the raw data with the control named rather than released, and evaluates the Dunnett quantile deterministically, so its limits match the book’s SAS output to three decimals rather than to simulation error.

HideShow
cv_dunnett(alpha_level = 0.05, df = df_error, n_comparisons = a - 1)
term value area_less area_greater
upper_cv 2.540 0.950 0.050
HideShow
#> 2.540 — the df = 20, a = 4 entry of Appendix Table A.6 (book p. 990),
#> smaller than the Tukey critical t of 2.799

ci_dunnett(x = blood_pressure$sbp, group = blood_pressure$Treatment,
           control = "Combination")
contrast mean_difference se t_value ci_lower ci_upper p_adjusted
Drug Therapy - Combination 15.000 4.668 3.214 3.143 26.857 0.0117
Biofeedback - Combination 9.167 4.668 1.964 -2.691 21.024 0.1528
Diet - Combination 11.667 4.668 2.500 -0.191 23.524 0.0544

Confidence level: 95%, simultaneous interval (Dunnett)

HideShow
#> 3.143 to 26.857, -2.691 to 21.024, and -0.191 to 23.524 — the intervals of
#> Table 5.14, as read back in the text of book p. 242 (which quotes 2.691,
#> 21.02, and 23.52)

5.8.3 — Procedures for Comparisons With the Best

Hsu’s procedure answers a different question: which treatment is best? It reuses the Dunnett critical value, but the group that plays the role of the control is not known before the data are seen — it is the group with the most desirable sample mean. For blood pressure, low is best.

5.8.4 — Numerical Example

Unconstrained intervals

The steps are those in the lower half of Table 5.12. Identify the group with the smallest sample mean, form two-sided Dunnett intervals comparing every other group with it, and then obtain an interval for the best-looking group itself by reversing the signs of the limits of the interval for the group with the second smallest mean.

HideShow
group_means <- Summary_5_4$mean
names(group_means) <- as.character(Summary_5_4$Treatment)
sort(group_means)
HideShow
 Combination  Biofeedback         Diet Drug Therapy 
    81.83333     91.00000     93.50000     96.83333 
HideShow
best_group <- names(which.min(group_means))
best_group
HideShow
[1] "Combination"
HideShow
#> Combination, with a mean of 81.83 — matches book p. 242

second_best <- names(sort(group_means))[2]
second_best
HideShow
[1] "Biofeedback"
HideShow
#> Biofeedback, with a mean of 91.00 — matches book p. 242

Unconstrained <- ci_dunnett(x = blood_pressure$sbp,
                            group = blood_pressure$Treatment,
                            control = best_group)
Unconstrained
contrast mean_difference se t_value ci_lower ci_upper p_adjusted
Drug Therapy - Combination 15.000 4.668 3.214 3.143 26.857 0.0117
Biofeedback - Combination 9.167 4.668 1.964 -2.691 21.024 0.1528
Diet - Combination 11.667 4.668 2.500 -0.191 23.524 0.0544

Confidence level: 95%, simultaneous interval (Dunnett)

HideShow
# Step 5: reverse the signs of the second-best group's limits to obtain an
# interval for the group with the smallest mean.
unconstrained_frame <- as.data.frame(Unconstrained)
second_row <- grep(second_best, unconstrained_frame$contrast)
round(-rev(c(unconstrained_frame$ci_lower[second_row],
             unconstrained_frame$ci_upper[second_row])), 3)
HideShow
[1] -21.024   2.691
HideShow
#> -21.024 and 2.691 — matches book p. 242

That interval contains zero, so biofeedback, diet, and the combination treatment all remain candidates for best; only drug therapy is ruled out. The book’s reading of the same numbers is that the combination therapy is at most 2.69 units worse than whichever treatment is truly best, while biofeedback and diet could be as much as 21.02 and 23.52 units worse.

Constrained intervals

If there is no interest in estimating by how much the best treatment is best, the constrained intervals of Table 5.13 are available instead: one-sided Dunnett upper limits, one-sided lower limits, and then a lower limit of zero substituted wherever the one-sided lower limit came out positive.

HideShow
Upper_Limits <- ci_dunnett(x = blood_pressure$sbp,
                           group = blood_pressure$Treatment,
                           control = best_group, alternative = "less")
Upper_Limits
contrast mean_difference se t_value ci_lower ci_upper p_adjusted
Drug Therapy - Combination 15.000 4.668 3.214 -Inf 25.233 0.9999
Biofeedback - Combination 9.167 4.668 1.964 -Inf 19.399 0.9971
Diet - Combination 11.667 4.668 2.500 -Inf 21.899 0.9994

Confidence level: 95%, simultaneous interval (Dunnett)

HideShow
#> upper limits 25.233 for drug, 19.399 for biofeedback, and 21.899 for diet
#> — match the "Upper Limits" panel of Table 5.15, book p. 243

Lower_Limits <- ci_dunnett(x = blood_pressure$sbp,
                           group = blood_pressure$Treatment,
                           control = best_group, alternative = "greater")
Lower_Limits
contrast mean_difference se t_value ci_lower ci_upper p_adjusted
Drug Therapy - Combination 15.000 4.668 3.214 4.767 Inf 0.0059
Biofeedback - Combination 9.167 4.668 1.964 -1.066 Inf 0.0765
Diet - Combination 11.667 4.668 2.500 1.434 Inf 0.0272

Confidence level: 95%, simultaneous interval (Dunnett)

HideShow
#> lower limits 4.767, -1.066, and 1.434 in the same order — match the
#> "Lower Limits" panel of Table 5.15, book p. 243
HideShow
upper <- as.data.frame(Upper_Limits)
lower <- as.data.frame(Lower_Limits)

# Step 4: a positive one-sided lower limit becomes a lower limit of zero.
final_limits <- data.frame(
  Group = sub(paste0(" - ", best_group), "", upper$contrast),
  Lower = pmin(lower$ci_lower, 0),
  Upper = upper$ci_upper
)

# Step 5: the interval for the group with the smallest mean, from the
# second-smallest group's reversed limits.
second_row <- grep(second_best, final_limits$Group)
final_limits <- rbind(
  final_limits,
  data.frame(Group = best_group,
             Lower = -final_limits$Upper[second_row],
             Upper = -final_limits$Lower[second_row])
)
final_limits[, c("Lower", "Upper")] <- round(final_limits[, c("Lower", "Upper")], 2)
final_limits
HideShow
         Group  Lower Upper
1 Drug Therapy   0.00 25.23
2  Biofeedback  -1.07 19.40
3         Diet   0.00 21.90
4  Combination -19.40  1.07
HideShow
#> drug 0.00 to 25.23, biofeedback -1.07 to 19.40, diet 0.00 to 21.90, and
#> combination -19.40 to 1.07 — match the final limits of Table 5.15,
#> book p. 243

Both the combination and the biofeedback intervals contain zero, so one of those two is the best treatment with 95% confidence. The constrained intervals rule out more treatments than the unconstrained ones did, at the cost of saying nothing about how much better the best treatment is.

5.8.5 — Fisher’s LSD (Protected tt)

Fisher’s LSD tests the omnibus hypothesis first and, if it is rejected, tests individual contrasts at αPC=.05\alpha_{PC} = .05. The book’s objection is that the omnibus test protects only the complete null hypothesis. Its illustration (p. 244) imagines eleven groups of which ten share a common population mean: the omnibus test is then rejected almost always, after which the ten identical groups receive no protection at all, and the probability of at least one spurious difference among them is given as approximately .60 rather than .05.

The companion simulation below puts numbers on that second stage directly: ten groups drawn from one population, all 45 pairwise comparisons tested at αPC=.05\alpha_{PC} = .05 against the pooled error term. The book states the approximate value without fixing a sample size, so the figure below is an illustration of the magnitude rather than a reproduction of a printed quantity.

HideShow
set.seed(113)

n_replications    <- 2000
groups_identical  <- 10
n_per_group       <- 10
df_error_lsd      <- groups_identical * (n_per_group - 1)
pairs_lsd         <- combn(groups_identical, 2)
critical_t        <- qt(1 - 0.05 / 2, df = df_error_lsd)

any_significant <- replicate(n_replications, {
  y    <- matrix(rnorm(groups_identical * n_per_group), ncol = groups_identical)
  mean_j <- colMeans(y)
  MS_W_j <- mean(apply(y, 2, var))
  t_obs  <- abs(mean_j[pairs_lsd[1, ]] - mean_j[pairs_lsd[2, ]]) /
    sqrt(MS_W_j * 2 / n_per_group)
  any(t_obs > critical_t)
})

c(number_of_pairs = ncol(pairs_lsd), rate = mean(any_significant))
HideShow
number_of_pairs            rate 
        45.0000          0.6175 

The rate is an order of magnitude above .05 and in the neighbourhood of the .60 the book reports, which is the point: the second stage of the LSD leaves the true part of a partially true null hypothesis unprotected.

5.9 — False Discovery Rate

Benjamini and Hochberg’s Linear Step Up (LSU) procedure compares the ordered pp values with a sliding scale of critical values (i/m)α(i/m)\alpha. The book works an example with m=5m = 5 and the pp values .029, .026, .167, .048, and .001 (p. 248).

HideShow
p_raw     <- c(.029, .026, .167, .048, .001)
m         <- length(p_raw)
alpha_FDR <- 0.05

p_sorted       <- sort(p_raw)
i              <- 1:m
critical_value <- (i / m) * alpha_FDR

data.frame(
  Rank_i         = i,
  P_Value        = p_sorted,
  Critical_Value = critical_value,
  Below_Critical = p_sorted < critical_value
)
HideShow
  Rank_i P_Value Critical_Value Below_Critical
1      1   0.001           0.01           TRUE
2      2   0.026           0.02          FALSE
3      3   0.029           0.03           TRUE
4      4   0.048           0.04          FALSE
5      5   0.167           0.05          FALSE
HideShow
# Step 4: k is the largest rank whose p value falls below its critical value.
k <- max(i[p_sorted < critical_value])
k
HideShow
[1] 3
HideShow
#> 3 — matches book p. 248

Reading the table from the bottom up, as the procedure prescribes: .167 is not below .05, .048 is not below .040, and .029 is below .030, so k=3k = 3 and testing stops. Step 5 then rejects every hypothesis of rank 3 or lower — the second-ranked pp value of .026 is rejected too, even though it is not itself below its own critical value of .020. That is why the last column above is labelled by what it compares rather than by a decision.

The same decision from base R’s p.adjust()

The LSU procedure is exactly the Benjamini–Hochberg adjustment, which base R implements directly. DMAR does not re-wrap it, so p.adjust() is the route to adjusted pp values for a reader who wants them rather than a step-up table.

HideShow
p.adjust(p_raw, method = "BH")
HideShow
[1] 0.04833333 0.04833333 0.16700000 0.06000000 0.00500000
HideShow
sum(p.adjust(p_raw, method = "BH") <= alpha_FDR)
HideShow
[1] 3
HideShow
#> 3 — the same three rejections the step-up table produced

5.11 — Statistical Power

Nothing about a contrast’s observed FF changes when other contrasts are tested alongside it. What changes is the critical value, and therefore the power. Section 5.11 computes that power from first principles, and the book prints the R code that does it (p. 253). The planning scenario is a follow-up to the Kroes et al. electroconvulsive therapy study: three groups with presumed means of 25, 34, and 37, a population standard deviation of 12, and 25 participants per group.

HideShow
a_power  <- 3
n_power  <- 25
N_total  <- a_power * n_power
sigma    <- 12
alpha_EW <- 0.05
mu       <- c(A = 25, B = 34, C = 37)

# Equation 4.56 for f-squared, then Equation 4.49 for the noncentrality
# parameter lambda.
noncentrality <- function(psi, sum_c_squared) {
  f_squared <- psi^2 / (a_power * sigma^2 * sum_c_squared)
  N_total * f_squared
}

planned_contrasts <- list(
  "A vs B"       = list(psi = mu["A"] - mu["B"],               sum_c_squared = 2),
  "A vs C"       = list(psi = mu["A"] - mu["C"],               sum_c_squared = 2),
  "B vs C"       = list(psi = mu["B"] - mu["C"],               sum_c_squared = 2),
  "A vs B and C" = list(psi = mu["A"] - mean(mu[c("B", "C")]),
                        sum_c_squared = 1 + 0.25 + 0.25)
)

lambda <- vapply(planned_contrasts,
                 function(z) noncentrality(z$psi, z$sum_c_squared),
                 numeric(1))
round(lambda, 2)
HideShow
      A vs B       A vs C       B vs C A vs B and C 
        7.03        12.50         0.78        12.76 
HideShow
#> 7.03, 12.50, 0.78, 12.76 — match the Lambda rows of Tables 5.18, 5.19,
#> and 5.20, book pp. 254 and 255

The three critical values are the ones developed earlier in the chapter, now evaluated for this design. Only Bonferroni’s depends on CC.

HideShow
CV_bonferroni_power <- function(C) qf(1 - alpha_EW / C, df1 = 1,
                                      df2 = N_total - a_power)
CV_tukey_power   <- qtukey(1 - alpha_EW, nmeans = a_power,
                           df = N_total - a_power)^2 / 2
CV_scheffe_power <- (a_power - 1) * qf(1 - alpha_EW, df1 = a_power - 1,
                                       df2 = N_total - a_power)

round(c(Bonferroni_C2 = CV_bonferroni_power(2),
        Bonferroni_C3 = CV_bonferroni_power(3),
        Bonferroni_C4 = CV_bonferroni_power(4),
        Tukey         = CV_tukey_power,
        Scheffe       = CV_scheffe_power), 2)
HideShow
Bonferroni_C2 Bonferroni_C3 Bonferroni_C4         Tukey       Scheffe 
         5.24          6.01          6.56          5.73          6.25 
HideShow
#> 5.24, 6.01, 6.56, 5.73, 6.25 — match the critical values of Tables 5.18,
#> 5.19, and 5.20, book pp. 254 and 255

# Power is the probability that a noncentral F exceeds the critical value.
power_contrast <- function(critical_value, lambda) {
  1 - pf(critical_value, df1 = 1, df2 = N_total - a_power, ncp = lambda)
}

power_table <- function(which_contrasts, C, tukey = TRUE) {
  l  <- lambda[which_contrasts]
  cv <- CV_bonferroni_power(C)
  out <- rbind(
    Lambda               = round(l, 2),
    "CV for Bonferroni"  = round(cv, 2),
    "Power for Bonferroni" = round(power_contrast(cv, l), 2),
    "CV for Tukey"       = if (tukey) round(CV_tukey_power, 2) else NA,
    "Power for Tukey"    = if (tukey) round(power_contrast(CV_tukey_power, l), 2) else NA,
    "CV for Scheffe"     = round(CV_scheffe_power, 2),
    "Power for Scheffe"  = round(power_contrast(CV_scheffe_power, l), 2)
  )
  colnames(out) <- which_contrasts
  out
}
Two planned comparisons, Table 5.18
HideShow
power_table(c("A vs B", "A vs C"), C = 2)
HideShow
                     A vs B A vs C
Lambda                 7.03  12.50
CV for Bonferroni      5.24   5.24
Power for Bonferroni   0.64   0.89
CV for Tukey           5.73   5.73
Power for Tukey        0.60   0.87
CV for Scheffe         6.25   6.25
Power for Scheffe      0.56   0.85
HideShow
#> Bonferroni power .64 and .89, Tukey .60 and .87, Scheffé .56 and .85 —
#> matches Table 5.18, book p. 254

With only two planned pairwise comparisons the Bonferroni critical value is the smallest of the three, so Bonferroni gives the most power. Power for the Group A versus Group C comparison is good; power for Group A versus Group B is marginal at best.

All pairwise comparisons, Table 5.19
HideShow
power_table(c("A vs B", "A vs C", "B vs C"), C = 3)
HideShow
                     A vs B A vs C B vs C
Lambda                 7.03  12.50   0.78
CV for Bonferroni      6.01   6.01   6.01
Power for Bonferroni   0.58   0.86   0.06
CV for Tukey           5.73   5.73   5.73
Power for Tukey        0.60   0.87   0.07
CV for Scheffe         6.25   6.25   6.25
Power for Scheffe      0.56   0.85   0.06
HideShow
#> Bonferroni power .58, .86, .06, Tukey .60, .87, .07, Scheffé .56, .85, .06
#> — matches Table 5.19, book p. 254

Three things change. Power for Groups B versus C is dismal, because their mean difference corresponds to a standardized mean difference of only 3/12=0.253/12 = 0.25. Tukey now beats Bonferroni, because CC has risen to 3 while the Tukey critical value does not depend on CC. And the Tukey and Scheffé columns are identical to those in Table 5.18 for exactly that reason.

All pairwise comparisons plus a complex contrast, Table 5.20
HideShow
power_table(c("A vs B", "A vs C", "B vs C", "A vs B and C"), C = 4,
            tukey = FALSE)
HideShow
                     A vs B A vs C B vs C A vs B and C
Lambda                 7.03  12.50   0.78        12.76
CV for Bonferroni      6.56   6.56   6.56         6.56
Power for Bonferroni   0.54   0.83   0.05         0.84
CV for Tukey             NA     NA     NA           NA
Power for Tukey          NA     NA     NA           NA
CV for Scheffe         6.25   6.25   6.25         6.25
Power for Scheffe      0.56   0.85   0.06         0.86
HideShow
#> Bonferroni power .54, .83, .05, .84 and Scheffé .56, .85, .06, .86 —
#> matches Table 5.20, book p. 255. Tukey is not applicable once a complex
#> contrast is tested, which is why the book prints N/A in those rows.

The complex contrast has the largest noncentrality parameter and so the largest power. Bonferroni’s critical value has risen again with CC, and Scheffé is now the better choice — and it would be the only legitimate choice had these four contrasts been chosen after looking at the data.

Complete, minimal, and proportional power

Every power value above is individual power: the probability that one particular contrast reaches significance. Section 5.11 also distinguishes complete power (all false null hypotheses rejected, also called all-pairs power), minimal power (at least one rejected, also called any-pairs power), and proportional power (the expected proportion of false null hypotheses rejected). Complete and minimal power have no textbook closed form, so the book obtains them by simulation, and Table 5.21 reports the results of 10,000 replications of a SAS macro.

The scenario is a Solomon four-group design with 30 participants per condition, population means of 54, 54, 46, and 46, a population standard deviation of 10, and Tukey’s method controlling αEW\alpha_{EW} at .05. Two of the six pairwise comparisons are true null hypotheses; power concerns only the other four.

The book does not print code for this table, and no function in base R or in DMAR computes these three quantities, so this is a place where following along means building the calculation. We do it twice: first by simulation, the way the book does, and then exactly, which this particular design turns out to allow. The second route is what makes the first one interpretable.

HideShow
set.seed(113)

n_replications <- 10000   # the same number of replications the book used
n_per_group    <- 30
mu_solomon     <- c(54, 54, 46, 46)
sigma_solomon  <- 10
group_solomon  <- factor(rep(1:4, each = n_per_group))

# The four false null hypotheses are the high-versus-low pairs.
false_nulls <- c("3-1", "4-1", "3-2", "4-2")

simulation <- t(replicate(n_replications, {
  y <- rnorm(length(group_solomon),
             mean = rep(mu_solomon, each = n_per_group),
             sd   = sigma_solomon)
  p_adjusted <- TukeyHSD(aov(y ~ group_solomon))$group_solomon[, "p adj"]
  rejected   <- p_adjusted[false_nulls] < 0.05
  c(complete = all(rejected), minimal = any(rejected),
    proportional = mean(rejected))
}))

estimates <- colMeans(simulation)
round(estimates, 4)
HideShow
    complete      minimal proportional 
      0.3620       0.9333       0.6824 
HideShow
#> .3620, .9333, .6824; Table 5.21 prints .35930, .94620, and .68773,
#> book p. 256

# A simulated power is an estimate, so it has a standard error. Report it.
# Complete and minimal power are proportions, so theirs is the binomial
# sqrt(p(1 - p)/reps). Proportional power is not a proportion: each replication
# contributes 0, .25, .5, .75 or 1, so the binomial formula overstates it by
# half. The column standard deviation is right for all three.
round(apply(simulation, 2, sd) / sqrt(n_replications), 4)
HideShow
    complete      minimal proportional 
      0.0048       0.0025       0.0030 
HideShow
#> .0048, .0025, .0030 — the Monte Carlo standard errors of the three
#> estimates above. The .0030 is worth noting: it matches the .00296 spread
#> that 2,000 independent runs of this simulation show below, which is the
#> check that the formula is the right one.

Table 5.21 reports .35930 for complete power with a simulation interval of .350 to .369, .94620 for minimal power with an interval of .942 to .951, and .68773 for proportional power with an interval of .682 to .694 (book p. 256). Complete power and proportional power from the run above fall inside those intervals. Minimal power does not: it comes out about .013 lower than the book’s figure.

It is tempting to read that as a discrepancy between SAS and R and go looking for a difference in how the Tukey decision is made. The Monte Carlo standard errors printed above suggest a prior question. Both figures are estimates from 10,000 replications, and the standard error of such an estimate is about .0024. How much of the third decimal can one run of this size actually support? The rest of this section answers that, and the answer makes the two published figures easier to understand than any difference in software would.

The same experiment, at a fraction of the cost

Answering that question means running the whole study many times over, and the chunk above is too slow for that: it builds 10,000 data sets of 120 observations and fits 10,000 analyses of variance. Almost none of that work is needed. In a balanced one-way design the group means and MSWMS_W are sufficient for every pairwise comparison, so the group means can be drawn straight from their sampling distribution, Y‾j∼N(μj,σ2/n)\bar{Y}_j \sim N(\mu_j, \sigma^2/n), and MSWMS_W straight from its scaled chi-square distribution, independently of them. Tukey’s rule then rejects a pair when the absolute difference of two drawn means exceeds q.95MSW/nq_{.95}\sqrt{MS_W/n}. It is the same experiment, simulated at the level of its sufficient statistics rather than observation by observation, and it runs about a thousand times faster.

HideShow
# Complete, minimal, and proportional power for a balanced one-way design,
# simulated from the sufficient statistics. The procedure argument supplies
# the critical value on the mean-difference scale, in units of
# sqrt(MS_within / n), so "bonferroni" and "scheffe" are available too.
mcp_power <- function(means, n, sigma, alpha = 0.05,
                      procedure = c("tukey", "bonferroni", "scheffe", "none"),
                      reps = 10000) {
  procedure  <- match.arg(procedure)
  a          <- length(means)
  df_within  <- a * (n - 1)
  pairs      <- combn(a, 2, simplify = FALSE)
  false_null <- Filter(function(p) means[p[1]] != means[p[2]], pairs)
  true_null  <- Filter(function(p) means[p[1]] == means[p[2]], pairs)

  critical <- switch(procedure,
    tukey      = qtukey(1 - alpha, nmeans = a, df = df_within),
    bonferroni = sqrt(2) * qt(1 - alpha / (2 * length(pairs)), df = df_within),
    scheffe    = sqrt(2 * (a - 1) * qf(1 - alpha, df1 = a - 1, df2 = df_within)),
    none       = sqrt(2) * qt(1 - alpha / 2, df = df_within))

  # One row per replication: the group means, plus that run's own MS_within.
  means_sim <- matrix(rnorm(reps * a, mean = rep(means, each = reps),
                            sd = sigma / sqrt(n)),
                      nrow = reps, ncol = a)
  MS_within <- sigma^2 * rchisq(reps, df = df_within) / df_within
  threshold <- critical * sqrt(MS_within / n)

  n_rejected <- integer(reps)
  for (p in false_null)
    n_rejected <- n_rejected +
      (abs(means_sim[, p[1]] - means_sim[, p[2]]) > threshold)

  any_true_rejected <- rep(FALSE, reps)
  for (p in true_null)
    any_true_rejected <- any_true_rejected |
      (abs(means_sim[, p[1]] - means_sim[, p[2]]) > threshold)

  estimate <- c(complete     = mean(n_rejected == length(false_null)),
                minimal      = mean(n_rejected > 0),
                proportional = mean(n_rejected) / length(false_null),
                true_FWE     = mean(any_true_rejected))

  # If every population mean is the same there is no false null hypothesis to
  # reject, so the three power quantities are undefined rather than 1, 0, and
  # 0/0. The familywise error rate in the last row is still exactly the
  # quantity one wants in that case.
  if (length(false_null) == 0)
    estimate[c("complete", "minimal", "proportional")] <- NA_real_

  # The Monte Carlo standard error of a mean is the standard deviation of the
  # quantity being averaged over the square root of the number of replications.
  # For complete, minimal and the familywise rate that reduces to the binomial
  # formula; for proportional power, which averages 0, .25, .5, .75 and 1, it
  # does not, and the binomial formula would overstate it.
  mc_se <- c(complete     = stats::sd(n_rejected == length(false_null)),
             minimal      = stats::sd(n_rejected > 0),
             proportional = stats::sd(n_rejected / max(1, length(false_null))),
             true_FWE     = stats::sd(any_true_rejected)) / sqrt(reps)
  if (length(false_null) == 0)
    mc_se[c("complete", "minimal", "proportional")] <- NA_real_

  data.frame(quantity = names(estimate),
             estimate = unname(estimate),
             MC_SE    = unname(mc_se))
}

set.seed(113)
mcp_power(means = mu_solomon, n = n_per_group, sigma = sigma_solomon,
          procedure = "tukey", reps = n_replications)
HideShow
      quantity estimate       MC_SE
1     complete  0.37190 0.004833361
2      minimal  0.93790 0.002413492
3 proportional  0.69005 0.003023700
4     true_FWE  0.02090 0.001430568
HideShow
#> .37190, .93790, .69005, and a true familywise error rate of .02090

Three sets of numbers are now in hand for one scenario: the book’s .35930, .94620, .68773; the raw-data run’s .3620, .9333, .6824; and this run’s .37190, .93790, .69005. They are three estimates of the same three quantities, differing only in the random stream each used. The fourth row is a bonus the book’s table does not report — the proportion of replications in which at least one of the two true null hypotheses was rejected, about .021, which is Tukey’s method being conservative, as it is designed to be.

The exact answer, for this design

Complete and minimal power have no general closed form, which is why the book simulates. For this scenario they can nonetheless be computed exactly, because the design is balanced and the four population means take only two values. Work in units of the standard error of a group mean, σ/n\sigma/\sqrt{n}, and condition on MSWMS_W, so that the rejection threshold is a fixed number τ\tau. Condition also on the two low-group means. A high-group mean then rejects against both of them when a single standard normal variable lands below the smaller or above the larger — or, should the two low means happen to lie more than 2τ2\tau apart, in the gap between them — and it rejects against neither when it lands in the overlap of the two acceptance windows, which is non-empty exactly when the two low means lie closer than 2τ2\tau. Each window is a difference of two normal distribution functions. The two high-group means are independent and carry the same two probabilities, so the chance that all four false null hypotheses are rejected is the first probability squared, and one minus the square of the second is minimal power. Averaging over the two low-group means and over MSWMS_W leaves a three-fold integral, and because each integrand is smooth and bounded, an equal-probability grid evaluates it to more decimal places than anyone needs.

HideShow
# Exact complete, minimal, and proportional power by quadrature, for the
# pattern of this scenario: four groups, two at a high mean and two at a low
# one, balanced, Tukey at alpha. No simulation and so no Monte Carlo error;
# the only error is the grid's, which is past the fourth decimal here.
exact_mcp <- function(means, n, sigma, alpha = 0.05,
                      n_grid_MS = 400, n_grid_mean = 320) {
  a <- length(means)
  stopifnot(a == 4, length(unique(means)) == 2,
            sum(means == max(means)) == 2)
  df_within <- a * (n - 1)
  SE_mean   <- sigma / sqrt(n)
  critical  <- qtukey(1 - alpha, nmeans = a, df = df_within)

  # MS_within / sigma^2 on an equal-probability grid of its chi-square law,
  # turned into the Tukey threshold in units of the standard error of a mean.
  MS_scaled <- qchisq((seq_len(n_grid_MS) - 0.5) / n_grid_MS,
                      df = df_within) / df_within
  tau   <- critical * sqrt(MS_scaled)
  delta <- diff(range(means)) / SE_mean   # mean separation, same units

  # The two low-group means, also on an equal-probability grid.
  z     <- qnorm((seq_len(n_grid_mean) - 0.5) / n_grid_mean)
  upper <- outer(z, z, pmax)
  lower <- outer(z, z, pmin)

  by_threshold <- vapply(tau, function(t) {
    hi <- t - delta   # how far a high-group mean must sit above the larger one
    lo <- t + delta   # and how far below the smaller one, to reject
    # The window strictly between the two low means and the window in which
    # neither comparison rejects are the two signs of one difference: whichever
    # is non-empty, the other is not.
    between        <- pnorm(upper - lo) - pnorm(lower + hi)
    reject_both    <- pnorm(lower - lo) + pnorm(upper + hi, lower.tail = FALSE) +
                      pmax(0, between)
    reject_neither <- pmax(0, -between)
    c(complete     = mean(reject_both^2),
      nothing      = mean(reject_neither^2),
      proportional = pnorm(hi / sqrt(2), lower.tail = FALSE) +
                     pnorm(-lo / sqrt(2)),
      true_FWE     = 1 - (1 - 2 * pnorm(t / sqrt(2), lower.tail = FALSE))^2)
  }, numeric(4))

  c(complete     = mean(by_threshold["complete", ]),
    minimal      = 1 - mean(by_threshold["nothing", ]),
    proportional = mean(by_threshold["proportional", ]),
    true_FWE     = mean(by_threshold["true_FWE", ]))
}

exact_solomon <- exact_mcp(means = mu_solomon, n = n_per_group,
                           sigma = sigma_solomon)
round(exact_solomon, 4)
HideShow
    complete      minimal proportional     true_FWE 
      0.3655       0.9405       0.6880       0.0205 
HideShow
#> complete .3655, minimal .9405, proportional .6880, true familywise error
#> rate .0205 — the exact counterparts of the three simulated values in
#> Table 5.21, book p. 256

Proportional power needs no grid at all, and it is worth seeing why. It is the expected proportion of the four false null hypotheses rejected, which by linearity of expectation is just the individual power of one such comparison. A single mean difference divided by its estimated standard error follows a noncentral tt distribution, and Tukey’s rule compares it to q.95/2q_{.95}/\sqrt{2}, so one line of base R settles it.

HideShow
# Individual power of one high-versus-low comparison under Tukey's rule, with
# df = 4 * (30 - 1) = 116 and ncp = 8 / sqrt(2 * sigma^2 / n).
1 - diff(pt(c(-1, 1) * qtukey(0.95, nmeans = 4, df = 116) / sqrt(2),
            df = 116, ncp = 8 / sqrt(2 * 100 / 30)))
HideShow
[1] 0.6880257
HideShow
#> .6880257 — agrees with the .6880 the quadrature above returns, and with
#> the .68773 of Table 5.21, book p. 256, to within that table's simulation
#> error
What one simulation run can support

With exact values in hand the earlier numbers can be placed. The exact minimal power is .9405. The book’s run returned .94620, which is 2.4 Monte Carlo standard errors above it — far enough that Table 5.21’s own interval for minimal power, (.942, .951), does not reach down to the value it brackets. That is not a flaw in the table: an interval of that kind misses about one time in twenty, and this is one of those times. The raw-data run at the top of this section returned .9333, which is 3.0 standard errors below the exact value and well out in the other tail — a run lands that low only about once in several hundred tries — but a tail is part of a distribution, not evidence of a different method. The way to see the distribution both figures come from is to run the whole 10,000-replication study over and over, which the sufficient-statistic version makes cheap enough to do on this page.

HideShow
set.seed(113)

# Two thousand independent repetitions of the book's 10,000-replication study:
# 20 million simulated experiments in a few seconds.
repeat_runs <- t(replicate(2000, {
  mcp_power(means = mu_solomon, n = n_per_group, sigma = sigma_solomon,
            procedure = "tukey", reps = n_replications)$estimate
}))
colnames(repeat_runs) <- c("complete", "minimal", "proportional", "true_FWE")

round(rbind(mean = colMeans(repeat_runs),
            SD   = apply(repeat_runs, 2, sd),
            min  = apply(repeat_runs, 2, min),
            max  = apply(repeat_runs, 2, max)), 5)
HideShow
     complete minimal proportional true_FWE
mean  0.36559 0.94050      0.68808  0.02052
SD    0.00480 0.00233      0.00296  0.00143
min   0.35020 0.93310      0.67672  0.01550
max   0.38190 0.94790      0.69900  0.02480
HideShow
#> minimal power: mean .94050 against the exact .9405, SD .00233 against the
#> .0024 that sqrt(p (1 - p) / 10000) predicts, and runs ranging from .9331
#> to .9479. Complete power: mean .36559 against the exact .3655. Proportional
#> power: mean .68808 against the exact .6880.

The means recover the exact values and the standard deviations are the Monte Carlo standard errors the formula predicts, so the simulation is doing exactly what it should. What it cannot do is pin the third decimal. The 2,000 runs of minimal power range from .9331 to .9479, and that range contains both published figures: the book’s .94620 and this page’s .9333 are both inside the spread of honest runs. Neither is evidence of anything but the random stream behind it.

HideShow
ggplot(data.frame(minimal = repeat_runs[, "minimal"]), aes(x = minimal)) +
  geom_histogram(binwidth = 0.001, fill = "grey80", colour = "white") +
  geom_vline(xintercept = exact_solomon[["minimal"]], linewidth = 1,
             colour = "#0C2340") +
  geom_vline(xintercept = 0.94620, linetype = "dashed", colour = "#0C2340") +
  geom_vline(xintercept = estimates[["minimal"]], linetype = "dotted",
             colour = "#0C2340") +
  annotate("text", x = exact_solomon[["minimal"]], y = 410, hjust = 1.1,
           label = "Exact .9405", colour = "#0C2340") +
  annotate("text", x = 0.94620, y = 330, hjust = 1.1,
           label = "Table 5.21 .94620", colour = "#0C2340") +
  annotate("text", x = estimates[["minimal"]], y = 330, hjust = -0.1,
           label = "Simulation above .9333", colour = "#0C2340") +
  labs(x     = "Estimated minimal (any-pairs) power per 10,000-replication run",
       y     = "Number of runs",
       title = "Two thousand runs of the same 10,000-replication simulation")

One more number makes the point concrete. To pin minimal power to within .001 with 95% confidence takes about 215,000 replications, not 10,000.

HideShow
# Replications needed for a half-width of .001 around a power near .9405.
ceiling(qnorm(0.975)^2 * 0.9405 * (1 - 0.9405) / 0.001^2)
HideShow
[1] 214968
HideShow
#> 214968 — about 215,000, more than twenty times the 10,000 behind Table 5.21

Two habits follow. Report a Monte Carlo standard error, or an interval, with any simulated power, as Table 5.21 does and as the first chunk of this section does; a power quoted to five decimals from 10,000 replications states several digits more than the run behind it can support. And where the design admits an exact calculation, prefer it: the quadrature above takes a few seconds, has no standard error at all, and is what tells us that both published figures are ordinary draws.

Is 30 per group enough?

The practical reading is the book’s. Thirty participants per condition give a high probability of finding something — a statistically significant pairwise difference somewhere — and only about a one-in-three chance of finding everything that is really there, which is a recipe for apparent failures to replicate. The book adds that PASS puts the sample size needed for all-pairs power of .80 at 52 per group (p. 257). The exact calculation can check that figure directly, since exact_mcp() takes nn as an argument.

HideShow
all_pairs_by_n <- vapply(50:54, function(n_group) {
  exact_mcp(means = mu_solomon, n = n_group, sigma = sigma_solomon,
            n_grid_MS = 200, n_grid_mean = 160)[["complete"]]
}, numeric(1))

round(setNames(all_pairs_by_n, 50:54), 3)
HideShow
   50    51    52    53    54 
0.771 0.785 0.799 0.812 0.824 
HideShow
#> .771, .785, .799, .812, .824 — exact all-pairs power at n = 52 is .799,
#> which matches the .80 PASS reports, book p. 257

A reader who wants the smallest nn whose exact all-pairs power reaches .80 on the nose would take 53. The difference is immaterial for planning, and it is the same lesson once more: PASS reaches 52 by simulation, so its answer carries a simulation error of its own.

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 5: Testing Several Contrasts: The Multiple-Comparisons Problem (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

Chapter 6: Trend Analysis

Open the separate reading

Code
Results
On this page

Chapter 6 moves from qualitative categories to quantitative factors, where the groups differ in amount rather than in kind. Bridging the analysis of variance of Chapters 3–5 with regression, the chapter shows how to estimate and test a linear trend, how to test for nonlinearity as a whole, and how orthogonal polynomials isolate higher order shapes such as the quadratic and the cubic.

These notes build on Chapter 1 and Chapters 3–5, where the operational aspects of R and the AMCP data sets are introduced; here we skip details already covered there. This chapter uses one data set, chapter_6_table_1, the hypothetical memory data of Table 6.1.

HideShow
# Load all of the packages used.
library(AMCP)           # the textbook's data sets
library(dplyr)          # data manipulation
library(ggplot2)        # figures
library(DMAR)           # design, measurement, and analysis
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables

6.4 — Statistical Treatment of Trend Analysis

The data of Table 6.1

The data of Table 6.1 are recall scores for 24 children, six in each of four study-time conditions: 1, 2, 3, or 4 minutes to study a list of 12 words. The dependent variable is the number of words recalled after a brief interference task. The quantitative factor here is “minutes allowed for study,” so the numbers 1 through 4 carry meaning; they are not arbitrary labels as the four hypertension treatments of Chapter 4 were.

The data come from the AMCP package, loaded above.

HideShow
data(chapter_6_table_1)
chapter_6_table_1
HideShow
   Recall Minutes
1       2       1
2       3       1
3       1       1
4       2       1
5       0       1
6       4       1
7       6       2
8       8       2
9       5       2
10      3       2
11      7       2
12      7       2
13      6       3
14      8       3
15     10       3
16      5       3
17     10       3
18      9       3
19     11       4
20     10       4
21      7       4
22      9       4
23      8       4
24      9       4

The four group means are the quantities every later calculation rests on.

HideShow
Summary_Recall <- chapter_6_table_1 |>
  group_by(Minutes) |>
  summarize(mean_Recall = mean(Recall),
            sd_Recall   = sd(Recall),
            n_Recall    = n(),
            .groups     = "drop")
Summary_Recall
HideShow
# A tibble: 4 × 4
  Minutes mean_Recall sd_Recall n_Recall
    <int>       <dbl>     <dbl>    <int>
1       1           2      1.41        6
2       2           6      1.79        6
3       3           8      2.10        6
4       4           9      1.41        6
HideShow
#> means 2, 6, 8, 9 — matches book p. 271, Table 6.1
Shared objects for the figures

The figures in this chapter all build from the recall data together with the linear and quadratic trend models the chapter fits to it. We set up those shared objects once here so each figure can refer to them: the fitted models, the group (cell) means with their model-predicted values, and the per-person residuals from each model.

HideShow
d6 <- chapter_6_table_1

# The two trend models the chapter fits to the recall data.
lin_fit  <- lm(Recall ~ Minutes, data = d6)                 # Eq. 6.23: 0.50 + 2.3 X
quad_fit <- lm(Recall ~ Minutes + I(Minutes^2), data = d6)  # Eq. 6.24

# Group (cell) means at each study time, and the model-predicted means.
group_means <- d6 |>
  group_by(Minutes) |>
  summarize(Recall = mean(Recall), .groups = "drop")
group_means$pred_lin  <- predict(lin_fit,  newdata = group_means)
group_means$pred_quad <- predict(quad_fit, newdata = group_means)

# Residuals (actual minus predicted) for every participant, for both models.
d6 <- d6 |>
  mutate(resid_lin  = Recall - predict(lin_fit,  newdata = d6),
         resid_quad = Recall - predict(quad_fit, newdata = d6))
Figure 6.1. Scatterplot of recall scores as a function of study time

A scatterplot of the 24 recall scores as a function of study time, the raw data of Table 6.1. The upward drift of the points motivates fitting a linear trend: on the whole, more study time goes with more words recalled.

HideShow
ggplot(d6, aes(Minutes, Recall)) +
  geom_point(shape = 4, size = 2.6, stroke = 0.9) +
  scale_x_continuous(breaks = 1:4) +
  scale_y_continuous(limits = c(0, 12), breaks = 0:12) +
  labs(title = "Figure 6.1. Scatterplot of recall scores as a function of study time",
       x = "Study time (minutes allotted)", y = "Recall (number of words)")
Figure 6.1. Scatterplot of recall scores as a function of study time.

Figure 6.1. Scatterplot of recall scores as a function of study time.

Two analyses of the same data

To see what the quantitative nature of the factor buys, run two different models on exactly the same data.

The first is the standard one-way ANOVA. It ignores the ordering of Minutes, treating it as four unordered categories, and asks only whether any group differs from another. Its mean square within is the error term the book uses for every trend test in this chapter, so we keep the object around.

HideShow
ANOVA_Object <- aov(Recall ~ as.factor(Minutes), data = chapter_6_table_1)
ANOVA_Result <- anova(ANOVA_Object)
ANOVA_Result
HideShow
Analysis of Variance Table

Response: Recall
                   Df Sum Sq Mean Sq F value    Pr(>F)    
as.factor(Minutes)  3  172.5    57.5  19.828 3.306e-06 ***
Residuals          20   58.0     2.9                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> SS_B = 172.5, SS_W = 58.0, MS_W = 2.9 — matches book p. 281 and Table 6.3, p. 285

The second treats Minutes as the number it is and fits a straight line, which is the model of Equation 6.2. The regression output reports the estimated slope β̂1\hat\beta_1 and intercept β̂0\hat\beta_0 directly.

HideShow
Regression_Object <- lm(Recall ~ Minutes, data = chapter_6_table_1)
Regression_Result <- summary(Regression_Object)
Regression_Result
HideShow

Call:
lm(formula = Recall ~ Minutes, data = chapter_6_table_1)

Residuals:
   Min     1Q Median     3Q    Max 
-2.800 -1.475  0.050  1.375  2.900 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   0.5000     0.9033   0.554    0.585    
Minutes       2.3000     0.3298   6.973 5.33e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.807 on 22 degrees of freedom
Multiple R-squared:  0.6885,    Adjusted R-squared:  0.6743 
F-statistic: 48.63 on 1 and 22 DF,  p-value: 5.333e-07
HideShow
#> intercept 0.50, slope 2.30 — matches book p. 274

6.4.1 — The Slope Parameter

Equation 6.7 says that the estimated slope is just the linear contrast of the group means divided by the sum of the squared contrast coefficients, where the coefficients of Equation 6.8 are cj=Xj−X‾c_j = X_j - \bar{X}. That is worth doing by hand once, because it makes the point that a “linear trend” in ANOVA is the slope of a simple regression.

HideShow
# Equation 6.8: the c-weights are deviations of X from its mean.
Summary_Recall$c_weight <- Summary_Recall$Minutes - mean(chapter_6_table_1$Minutes)
Summary_Recall
HideShow
# A tibble: 4 × 5
  Minutes mean_Recall sd_Recall n_Recall c_weight
    <int>       <dbl>     <dbl>    <int>    <dbl>
1       1           2      1.41        6     -1.5
2       2           6      1.79        6     -0.5
3       3           8      2.10        6      0.5
4       4           9      1.41        6      1.5
HideShow
#> c-weights -1.5, -0.5, 0.5, 1.5 — matches book p. 274

mean(chapter_6_table_1$Minutes)
HideShow
[1] 2.5
HideShow
#> 2.5 — matches book p. 274 (the mean study time, X-bar)

6.4.2 — Numerical Example

With the coefficients in hand, Equation 6.6 gives the linear contrast and Equation 6.7 turns it into the slope.

HideShow
C_Linear <- Summary_Recall$c_weight
MS_W     <- ANOVA_Result$"Mean Sq"[2]
  # MS_W comes from the cell means ("as.factor") ANOVA rather than from the error of the
  # straight-line `lm` model. The book explains on p. 276 why that is the recommended
  # denominator for a trend test when the factor has few distinct values.

# Equation 6.6
Psi_Linear <- sum(Summary_Recall$mean_Recall * C_Linear)
Psi_Linear
HideShow
[1] 11.5
HideShow
#> 11.5 — matches book p. 274 (psi_hat_linear = -1.5(2) - 0.5(6) + 0.5(8) + 1.5(9) = 11.5)

Sum_c_Squared <- sum(C_Linear^2)
Sum_c_Squared
HideShow
[1] 5
HideShow
#> 5.0 — matches book p. 274 (sum of squared c-weights)

# Equation 6.7
b1 <- Psi_Linear / Sum_c_Squared
b1
HideShow
[1] 2.3
HideShow
#> 2.3 — matches book p. 274 (slope = 11.5 / 5.0 = 2.3)

With the slope known, the least squares intercept completes the equation of the line.

HideShow
b0 <- mean(chapter_6_table_1$Recall) - b1 * mean(chapter_6_table_1$Minutes)
b0
HideShow
[1] 0.5
HideShow
#> 0.50 — matches book p. 274 (intercept = 6.25 - 2.3 * 2.5 = 0.50)

Every additional minute of study time is estimated to translate into an average gain of 2.3 additional words recalled. The fitted line is Ŷij=0.50+2.3Xj\hat{Y}_{ij} = 0.50 + 2.3X_j.

Figure 6.2. Sample means and estimated linear trend

The book’s Figure 6.2 plots two sets of points at each study time: the sample mean (open circles) and the mean predicted by the linear trend (filled circles), with the fitted line through the predicted means. The line passes near but not exactly through the sample means, which rise quickly from 1 to 2 minutes and then level off.

HideShow
fig_6_2_points <- rbind(
  data.frame(Minutes = group_means$Minutes, Value = group_means$Recall,
             Kind = "Sample mean"),
  data.frame(Minutes = group_means$Minutes, Value = group_means$pred_lin,
             Kind = "Predicted mean")
)
fig_6_2_points$Kind <- factor(fig_6_2_points$Kind,
                              levels = c("Sample mean", "Predicted mean"))

ggplot(fig_6_2_points, aes(Minutes, Value, shape = Kind, color = Kind)) +
  geom_abline(intercept = coef(lin_fit)[1], slope = coef(lin_fit)[2],
              color = "#0C2340", linewidth = 0.8) +
  geom_point(size = 3.6, stroke = 1) +
  scale_shape_manual(name = NULL, values = c("Sample mean" = 1, "Predicted mean" = 16)) +
  scale_color_discrete(name = NULL) +
  scale_x_continuous(breaks = 1:4) +
  scale_y_continuous(limits = c(0, 12), breaks = 0:12) +
  labs(title = "Figure 6.2. Sample means and estimated linear trend",
       x = "Study time (minutes allotted)", y = "Recall (number of words)") +
  theme(legend.position = "top")
Figure 6.2. Plot of sample means and estimated linear trend.

Figure 6.2. Plot of sample means and estimated linear trend.

6.4.3 — Hypothesis Test of Slope Parameter

The book frames the test of β1=0\beta_1 = 0 as a model comparison: the full model is the straight line of Equation 6.2 and the restricted model drops the slope (Equation 6.9). Base R carries that comparison out directly, and the resulting ER−EFE_R - E_F is exactly the sum of squares of the linear contrast promised by Equation 6.11.

HideShow
Model_Restricted <- lm(Recall ~ 1,       data = chapter_6_table_1)  # Equation 6.9
Model_Full       <- lm(Recall ~ Minutes, data = chapter_6_table_1)  # Equation 6.2
anova(Model_Restricted, Model_Full)
HideShow
Analysis of Variance Table

Model 1: Recall ~ 1
Model 2: Recall ~ Minutes
  Res.Df   RSS Df Sum of Sq      F    Pr(>F)    
1     23 230.5                                  
2     22  71.8  1     158.7 48.627 5.333e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Sum of Sq = 158.7 (= E_R - E_F = SS_linear) — matches book p. 277

The FF reported on that line (48.63) uses the straight-line model’s own error term, which is the usual choice in regression. As the book explains on p. 276, in ANOVA we instead divide by MSWMS_W from the cell means model, which is what gives the FF reported throughout the chapter.

HideShow
SS_Linear <- Psi_Linear^2 / sum(C_Linear^2 / Summary_Recall$n_Recall)
SS_Linear
HideShow
[1] 158.7
HideShow
#> 158.7 — matches book p. 277 (SS_linear = 6(11.5)^2 / 5 = 158.7)

F_Linear <- SS_Linear / MS_W
F_Linear
HideShow
[1] 54.72414
HideShow
#> 54.72 — matches book p. 277 (F = 158.7 / 2.9 = 54.72)

The linear trend is statistically significant, F(1,20)=54.72F(1, 20) = 54.72: recall increased linearly as study time increased.

6.5 — Confidence Interval and Other Effect Size Measures for the Slope Parameter

Equation 6.12 gives the confidence interval for the slope,

β̂1±Fα;1,N−aMSW∑j=1a(cj2/nj)∑j=1acj2,\hat\beta_1 \pm \sqrt{F_{\alpha;1,N-a}}\;\frac{\sqrt{MS_W \sum_{j=1}^{a} (c_j^2/n_j)}}{\sum_{j=1}^{a} c_j^2},

which differs from the Chapter 4 interval for a contrast only by the rescaling that turns ψ̂\hat\psi into β̂1\hat\beta_1. That rescaling is the whole practical difficulty: an interval computed from the raw coefficients −1.5,−0.5,0.5,1.5-1.5, -0.5, 0.5, 1.5 is an interval for ψ\psi, not for β1\beta_1, and the two differ by a factor of ∑cj2\sum c_j^2.

6.5.1 — Numerical Example

The test, from the book’s own inputs

The book’s Section 6.5.1 recomputes the linear trend test from n=6n = 6, the four means, and ∑cj2=5\sum c_j^2 = 5. Scaling the weights first (dividing each by ∑cj2\sum c_j^2) makes the contrast itself equal the slope, and the sum of squares is unchanged, because rescaling a contrast’s coefficients does not change its sum of squares.

HideShow
c_Linear        <- Summary_Recall$Minutes - mean(chapter_6_table_1$Minutes)
c_Linear_Scaled <- c_Linear / sum(c_Linear^2)
c_Linear_Scaled
HideShow
[1] -0.3 -0.1  0.1  0.3
HideShow
#> -0.3, -0.1, 0.1, 0.3 — matches book p. 278 (the scaling needed for an interval on beta_1)

Ybar <- Summary_Recall$mean_Recall
n_j  <- Summary_Recall$n_Recall

Slope_From_Contrast <- sum(c_Linear_Scaled * Ybar)
Slope_From_Contrast
HideShow
[1] 2.3
HideShow
#> 2.3 — matches book p. 274 (the scaled contrast is the slope itself)

SS_Linear_Scaled <- Slope_From_Contrast^2 / sum(c_Linear_Scaled^2 / n_j)
SS_Linear_Scaled
HideShow
[1] 158.7
HideShow
#> 158.7 — matches book p. 277 (the SS is invariant to rescaling the c-weights)

F_value <- SS_Linear_Scaled / MS_W
F_value
HideShow
[1] 54.72414
HideShow
#> 54.72 — matches book p. 277 and Table 6.3, p. 285

This is significant well beyond the .001 level, so we can assert a linear trend in the population.

The confidence interval by hand, from Equation 6.12

The hypothesis test says the slope is not zero but gives no plausible range for it. The book works the interval out by hand on p. 278, and the same arithmetic in base R gives each intermediate value it reports.

HideShow
# Critical F with 1 and N - a = 20 degrees of freedom.
F_Critical <- qf(0.95, df1 = 1, df2 = 20)
F_Critical
HideShow
[1] 4.351244
HideShow
#> 4.35 — matches book p. 278 (F_.05;1,20 = 4.35)

# Standard error of the slope: the Equation 6.12 radical divided by sum(c^2).
SE_Slope <- sqrt(MS_W * sum(C_Linear^2 / Summary_Recall$n_Recall)) / sum(C_Linear^2)
SE_Slope
HideShow
[1] 0.3109126
HideShow
#> 0.3109 — matches book p. 278 (standard error of the slope)

# Half-width (margin of error) and the interval itself.
Half_Width <- sqrt(F_Critical) * SE_Slope
Half_Width
HideShow
[1] 0.6485524
HideShow
#> 0.65 — matches book p. 278 (half width = sqrt(4.35) * 0.3109)

c(Lower = b1 - Half_Width, Upper = b1 + Half_Width)
HideShow
   Lower    Upper 
1.651448 2.948552 
HideShow
#> [1.65, 2.95] — matches book p. 278 (95% CI on the slope)

Every additional minute of study time leads to an increase of between 1.65 and 2.95 words recalled.

Intervals for the contrast and the slope in DMAR

With the original contrast weights, ci_c() gives an interval for the contrast ψ\psi. Dividing the weights by ∑cj2=5\sum c_j^2 = 5 gives the interval for the slope β1\beta_1, in words recalled per minute of study.

HideShow
ci_c(means = Summary_Recall$mean_Recall,
     s_anova = sqrt(MS_W),
     c_weights = Summary_Recall$c_weight,
     n_per_group = Summary_Recall$n_Recall,
     N = sum(Summary_Recall$n_Recall),
     conf_level = 0.95)
term value
ci_lower 8.257
contrast 11.500
ci_upper 14.743

Confidence level: 95%

HideShow
#> contrast 11.500, 95% CI [8.257, 14.743]

Using the scaled weights gives the interval for β1\beta_1.

HideShow
ci_c(means = Summary_Recall$mean_Recall,
     s_anova = sqrt(MS_W),
     c_weights = Summary_Recall$c_weight / sum(Summary_Recall$c_weight^2),
     n_per_group = Summary_Recall$n_Recall,
     N = sum(Summary_Recall$n_Recall),
     conf_level = 0.95)
term value
ci_lower 1.651
contrast 2.300
ci_upper 2.949

Confidence level: 95%

HideShow
#> slope 2.300, 95% CI [1.651, 2.949] — matches book p. 278 (2.3, [1.65, 2.95])

Finally, to guard against the misconception the book flags on p. 278: a significant linear trend does not imply the relationship is strictly a straight line. The data may go up and curve while doing so. The FF of 54.72 tells us it goes up; it says nothing about curvature. For that we test nonlinearity.

6.6 — Testing for Nonlinearity

Before testing specific shapes, Section 6.6 asks the broader question: is there any nonlinearity? Equation 6.18 pools every non-linear trend into a single test,

F=(SSB−SSlinear)/(a−2)MSW.F = \frac{(SS_B - SS_{linear})/(a - 2)}{MS_W}.

As a model comparison, that is the straight-line model (restricted) against the cell means model (full), which base R does in one call.

HideShow
Model_Linear     <- lm(Recall ~ Minutes,         data = chapter_6_table_1)  # Eq. 6.2
Model_Cell_Means <- lm(Recall ~ factor(Minutes), data = chapter_6_table_1)  # cell means
anova(Model_Linear, Model_Cell_Means)
HideShow
Analysis of Variance Table

Model 1: Recall ~ Minutes
Model 2: Recall ~ factor(Minutes)
  Res.Df  RSS Df Sum of Sq      F Pr(>F)
1     22 71.8                           
2     20 58.0  2      13.8 2.3793 0.1183
HideShow
#> Sum of Sq = 13.8, F = 2.38, p = .118 — matches book p. 281 and Table 6.3, p. 285

6.6.1 — Numerical Example

The book works the same test from its component sums of squares, which the ANOVA above already gave us.

HideShow
SS_Between <- ANOVA_Result$"Sum Sq"[1]
SS_Between
HideShow
[1] 172.5
HideShow
#> 172.5 — matches book p. 281

SS_Departure <- SS_Between - SS_Linear
SS_Departure
HideShow
[1] 13.8
HideShow
#> 13.8 — matches book Table 6.3, p. 285 (deviation from linearity, SS_B - SS_linear)

df_Departure <- 2   # a - 2 = 4 - 2
MS_Departure <- SS_Departure / df_Departure
MS_Departure
HideShow
[1] 6.9
HideShow
#> 6.9 — matches book Table 6.3, p. 285

F_Departure <- MS_Departure / MS_W
F_Departure
HideShow
[1] 2.37931
HideShow
#> 2.38 — matches book p. 281 (F = (172.5 - 158.7)/2 / 2.9 = 2.38)

pf(F_Departure, df1 = df_Departure, df2 = 20, lower.tail = FALSE)
HideShow
[1] 0.1183138
HideShow
#> .118 — matches book Table 6.3, p. 285 (deviation from linearity, p)

With 2 and 20 degrees of freedom this is not significant at the .05 level, so the apparent nonlinearity in Figure 6.2 may simply reflect sampling error. As always, that is a failure to reject, not a demonstration that the nonlinear trends are zero.

This omnibus test can also obscure a real effect: pooling a strong quadratic trend with a negligible cubic one dilutes the signal. Section 6.7 tests the shapes individually.

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 6: Trend Analysis (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

Chapter 7: Two-Way Between-Subjects Factorial Designs

Open the separate reading

Code
Results
On this page

Chapter 7 extends the analysis of variance from single-factor designs to factorial designs, where the groups are defined by two factors at once. Decomposing the general two-way model shows how to test the two omnibus main effects and the interaction, how to follow a significant effect up with contrasts of marginal means, simple effects, and interaction contrasts, and how to report total and partial measures of effect. The chapter closes with the steep sample sizes an interaction test requires and with nonorthogonal (unequal-nn) designs, where Type I, Type II, and Type III sums of squares test genuinely different hypotheses about the marginal means.

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

HideShow
# Load all of the packages used.
library(AMCP)           # the textbook's data sets
library(ggplot2)        # the grammar of graphics used for the book's data figures
library(dplyr)          # data manipulation
library(DMAR)           # design, measurement, and analysis
library(car)            # Anova() for Type II/III tests
library(emmeans)        # estimated marginal means and contrasts
library(pwr)            # power analysis for common designs
library(broom)          # tidy model output into data frames
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables

7.4 — The 2 × 2 Design

The hypothetical blood pressure data of Table 7.1 come from four groups: biofeedback and drug therapy together, biofeedback alone, drug therapy alone, and neither. We load the data and build the two factor columns that the four groups cross.

HideShow
data(chapter_7_table_1)

# Group codes in the book: 1 = both present, 2 = biofeedback alone,
# 3 = drug alone, 4 = neither. Spell each level out rather than relying on the
# order of a labels = argument.
bp <- chapter_7_table_1 |>
  mutate(
    Biofeedback = case_when(
      Group %in% c(1, 2) ~ "Present",
      Group %in% c(3, 4) ~ "Absent"
    ),
    DrugTherapy = case_when(
      Group %in% c(1, 3) ~ "Present",
      Group %in% c(2, 4) ~ "Absent"
    ),
    Biofeedback = factor(Biofeedback, levels = c("Present", "Absent")),
    DrugTherapy = factor(DrugTherapy, levels = c("Present", "Absent")),
    Group       = factor(Group)
  )

bp
HideShow
   Group Score Biofeedback DrugTherapy
1      1   158     Present     Present
2      1   163     Present     Present
3      1   173     Present     Present
4      1   178     Present     Present
5      1   168     Present     Present
6      2   188     Present      Absent
7      2   183     Present      Absent
8      2   198     Present      Absent
9      2   178     Present      Absent
10     2   193     Present      Absent
11     3   186      Absent     Present
12     3   191      Absent     Present
13     3   196      Absent     Present
14     3   181      Absent     Present
15     3   176      Absent     Present
16     4   185      Absent      Absent
17     4   190      Absent      Absent
18     4   195      Absent      Absent
19     4   200      Absent      Absent
20     4   180      Absent      Absent
HideShow
# Group means and standard deviations, as printed at the foot of Table 7.1.
bp |>
  group_by(Group) |>
  summarize(Mean = mean(Score), s = sd(Score), n = n(), .groups = "drop")
HideShow
# A tibble: 4 × 4
  Group  Mean     s     n
  <fct> <dbl> <dbl> <int>
1 1       168  7.91     5
2 2       188  7.91     5
3 3       186  7.91     5
4 4       190  7.91     5
HideShow
#> means 168, 188, 186, 190 and s = 7.91 in every group — matches book Table 7.1 (p. 306)
The omnibus test of the four groups

Based on the previous chapters, our first instinct is to perform an omnibus test comparing all four groups. That is Table 7.2.

HideShow
# Table 7.2: a one-way ANOVA treating the four groups as four levels of one factor.
ANOVA_Object <- aov(Score ~ Group, data = bp)

# anova() and summary() give the same table for an aov object.
anova(ANOVA_Object)
HideShow
Analysis of Variance Table

Response: Score
          Df Sum Sq Mean Sq F value   Pr(>F)   
Group      3   1540  513.33  8.2133 0.001553 **
Residuals 16   1000   62.50                    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
summary(ANOVA_Object)
HideShow
            Df Sum Sq Mean Sq F value  Pr(>F)   
Group        3   1540   513.3   8.213 0.00155 **
Residuals   16   1000    62.5                   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> SS_between 1,540, SS_within 1,000, MS_W 62.50, F = 8.21, p = .002 — matches book Table 7.2 (p. 306)

The omnibus test shows a statistically significant difference among the four groups (F=8.21F = 8.21, p=.002p = .002), but it does not reveal which factor is driving the change.

Decomposing the between-group sum of squares into three orthogonal contrasts

Instead of stopping at the omnibus test, the book tests planned comparisons. Three orthogonal contrasts exhaust the 3 degrees of freedom among four groups:

  • Biofeedback effect, averaging over the drug conditions: 1,1,−1,−11, 1, -1, -1
  • Drug therapy effect, averaging over the biofeedback conditions: 1,−1,1,−11, -1, 1, -1
  • The one remaining orthogonal contrast, which turns out to be the interaction: 1,−1,−1,11, -1, -1, 1
HideShow
# Define the contrast weights, in the order of the Group codes 1, 2, 3, 4.
c_bio  <- c(1,  1, -1, -1)
c_drug <- c(1, -1,  1, -1)
c_int  <- c(1, -1, -1,  1)

# Orthogonality: each pairwise cross-product sums to zero (Equation 4.61).
c(bio_drug = sum(c_bio * c_drug),
  bio_int  = sum(c_bio * c_int),
  drug_int = sum(c_drug * c_int))
HideShow
bio_drug  bio_int drug_int 
       0        0        0 
HideShow
#> all zero — matches book p. 307

# Attach the contrasts to the Group factor and split the Group SS by them.
contrasts(bp$Group) <- cbind(c_bio, c_drug, c_int)
ANOVA_Contrasts <- aov(Score ~ Group, data = bp)
summary(ANOVA_Contrasts,
        split = list(Group = list("Biofeedback" = 1, "Drug" = 2, "Interaction" = 3)))
HideShow
                     Df Sum Sq Mean Sq F value  Pr(>F)   
Group                 3   1540   513.3   8.213 0.00155 **
  Group: Biofeedback  1    500   500.0   8.000 0.01211 * 
  Group: Drug         1    720   720.0  11.520 0.00371 **
  Group: Interaction  1    320   320.0   5.120 0.03792 * 
Residuals            16   1000    62.5                   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> SS 500 (F = 8.00), 720 (F = 11.52), 320 (F = 5.12) — matches book p. 307

The three sums of squares add to the between-group sum of squares of the omnibus test: 500+720+320=1,540500 + 720 + 320 = 1{,}540. The first two contrasts test the main effects — the average effect of biofeedback and the average effect of drug therapy. The third contrast, with F=5.12F = 5.12, tests the interaction.

7.4.1 — The Concept of Interaction

The meaning of the interaction becomes clear once the four group means are arranged in a 2 × 2 table with its row, column, and grand means. That is Table 7.3: the rows are drug therapy and the columns are biofeedback.

HideShow
# Cell means in the layout of Table 7.3: drug therapy in rows, biofeedback in columns.
cell_means_7_3 <- tapply(bp$Score, list(`Drug Therapy` = bp$DrugTherapy,
                                        Biofeedback   = bp$Biofeedback), mean)
addmargins(cell_means_7_3, FUN = list(Average = mean), quiet = TRUE)
HideShow
            Biofeedback
Drug Therapy Present Absent Average
     Present     168    186     177
     Absent      188    190     189
     Average     178    188     183
HideShow
#> cells 168, 186, 188, 190; row means 177 and 189; column means 178 and 188;
#> grand mean 183 — matches book Table 7.3 (p. 308)

# The same cell means with dplyr, for readers who prefer a long data frame.
cell_means_7_1 <- bp |>
  group_by(Biofeedback, DrugTherapy) |>
  summarize(Score = mean(Score), .groups = "drop")
cell_means_7_1
HideShow
# A tibble: 4 × 3
  Biofeedback DrugTherapy Score
  <fct>       <fct>       <dbl>
1 Present     Present       168
2 Present     Absent        188
3 Absent      Present       186
4 Absent      Absent        190

The first contrast compared the column marginal means 178 and 188; the second compared the row marginal means 177 and 189. The third is more subtle. The biofeedback effect in the presence of drug therapy is 18 points (186−168186 - 168), whereas the average biofeedback effect is only 10 points (188−178188 - 178). The significant interaction says that 18 differs from the average of 18 and 2, which is the same as saying that 18 differs from 2 — the biofeedback effect in the absence of drug therapy.

HideShow
# The two biofeedback effects whose difference the interaction contrast tests.
c(`drug present` = cell_means_7_3["Present", "Absent"] - cell_means_7_3["Present", "Present"],
  `drug absent`  = cell_means_7_3["Absent",  "Absent"] - cell_means_7_3["Absent",  "Present"])
HideShow
drug present  drug absent 
          18            2 
HideShow
#> 18 and 2 — matches book p. 308

7.4.2 — Additional Perspectives on the Interaction

It is just as reasonable to ask whether the drug therapy effect is the same with and without biofeedback. It is 20 in the presence of biofeedback and 4 in its absence — a difference of 16, the same difference found for biofeedback. That the same number appears both ways is a mathematical necessity, not a coincidence.

HideShow
# The two drug therapy effects; their difference matches the difference between
# the two biofeedback effects computed above.
drug_effects <- c(
  `biofeedback present` = cell_means_7_3["Absent", "Present"] - cell_means_7_3["Present", "Present"],
  `biofeedback absent`  = cell_means_7_3["Absent", "Absent"]  - cell_means_7_3["Present", "Absent"]
)
drug_effects
HideShow
biofeedback present  biofeedback absent 
                 20                   4 
HideShow
#> 20 and 4 — matches book p. 308
unname(drug_effects[1] - drug_effects[2])
HideShow
[1] 16
HideShow
#> 16, the same difference found for the two biofeedback effects — matches book p. 308

Figure 7.1 shows the same four means in both orientations, exactly as the book prints them. The lines are not parallel in either panel, which is the geometric signature of an interaction.

Figure 7.1(a). Biofeedback effect highlighted

Drug therapy is on the horizontal axis, with a separate line for each biofeedback condition. The vertical gap between the lines is the biofeedback effect at that level of drug therapy: 18 points when drug therapy is present and 2 points when it is absent.

HideShow
ggplot(cell_means_7_1,
       aes(DrugTherapy, Score, color = Biofeedback, group = Biofeedback)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3.5) +
  labs(title = "Figure 7.1(a). Group means of Table 7.3 (biofeedback effect)",
       x = "Drug therapy", y = "Mean systolic blood pressure", color = "Biofeedback") +
  theme(legend.position = "top")
Figure 7.1(a). Geometric depiction of the group means of Table 7.3, biofeedback effect highlighted.

Figure 7.1(a). Geometric depiction of the group means of Table 7.3, biofeedback effect highlighted.

Figure 7.1(b). Drug therapy effect highlighted

The same four means with the roles of the two factors reversed. This view makes the drug therapy effect easier to read — 20 points with biofeedback present, 4 points with it absent — though it carries exactly the same information as panel (a).

HideShow
ggplot(cell_means_7_1,
       aes(Biofeedback, Score, color = DrugTherapy, group = DrugTherapy)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3.5) +
  labs(title = "Figure 7.1(b). Group means of Table 7.3 (drug therapy effect)",
       x = "Biofeedback", y = "Mean systolic blood pressure", color = "Drug therapy") +
  theme(legend.position = "top")
Figure 7.1(b). Geometric depiction of the group means of Table 7.3, drug therapy effect highlighted.

Figure 7.1(b). Geometric depiction of the group means of Table 7.3, drug therapy effect highlighted.

7.5 — A Model Comparison Approach to the General Two-Factor Design

The previous section was restricted to a 2 × 2 design. We now generalize to an a×ba \times b design, where factor A has aa levels and factor B has bb levels.

7.5.1 — Alternate Form of Full Model

The full model can be written as a cell means model, Yijk=μjk+εijk,Y_{ijk} = \mu_{jk} + \varepsilon_{ijk}, or, equivalently, decomposed into a grand mean, two main effects, and an interaction (Equation 7.6): Yijk=μ+αj+βk+(αβ)jk+εijk.Y_{ijk} = \mu + \alpha_j + \beta_k + (\alpha\beta)_{jk} + \varepsilon_{ijk}.

To see exactly what these parameters are, the book works with the hypothetical 3 × 4 table of population means in Table 7.4. The arithmetic below is a deliberately manual demonstration of the effects model — it bridges the algebra to code without touching a sample — so it does not look like a practical analysis.

HideShow
# The population means of Table 7.4.
table_7_4 <- matrix(c(10, 15, 20, 11,
                      15, 10,  5, 14,
                       8,  5, 14,  5),
                    nrow = 3, byrow = TRUE,
                    dimnames = list(c("A1", "A2", "A3"),
                                    c("B1", "B2", "B3", "B4")))
addmargins(table_7_4, FUN = list(`Marginal Means` = mean), quiet = TRUE)
HideShow
               B1 B2 B3 B4 Marginal Means
A1             10 15 20 11             14
A2             15 10  5 14             11
A3              8  5 14  5              8
Marginal Means 11 10 13 10             11
HideShow
#> row means 14, 11, 8; column means 11, 10, 13, 10; grand mean 11
#> — matches book Table 7.4 (p. 311) and pp. 311–312

The population marginal means and grand mean are Equations 7.7, 7.8, and 7.9.

HideShow
grand_mean <- mean(table_7_4)         # Equation 7.9
row_means  <- rowMeans(table_7_4)     # Equation 7.7
col_means  <- colMeans(table_7_4)     # Equation 7.8

cat("Grand mean:", grand_mean, "\n")
HideShow
Grand mean: 11 
HideShow
cat("Row marginal means (factor A):", row_means, "\n")
HideShow
Row marginal means (factor A): 14 11 8 
HideShow
cat("Column marginal means (factor B):", col_means, "\n")
HideShow
Column marginal means (factor B): 11 10 13 10 

The A main effect αj\alpha_j is the row mean minus the grand mean (Equation 7.10); the B main effect βk\beta_k is the column mean minus the grand mean (Equation 7.11).

HideShow
alpha_effects <- row_means - grand_mean   # Equation 7.10
beta_effects  <- col_means - grand_mean   # Equation 7.11

cat("Factor A effects (alpha):", alpha_effects, "\n")
HideShow
Factor A effects (alpha): 3 0 -3 
HideShow
#> 3, 0, -3 — matches book p. 312
cat("Factor B effects (beta):", beta_effects, "\n")
HideShow
Factor B effects (beta): 0 -1 2 -1 
HideShow
#> 0, -1, 2, -1 — matches book p. 312

# Each set of effects is constrained to sum to zero.
c(sum_alpha = sum(alpha_effects), sum_beta = sum(beta_effects))
HideShow
sum_alpha  sum_beta 
        0         0 

The interaction effect for a cell is how far that cell departs from an additive combination of the grand mean and the two main effects (Equation 7.12).

HideShow
# (alpha beta)_jk = mu_jk - (grand_mean + alpha_j + beta_k), Equation 7.12.
interaction_effects <- table_7_4 -
  outer(grand_mean + alpha_effects, beta_effects, FUN = "+")
interaction_effects
HideShow
   B1 B2 B3 B4
A1 -4  2  4 -2
A2  4  0 -8  4
A3  0 -2  4 -2
HideShow
#> row A1: -4, 2, 4, -2; row A2: 4, 0, -8, 4; row A3: 0, -2, 4, -2
#> — matches the 12 interaction parameters on book p. 312

For the (1, 1) cell, (αβ)11=10−(11+3+0)=−4(\alpha\beta)_{11} = 10 - (11 + 3 + 0) = -4: the particular combination of A1A_1 and B1B_1 lowers scores, contrary to their average effects separately.

7.5.3 — Numerical Example

Table 7.5 holds hypothetical blood pressure data from a 2 × 3 design crossing biofeedback (present, absent) with type of drug (X, Y, Z), with n=5n = 5 per cell.

HideShow
data(chapter_7_table_5)

# The AMCP columns are numeric codes: Feedback 1 = present, 2 = absent;
# Drug 1 = X, 2 = Y, 3 = Z. Spell each level out before setting the order.
bp23 <- chapter_7_table_5 |>
  mutate(
    Biofeedback = case_when(
      Feedback == 1 ~ "Present",
      Feedback == 2 ~ "Absent"
    ),
    Drug = case_when(
      Drug == 1 ~ "X",
      Drug == 2 ~ "Y",
      Drug == 3 ~ "Z"
    ),
    Biofeedback = factor(Biofeedback, levels = c("Present", "Absent")),
    Drug        = factor(Drug, levels = c("X", "Y", "Z"))
  ) |>
  select(Score, Biofeedback, Drug)

bp23
HideShow
   Score Biofeedback Drug
1    170     Present    X
2    175     Present    X
3    165     Present    X
4    180     Present    X
5    160     Present    X
6    186     Present    Y
7    194     Present    Y
8    201     Present    Y
9    215     Present    Y
10   219     Present    Y
11   180     Present    Z
12   187     Present    Z
13   199     Present    Z
14   170     Present    Z
15   204     Present    Z
16   173      Absent    X
17   194      Absent    X
18   197      Absent    X
19   190      Absent    X
20   176      Absent    X
21   189      Absent    Y
22   194      Absent    Y
23   217      Absent    Y
24   206      Absent    Y
25   199      Absent    Y
26   202      Absent    Z
27   228      Absent    Z
28   190      Absent    Z
29   206      Absent    Z
30   224      Absent    Z
HideShow
str(bp23)
HideShow
'data.frame':   30 obs. of  3 variables:
 $ Score      : int  170 175 165 180 160 186 194 201 215 219 ...
 $ Biofeedback: Factor w/ 2 levels "Present","Absent": 1 1 1 1 1 1 1 1 1 1 ...
 $ Drug       : Factor w/ 3 levels "X","Y","Z": 1 1 1 1 1 2 2 2 2 2 ...

Table 7.6 shows the cell means and the marginal means for these data.

HideShow
# Table 7.6: cells, row margins, column margins, and the grand mean.
cell_means_7_6 <- tapply(bp23$Score, list(`A (Biofeedback)` = bp23$Biofeedback,
                                          `B (Drug)`        = bp23$Drug), mean)
addmargins(cell_means_7_6, FUN = list(`Marginal Means` = mean), quiet = TRUE)
HideShow
                B (Drug)
A (Biofeedback)    X   Y   Z Marginal Means
  Present        170 203 188            187
  Absent         186 201 210            199
  Marginal Means 178 202 199            193
HideShow
#> cells 170, 203, 188 / 186, 201, 210; row means 187 and 199;
#> column means 178, 202, 199; grand mean 193 — matches book Table 7.6 (p. 319)

# The same marginal means with dplyr, with standard deviations and cell sizes.
bp23 |> group_by(Biofeedback) |>
  summarize(mean_Score = mean(Score), sd_Score = sd(Score), n_Score = n(), .groups = "drop")
HideShow
# A tibble: 2 × 4
  Biofeedback mean_Score sd_Score n_Score
  <fct>            <dbl>    <dbl>   <int>
1 Present            187     18.0      15
2 Absent             199     15.6      15
HideShow
bp23 |> group_by(Drug) |>
  summarize(mean_Score = mean(Score), sd_Score = sd(Score), n_Score = n(), .groups = "drop")
HideShow
# A tibble: 3 × 4
  Drug  mean_Score sd_Score n_Score
  <fct>      <dbl>    <dbl>   <int>
1 X            178     12.3      10
2 Y            202     11.8      10
3 Z            199     18.2      10

The two-way omnibus ANOVA reproduces the bottom third of Table 7.7. Because Biofeedback and Drug are genuine factor columns, aov() fits an ANOVA rather than a regression on numeric codes.

HideShow
ANOVA_TwoWay <- aov(Score ~ Biofeedback * Drug, data = bp23)

# anova() and summary() give the same table.
anova(ANOVA_TwoWay)
HideShow
Analysis of Variance Table

Response: Score
                 Df Sum Sq Mean Sq F value    Pr(>F)    
Biofeedback       1   1080 1080.00  6.9342 0.0145635 *  
Drug              2   3420 1710.00 10.9791 0.0004113 ***
Biofeedback:Drug  2    780  390.00  2.5040 0.1028767    
Residuals        24   3738  155.75                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
Summary_ANOVA_TwoWay <- summary(ANOVA_TwoWay)
Summary_ANOVA_TwoWay
HideShow
                 Df Sum Sq Mean Sq F value   Pr(>F)    
Biofeedback       1   1080  1080.0   6.934 0.014563 *  
Drug              2   3420  1710.0  10.979 0.000411 ***
Biofeedback:Drug  2    780   390.0   2.504 0.102877    
Residuals        24   3738   155.8                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> A: SS 1,080, MS 1,080.00, F = 6.93, p = .015
#> B: SS 3,420, MS 1,710.00, F = 10.98, p < .001
#> AB: SS 780, MS 390.00, F = 2.50, p = .103
#> Within cells: SS 3,738, df 24, MS 155.75 — matches book Table 7.7 (p. 320)

Both main effects are statistically significant and the interaction is not (p=.103p = .103). The error sums of squares of the three restricted models in the upper part of Table 7.7 follow from the same fits.

HideShow
# Each restricted model drops one set of parameters from the full model, so by
# the model-comparison identity E_R - E_F = SS for that effect.
aov_rows <- anova(ANOVA_TwoWay)
E_F  <- aov_rows["Residuals", "Sum Sq"]
E_R1 <- E_F + aov_rows["Biofeedback", "Sum Sq"]        # alpha_j omitted
E_R2 <- E_F + aov_rows["Drug", "Sum Sq"]               # beta_k omitted
E_R3 <- E_F + aov_rows["Biofeedback:Drug", "Sum Sq"]   # (alpha beta)_jk omitted
c(E_F = E_F, E_R1 = E_R1, E_R2 = E_R2, E_R3 = E_R3)
HideShow
 E_F E_R1 E_R2 E_R3 
3738 4818 7158 4518 
HideShow
#> 3,738; 4,818; 7,158; 4,518 — matches book Table 7.7 (p. 320)
The same ANOVA as an APA-style table

The same table formatted with gt: sums of squares, df, MS, FF, pp, and partial η2\eta^2 for each source. Partial η2\eta^2 here is each effect’s SSSS over that effect’s SSSS plus the within-cells SSSS, which is exactly the partial R2R^2 of Equation 7.40 and of Table 7.8.

HideShow
aov_tbl <- broom::tidy(ANOVA_TwoWay)
ss_res  <- aov_tbl$sumsq[aov_tbl$term == "Residuals"]   # within-cells SS

aov_tbl |>
  # car (loaded for Type II/III SS) masks dplyr::recode, so qualify it explicitly.
  dplyr::transmute(
    Source = dplyr::recode(term,
                    "Biofeedback"      = "A (Biofeedback)",
                    "Drug"             = "B (Drug)",
                    "Biofeedback:Drug" = "AB (Interaction)",
                    "Residuals"        = "Within cells"),
    SS = sumsq, df = df, MS = meansq,
    Fstat = statistic, p = p.value,
    # Partial eta-squared = SS_effect / (SS_effect + SS_within).
    peta  = dplyr::if_else(term == "Residuals", NA_real_, sumsq / (sumsq + ss_res))
  ) |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("**Table 7.7**. Analysis of Variance for Blood Pressure")) |>
  cols_align(align = "center", columns = -Source)
Table 7.7. Analysis of Variance for Blood Pressure
Source SS df MS F p Partial η2
A (Biofeedback) 1,080.00 1 1,080.00 6.93 0.0146 0.224
B (Drug) 3,420.00 2 1,710.00 10.98 0.0004 0.478
AB (Interaction) 780.00 2 390.00 2.50 0.1029 0.173
Within cells 3,738.00 24 155.75


HideShow
#> partial eta-squared .224, .478, .173 — the partial R-squared column of
#> book Table 7.8 (p. 325), rounded there to .22, .48, .17
The additive and interaction models side by side

The interaction line of Table 7.7 is a comparison of two models, so it is instructive to see them as columns. With modelsummary, each model is a column and the fit statistics sit at the foot.

HideShow
fit_additive    <- lm(Score ~ Biofeedback + Drug, data = bp23)
fit_interaction <- lm(Score ~ Biofeedback * Drug, data = bp23)

modelsummary(
  list("Main effects only" = fit_additive, "With interaction" = fit_interaction),
  estimate  = "{estimate}",
  statistic = "({std.error})",   # standard errors in parentheses, APA style
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  stars     = TRUE,
  output    = "gt"
)
Main effects only With interaction
(Intercept) 172.000 170.000
(4.813) (5.581)
BiofeedbackAbsent 12.000 16.000
(4.813) (7.893)
DrugY 24.000 33.000
(5.895) (7.893)
DrugZ 21.000 18.000
(5.895) (7.893)
BiofeedbackAbsent × DrugY -18.000
(11.162)
BiofeedbackAbsent × DrugZ 6.000
(11.162)
Num.Obs. 30 30
AIC 245.6 243.9
BIC 252.6 253.7
Log.Lik. -117.788 -114.945
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

The same two models as a gtsummary table, each under its own spanning header. The interaction model adds the two Biofeedback:Drug product terms that the additive model leaves out.

HideShow
t_add <- tbl_regression(fit_additive,    intercept = TRUE)
t_int <- tbl_regression(fit_interaction, intercept = TRUE)
# quiet = TRUE: the two models have different numbers of coefficient rows (the
# interaction model adds the two Biofeedback:Drug terms), which is expected here.
tbl_merge(list(t_add, t_int),
          tab_spanner = c("**Main effects only**", "**With interaction**"),
          quiet = TRUE)
Characteristic
Main effects only
With interaction
Beta 95% CI p-value Beta 95% CI p-value
(Intercept) 172 162, 182 <0.001 170 158, 182 <0.001
Biofeedback





    Present — —
— —
    Absent 12 2.1, 22 0.019 16 -0.29, 32 0.054
Drug





    X — —
— —
    Y 24 12, 36 <0.001 33 17, 49 <0.001
    Z 21 8.9, 33 0.001 18 1.7, 34 0.032
Biofeedback * Drug





    Absent * Y


-18 -41, 5.0 0.12
    Absent * Z


6.0 -17, 29 0.6
Abbreviation: CI = Confidence Interval
Extracting pieces of the ANOVA table

As in the code for Chapter 3, the parts of the ANOVA table can be pulled out for effect sizes and follow-up tests.

HideShow
# What the summary object contains.
str(Summary_ANOVA_TwoWay)
HideShow
List of 1
 $ :Classes 'anova' and 'data.frame':   4 obs. of  5 variables:
  ..$ Df     : num [1:4] 1 2 2 24
  ..$ Sum Sq : num [1:4] 1080 3420 780 3738
  ..$ Mean Sq: num [1:4] 1080 1710 390 156
  ..$ F value: num [1:4] 6.93 10.98 2.5 NA
  ..$ Pr(>F) : num [1:4] 0.014563 0.000411 0.102877 NA
 - attr(*, "class")= chr [1:2] "summary.aov" "listof"
HideShow
# Sums of squares, degrees of freedom, and mean squares.
Summary_ANOVA_TwoWay[[1]]["Sum Sq"]
HideShow
                 Sum Sq
Biofeedback        1080
Drug               3420
Biofeedback:Drug    780
Residuals          3738
HideShow
Summary_ANOVA_TwoWay[[1]]["Df"]
HideShow
                 Df
Biofeedback       1
Drug              2
Biofeedback:Drug  2
Residuals        24
HideShow
Summary_ANOVA_TwoWay[[1]]["Mean Sq"]
HideShow
                 Mean Sq
Biofeedback      1080.00
Drug             1710.00
Biofeedback:Drug  390.00
Residuals         155.75

7.5.5 — Measures of Effect

A factorial design forces a decision that a single-factor design does not: whether the “off factor” is intrinsic (its variance belongs in the total) or extrinsic (its variance should be partialled out). The book reports all four combinations in Table 7.8 — R2R^2 and ω̂2\hat{\omega}^2 in total form (Equations 7.41 and 7.45) and in partial form (Equations 7.40 and 7.44).

We build the table by hand first, straight from the sums of squares.

HideShow
anova_table <- Summary_ANOVA_TwoWay[[1]]

# Row 1: Biofeedback, Row 2: Drug, Row 3: Interaction, Row 4: Residuals.
SS_A  <- anova_table[1, "Sum Sq"]
SS_B  <- anova_table[2, "Sum Sq"]
SS_AB <- anova_table[3, "Sum Sq"]
SS_W  <- anova_table[4, "Sum Sq"]
SS_T  <- SS_A + SS_B + SS_AB + SS_W

df_A  <- anova_table[1, "Df"]
df_B  <- anova_table[2, "Df"]
df_AB <- anova_table[3, "Df"]
df_W  <- anova_table[4, "Df"]

N     <- df_A + df_B + df_AB + df_W + 1   # total df + 1
MS_W  <- anova_table[4, "Mean Sq"]

calc_effects <- function(SS_eff, df_eff) {
  # Intrinsic ("total") measures: Equations 7.41 and 7.45.
  R2_total       <- SS_eff / SS_T
  omega2_total   <- (SS_eff - (df_eff * MS_W)) / (SS_T + MS_W)
  # Extrinsic ("partial") measures: Equations 7.40 and 7.44.
  R2_partial     <- SS_eff / (SS_eff + SS_W)
  omega2_partial <- (SS_eff - (df_eff * MS_W)) / (SS_eff + (N - df_eff) * MS_W)
  c(R2_total, omega2_total, R2_partial, omega2_partial)
}

chapter_7_table_8 <- data.frame(
  Effect         = c("A (Biofeedback)", "B (Drug)", "AB (Interaction)"),
  R2             = NA_real_, Omega2 = NA_real_,
  R2_partial     = NA_real_, Omega2_partial = NA_real_
)
chapter_7_table_8[1, -1] <- as.list(calc_effects(SS_A,  df_A))
chapter_7_table_8[2, -1] <- as.list(calc_effects(SS_B,  df_B))
chapter_7_table_8[3, -1] <- as.list(calc_effects(SS_AB, df_AB))

chapter_7_table_8[, -1] <- round(chapter_7_table_8[, -1], 2)
chapter_7_table_8
HideShow
            Effect   R2 Omega2 R2_partial Omega2_partial
1  A (Biofeedback) 0.12   0.10       0.22           0.17
2         B (Drug) 0.38   0.34       0.48           0.40
3 AB (Interaction) 0.09   0.05       0.17           0.09
HideShow
#> A .12 / .10 / .22 / .17, B .38 / .34 / .48 / .40, AB .09 / .05 / .17 / .09
#> — matches book Table 7.8 (p. 325)

The drug effect is strongest and the interaction weakest on every measure, and for any one effect Rpartial2R^2_{\text{partial}} is always the largest and ω̂2\hat{\omega}^2 always the smallest.

The same four measures in DMAR

Having built Table 7.8 by hand, we can let DMAR read the same measures off the fitted model. eta_squared() and omega_squared() take the lm fit and an estimand argument, so one call returns both the total and the partial version of each measure without indexing the ANOVA table ourselves. They also carry the FF values and degrees of freedom along with the estimates, which is what the interval machinery below needs.

HideShow
# The same full two-factor model used for Table 7.7.
fit_full <- lm(Score ~ Biofeedback * Drug, data = bp23)

# R-squared (total) and partial R-squared, the first and third columns of Table 7.8.
eta_squared(fit_full, estimand = "all")
effect eta_squared_total eta_squared_partial F_value df_effect df_error
Biofeedback 0.120 0.224 6.934 1 24
Drug 0.379 0.478 10.979 2 24
Biofeedback:Drug 0.086 0.173 2.504 2 24

Sum of squares: Type III

HideShow
#> total .120, .379, .086 and partial .224, .478, .173 — the same values we
#> computed by hand, and book Table 7.8 (p. 325) rounds them to
#> .12 / .38 / .09 and .22 / .48 / .17

# Omega-squared (total) and partial omega-squared, the second and fourth columns.
omega_squared(fit_full, estimand = "all")
effect omega_squared_total omega_squared_partial F_value df_effect df_error N
Biofeedback 0.101 0.165 6.934 1 24 30
Drug 0.339 0.399 10.979 2 24 30
Biofeedback:Drug 0.051 0.091 2.504 2 24 30

Sum of squares: Type III

HideShow
#> total .101, .339, .051 and partial .165, .399, .091 — matches the hand
#> computation and book Table 7.8 (p. 325): .10 / .34 / .05 and .17 / .40 / .09

Where the two routes agree exactly, as they do here, the agreement is the point: the DMAR call is a convenience, not a different estimator.

An interval for the measure

The book cautions on p. 325 that a point estimate such as the 9% of partial variance attributable to the interaction should be treated skeptically in a sample this small, and points the reader to the literature on confidence intervals for these measures. DMAR forms that interval directly, by inverting the noncentral FF distribution.

HideShow
# Noncentral-F confidence interval on each effect's partial omega-squared.
ci_omega_squared(fit_full, estimand = "partial", conf_level = 0.95)
effect omega_squared_partial omega_squared_partial_ci_lower omega_squared_partial_ci_upper F_value df_effect df_error N
Biofeedback 0.165 0.008 0.425 6.934 1 24 30
Drug 0.399 0.130 0.616 10.979 2 24 30
Biofeedback:Drug 0.091 0.000 0.361 2.504 2 24 30

Sum of squares: Type III

Confidence level: 95%

The interval for the interaction runs down to zero, which is consistent with the nonsignificant interaction test in Table 7.7: the data are compatible with the interaction accounting for no variance at all in the population. DMAR also returns an asymptotic variance for each estimate, which is what a Wald-style test or a meta-analytic weight would need. The book does not report these variances, so the values below are an addition to, not a reproduction of, the printed table.

HideShow
# Asymptotic variance of each effect's partial omega-squared.
var_omega_squared(object = fit_full)
effect omega_squared_partial var_omega_squared df_effect df_error N
Biofeedback 0.165 0.018 1 24 30
Drug 0.399 0.020 2 24 30
Biofeedback:Drug 0.091 0.015 2 24 30

Sum of squares: Type III

7.6 — Follow-Up Tests

7.6.1 — Further Investigation of Main Effects

The drug main effect is significant, but with three levels that only says the three marginal means are not all equal. Contrasts of the marginal means locate the difference, exactly as in the one-way design. The sum of squares for a contrast of the B marginal means is Equation 7.48, SSψB=na(ψ̂)2/∑k=1bck2,SS_{\psi_B} = na(\hat{\psi})^2 \big/ \textstyle\sum_{k=1}^{b} c_k^2 , with nana in the numerator because each B marginal mean rests on nn times aa observations.

We compare Drug X with Drug Y, whose marginal means from Table 7.6 are 178 and 202.

HideShow
# Marginal means read off the fitted data rather than typed in by hand.
drug_marginals <- tapply(bp23$Score, bp23$Drug, mean)
drug_marginals
HideShow
  X   Y   Z 
178 202 199 
HideShow
n <- 5    # observations per cell
a <- 2    # levels of biofeedback

# Contrast of Drug X (1) versus Drug Y (-1), leaving Drug Z out (0).
c_weights <- c(X = 1, Y = -1, Z = 0)
psi_hat   <- sum(c_weights * drug_marginals)
cat("psi-hat:", psi_hat, "\n")
HideShow
psi-hat: -24 
HideShow
#> -24 — matches book p. 326

SS_psi <- (n * a * psi_hat^2) / sum(c_weights^2)     # Equation 7.48
cat("SS for contrast:", SS_psi, "\n")
HideShow
SS for contrast: 2880 
HideShow
#> 2,880 — matches book p. 326

F_obs <- SS_psi / MS_W                               # Equation 7.50
cat("Observed F:", F_obs, "\n")
HideShow
Observed F: 18.49117 
HideShow
#> 18.49 — matches book p. 326

Because this is a pairwise comparison, the observed FF goes against a Tukey critical value of the form q.05,b,dferror2/2q^2_{.05,b,df_{\text{error}}}/2, with b=3b = 3 because we are comparing marginal means of the B factor.

HideShow
q_crit <- qtukey(0.95, nmeans = 3, df = 24)
cat("Critical q:", q_crit, "\n")
HideShow
Critical q: 3.531697 
HideShow
#> 3.53 — matches book p. 326

F_crit <- q_crit^2 / 2
cat("Critical F:", F_crit, "\n")
HideShow
Critical F: 6.236443 
HideShow
#> 6.2364; book p. 326 prints 6.23, which is the table value 3.53 squared and
#> halved, where R squares the exact 3.5317

The observed FF of 18.49 comfortably exceeds the critical value near 6.23, so the marginal means of Drugs X and Y differ. The matching Tukey simultaneous interval (Equation 7.51) uses ng=10n_g = 10, because each column marginal mean rests on the 10 participants who received that drug, not on the 5 in a cell.

HideShow
n_marginal      <- 10     # participants per drug, pooling over biofeedback
margin_of_error <- (q_crit / sqrt(2)) * sqrt(MS_W * (1 / n_marginal + 1 / n_marginal))

cat("95% CI: [", psi_hat - margin_of_error, ",", psi_hat + margin_of_error, "]\n")
HideShow
95% CI: [ -37.93791 , -10.06209 ]
HideShow
#> [-37.93, -10.07] — matches book p. 327

# An approximate standardized interval divides the limits by the within-cell SD.
cat("Standardized: [", (psi_hat - margin_of_error) / sqrt(MS_W), ",",
    (psi_hat + margin_of_error) / sqrt(MS_W), "]\n")
HideShow
Standardized: [ -3.0399 , -0.8062586 ]
HideShow
#> [-3.04, -0.81] — matches book p. 327

The interval excludes zero, so Tukey’s method rejects the null hypothesis. Our single best guess is that Drug X is 24 points better than Drug Y, but the population advantage may be as large as 38 points or as small as 10.

All pairwise comparisons of the drug marginal means at once, with emmeans, give the same answer for X versus Y without our assembling the critical value by hand.

HideShow
emm_drug <- emmeans(ANOVA_TwoWay, ~ Drug)
emm_drug
HideShow
 Drug emmean   SE df lower.CL upper.CL
 X       178 3.95 24      170      186
 Y       202 3.95 24      194      210
 Z       199 3.95 24      191      207

Results are averaged over the levels of: Biofeedback 
Confidence level used: 0.95 
HideShow
#> 178, 202, 199 — matches book Table 7.6 (p. 319)

pairs(emm_drug, adjust = "tukey")
HideShow
 contrast estimate   SE df t.ratio p.value
 X - Y         -24 5.58 24  -4.300  0.0007
 X - Z         -21 5.58 24  -3.763  0.0027
 Y - Z           3 5.58 24   0.538  0.8537

Results are averaged over the levels of: Biofeedback 
P value adjustment: tukey method for comparing a family of 3 estimates 
HideShow
#> X - Y: estimate -24, the same contrast tested by hand above
confint(pairs(emm_drug, adjust = "tukey"))
HideShow
 contrast estimate   SE df lower.CL upper.CL
 X - Y         -24 5.58 24    -37.9   -10.06
 X - Z         -21 5.58 24    -34.9    -7.06
 Y - Z           3 5.58 24    -10.9    16.94

Results are averaged over the levels of: Biofeedback 
Confidence level used: 0.95 
Conf-level adjustment: tukey method for comparing a family of 3 estimates 
HideShow
#> X - Y: [-37.93, -10.07] — matches book p. 327
The same critical value in DMAR

DMAR’s cv_tukey_hsd() returns the Tukey critical value in the tt metric, that is q/2q/\sqrt{2}, so squaring it gives the critical FF the book compares the observed FF against. Its arguments are stated in the design’s own terms — number of groups and error degrees of freedom — rather than in the studentized-range parameterization.

HideShow
cv_tukey <- cv_tukey_hsd(alpha_level = 0.05, df = 24, n_groups = 3, verbose = FALSE)
cv_tukey
term value
upper_cv 2.497
HideShow
cat("Squared:", cv_tukey$value^2, "\n")
HideShow
Squared: 6.236443 
HideShow
#> 6.2364, exactly the critical F that qtukey() produced above

7.6.2 — Further Investigation of an Interaction—Simple Effects

When an interaction is significant, the marginal means can mislead, because the interaction is precisely the signal that the individual effects differ from the average effect. The book makes the interaction significant by adding one observation per cell (Table 7.9), bringing nn to 6.

HideShow
# Table 7.9: one additional observation in each of the six cells, in the order
# biofeedback present with Drugs X, Y, Z, then biofeedback absent with X, Y, Z.
new_obs <- data.frame(
  Score    = c(158, 209, 194, 198, 195, 204),
  Feedback = c(1, 1, 1, 2, 2, 2),
  Drug     = c(1, 2, 3, 1, 2, 3)
)

bp23_n6 <- rbind(chapter_7_table_5, new_obs) |>
  mutate(
    Biofeedback = case_when(
      Feedback == 1 ~ "Present",
      Feedback == 2 ~ "Absent"
    ),
    Drug = case_when(
      Drug == 1 ~ "X",
      Drug == 2 ~ "Y",
      Drug == 3 ~ "Z"
    ),
    Biofeedback = factor(Biofeedback, levels = c("Present", "Absent")),
    Drug        = factor(Drug, levels = c("X", "Y", "Z"))
  )

# Table 7.10: cell means and marginal means on six observations per cell.
cell_means_7_10 <- tapply(bp23_n6$Score, list(`A (Biofeedback)` = bp23_n6$Biofeedback,
                                              `B (Drug)`        = bp23_n6$Drug), mean)
addmargins(cell_means_7_10, FUN = list(`Marginal Means` = mean), quiet = TRUE)
HideShow
                B (Drug)
A (Biofeedback)    X   Y   Z Marginal Means
  Present        168 204 189            187
  Absent         188 200 209            199
  Marginal Means 178 202 199            193
HideShow
#> cells 168, 204, 189 / 188, 200, 209; row means 187 and 199;
#> column means 178, 202, 199; grand mean 193 — matches book Table 7.10 (p. 328)
HideShow
ANOVA_new <- aov(Score ~ Biofeedback * Drug, data = bp23_n6)
summary(ANOVA_new)
HideShow
                 Df Sum Sq Mean Sq F value   Pr(>F)    
Biofeedback       1   1296  1296.0   9.488   0.0044 ** 
Drug              2   4104  2052.0  15.022 3.02e-05 ***
Biofeedback:Drug  2   1152   576.0   4.217   0.0243 *  
Residuals        30   4098   136.6                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> A: F = 9.49, p = .0044; B: F = 15.02, p < .001; AB: F = 4.22, p = .0243
#> — matches book p. 328

MS_W_new <- anova(ANOVA_new)["Residuals", "Mean Sq"]
df_W_new <- anova(ANOVA_new)["Residuals", "Df"]
c(MS_W = MS_W_new, df_W = df_W_new)
HideShow
 MS_W  df_W 
136.6  30.0 
HideShow
#> MS_W = 136.6 on 30 df — matches book p. 329

All three effects are now significant. The biofeedback main effect of 12 points is the average of three very different simple effects: 20 points under Drug X, −4-4 under Drug Y, and 20 under Drug Z. Reporting the 12 alone would be misleading, so we test each simple effect separately, treating the data at a fixed level of the other factor as a one-way design (Equation 7.52) and keeping the pooled MSWMS_W as the error term.

HideShow
n_new <- 6   # observations per cell

# Simple effect of A (biofeedback) within each drug.
simple_A_within_B <- lapply(levels(bp23_n6$Drug), function(lv) {
  sub <- subset(bp23_n6, Drug == lv)
  means <- tapply(sub$Score, sub$Biofeedback, mean)
  SS <- n_new * sum((means - mean(sub$Score))^2)       # Equation 7.52
  F_obs <- (SS / 1) / MS_W_new
  data.frame(Effect = paste0("A within Drug ", lv), SS = SS, df = 1,
             F = F_obs, p = pf(F_obs, 1, df_W_new, lower.tail = FALSE))
})
do.call(rbind, simple_A_within_B)
HideShow
           Effect   SS df         F           p
1 A within Drug X 1200  1 8.7847731 0.005900874
2 A within Drug Y   48  1 0.3513909 0.557769228
3 A within Drug Z 1200  1 8.7847731 0.005900874
HideShow
#> Drug X: SS 1,200, F = 8.78, p = .0059; Drug Y: F = 0.35, p = .5578;
#> Drug Z: F = 8.78, p = .0059 — matches book p. 329

# Simple effect of B (drug) within each level of biofeedback.
simple_B_within_A <- lapply(levels(bp23_n6$Biofeedback), function(lv) {
  sub <- subset(bp23_n6, Biofeedback == lv)
  means <- tapply(sub$Score, sub$Drug, mean)
  SS <- n_new * sum((means - mean(sub$Score))^2)       # Equation 7.52
  F_obs <- (SS / 2) / MS_W_new
  data.frame(Effect = paste0("B within biofeedback ", lv), SS = SS, df = 2,
             F = F_obs, p = pf(F_obs, 2, df_W_new, lower.tail = FALSE))
})
do.call(rbind, simple_B_within_A)
HideShow
                        Effect   SS df         F            p
1 B within biofeedback Present 3924  2 14.363104 4.210556e-05
2  B within biofeedback Absent 1332  2  4.875549 1.467513e-02
HideShow
#> Biofeedback present: SS 3,924, F = 14.36, p < .001;
#> biofeedback absent: F = 4.88, p = .0147 — matches book p. 329

Biofeedback helps with Drug X and with Drug Z but not with Drug Y. The drugs differ from each other both with and without biofeedback. To say which drugs differ, we need cell mean comparisons. Drugs Y and Z in the presence of biofeedback have means of 204 and 189.

HideShow
# Contrast of Drug Z against Drug Y within biofeedback present.
psi_hat_cell  <- cell_means_7_10["Present", "Z"] - cell_means_7_10["Present", "Y"]
SS_psi_cell   <- n_new * psi_hat_cell^2 / 2
F_cell        <- SS_psi_cell / MS_W_new

cat("psi-hat:", psi_hat_cell, " SS:", SS_psi_cell, " F:", F_cell,
    " p:", pf(F_cell, 1, df_W_new, lower.tail = FALSE), "\n")
HideShow
psi-hat: -15  SS: 675  F: 4.941435  p: 0.03390169 
HideShow
#> psi-hat -15, SS 675, F = 4.94, p = .0339 — matches book p. 329

# Tukey interval for the cell comparison (Equation 7.53): n = 6 per cell, not 10.
q_crit_cell       <- qtukey(0.95, nmeans = 3, df = df_W_new)
margin_error_cell <- (q_crit_cell / sqrt(2)) * sqrt(MS_W_new * (1 / n_new + 1 / n_new))
cat("95% CI: [", psi_hat_cell - margin_error_cell, ",",
    psi_hat_cell + margin_error_cell, "]\n")
HideShow
95% CI: [ -31.63525 , 1.635254 ]
HideShow
#> [-31.64, 1.64] — matches book p. 330, which prints [-31.65, 1.65] using the
#> table value q = 3.49 where R uses the exact 3.4864

The interval contains zero, so we cannot be confident which of the two drugs is more effective within the biofeedback condition. It is wider than the marginal-mean interval of Section 7.6.1 because each cell mean rests on 6 participants rather than 10.

All of the simple effects at once in DMAR

The hand computation above tests one simple effect at a time. DMAR’s simple_effects_AB() takes the fitted full model and returns every simple effect — of A within each level of B and of B within each level of A — in a single table, with the pooled MSWMS_W as the default error term. Each row also carries the partial η2\eta^2 with a noncentral-FF interval, which the book does not tabulate.

HideShow
fit_full_n6 <- lm(Score ~ Biofeedback * Drug, data = bp23_n6)
simple_effects_AB(fit_full_n6)
effect focal_factor conditioning_factor conditioning_level F_value df_effect df_error p_value p_adjusted eta_squared_partial ci_lower ci_upper n_at_level
Biofeedback | Drug = X Biofeedback Drug X 8.785 1 30 0.0059 0.0059 0.227 0.019 0.414 12
Biofeedback | Drug = Y Biofeedback Drug Y 0.351 1 30 0.5578 0.5578 0.012 0.000 0.152 12
Biofeedback | Drug = Z Biofeedback Drug Z 8.785 1 30 0.0059 0.0059 0.227 0.019 0.414 12
Drug | Biofeedback = Present Drug Biofeedback Present 14.363 2 30 < 0.0001 < 0.0001 0.489 0.180 0.618 18
Drug | Biofeedback = Absent Drug Biofeedback Absent 4.876 2 30 0.0147 0.0147 0.245 0.010 0.419 18

Confidence level: 95%

Pooled-error partial eta squared with a noncentral-F interval.

HideShow
#> A | Drug X: F = 8.785, p = .0059; A | Drug Y: F = 0.351, p = .5578;
#> A | Drug Z: F = 8.785, p = .0059; B | biofeedback present: F = 14.363, p < .001;
#> B | biofeedback absent: F = 4.876, p = .0147 — all five match book p. 329

Every FF reproduces the hand computation and the book.

7.6.6 — An Alternative Method for Investigating an Interaction—Interaction Contrasts

Simple effects are the usual follow-up to a significant interaction, but there is an alternative: form single-degree-of-freedom comparisons of the interaction itself. The book gives a post hoc example and a planned example, and we work both.

A post hoc interaction contrast in the blood pressure data

The biofeedback effect is 20 for Drug X and 20 for Drug Z but only −4-4 for Drug Y. We first ask whether the biofeedback effect for Drug Y differs from that for Drug X, which is the null hypothesis μ12−μ22−μ11+μ21=0\mu_{12} - \mu_{22} - \mu_{11} + \mu_{21} = 0.

HideShow
# Biofeedback effect within each drug: how much higher blood pressure runs
# without biofeedback than with it, the book's sign convention on p. 328.
bio_effect <- cell_means_7_10["Absent", ] - cell_means_7_10["Present", ]
bio_effect
HideShow
 X  Y  Z 
20 -4 20 
HideShow
#> 20, -4, 20 for Drugs X, Y, Z, averaging to the 12-point main effect
#> — matches book p. 328 and p. 334

# Contrast 1: the biofeedback effect for Drug Y against that for Drug X.
psi_hat_1     <- bio_effect["Y"] - bio_effect["X"]
sum_c_sq_1    <- 1^2 + (-1)^2 + (-1)^2 + 1^2          # four cells involved
SS_contrast_1 <- n_new * psi_hat_1^2 / sum_c_sq_1
F_contrast_1  <- SS_contrast_1 / MS_W_new

cat("Contrast 1 (Drug Y vs X): SS =", SS_contrast_1, ", F =", F_contrast_1, "\n")
HideShow
Contrast 1 (Drug Y vs X): SS = 864 , F = 6.325037 
HideShow
#> SS 864, F = 6.33 — matches book p. 334

Chosen after looking at the data, this contrast must clear a Scheffé critical value of (a−1)(b−1)F.05,(a−1)(b−1),N−ab(a-1)(b-1)F_{.05,(a-1)(b-1),N-ab}.

HideShow
scheffe_crit <- 2 * qf(0.95, 2, 30)
cat("Scheffé critical value:", scheffe_crit, "\n")
HideShow
Scheffé critical value: 6.631659 
HideShow
#> 6.63; book p. 334 prints 6.64 because it uses the table value F = 3.32 where
#> R uses the exact 3.3158

The observed 6.33 falls short of the critical value, so as a post hoc test it cannot be declared significant. That is puzzling only until we notice it is not the optimal subeffect, which contrasts the biofeedback effect for Drug Y with the average of the effects for Drugs X and Z.

HideShow
# Contrast 2: Drug Y against the average of Drugs X and Z.
psi_hat_2     <- bio_effect["Y"] - 0.5 * bio_effect["X"] - 0.5 * bio_effect["Z"]
sum_c_sq_2    <- 1^2 + (-1)^2 + 4 * 0.5^2             # all six cells involved
SS_contrast_2 <- n_new * psi_hat_2^2 / sum_c_sq_2
F_contrast_2  <- SS_contrast_2 / MS_W_new

cat("Contrast 2 (Drug Y vs average of X and Z): SS =", SS_contrast_2,
    ", F =", F_contrast_2, "\n")
HideShow
Contrast 2 (Drug Y vs average of X and Z): SS = 1152 , F = 8.433382 
HideShow
#> SS 1,152, F = 8.43 — matches book p. 335

This one clears the Scheffé threshold. Notice that its sum of squares, 1,152, is the entire interaction sum of squares from the omnibus table — this single degree of freedom is the whole interaction.

DMAR’s cv_scheffe() gives the same critical value from the design’s degrees of freedom, again in the tt metric, so squaring it recovers the critical FF.

HideShow
cv_s <- cv_scheffe(alpha_level = 0.05, df_numerator = 2, df_denominator = 30,
                   verbose = FALSE)
cv_s
term value
upper_cv 2.575
HideShow
cat("Squared:", cv_s$value^2, "\n")
HideShow
Squared: 6.631659 
HideShow
#> 6.63, the same Scheffé critical F computed by hand above
A planned interaction contrast: the cognitive-neuroscience example

The second example is a 3 × 3 design crossing diagnosis (amnesiac, Huntington’s, control) with task (artificial grammar, classification learning, recognition memory), with five participants per cell. The first two tasks tap implicit memory and the third taps explicit memory, so theory predicts a specific interaction: amnesiacs relatively better on the implicit tasks, Huntington patients relatively better on the explicit task. These are the data of Table 7.11.

HideShow
data(chapter_7_table_11)

# AMCP stores the performance score in a column named Y; rename it to Score so
# the axis label and the plotting code read naturally.
mem <- chapter_7_table_11 |>
  rename(Score = Y) |>
  mutate(
    Diagnosis = case_when(
      Diagnosis == 1 ~ "Amnesiac",
      Diagnosis == 2 ~ "Huntington's",
      Diagnosis == 3 ~ "Control"
    ),
    Task = case_when(
      Task == 1 ~ "Grammar",
      Task == 2 ~ "Classification",
      Task == 3 ~ "Recognition"
    ),
    Diagnosis = factor(Diagnosis, levels = c("Amnesiac", "Huntington's", "Control")),
    Task      = factor(Task, levels = c("Grammar", "Classification", "Recognition"))
  )

cell_means_7_11 <- tapply(mem$Score, list(Diagnosis = mem$Diagnosis, Task = mem$Task), mean)
cell_means_7_11
HideShow
              Task
Diagnosis      Grammar Classification Recognition
  Amnesiac          60             70          65
  Huntington's      40             45          95
  Control           80             80          95
HideShow
#> Amnesiac 60, 70, 65; Huntington's 40, 45, 95; Control 80, 80, 95
#> — matches book p. 339, which reads these means off Table 7.11 (p. 336)

The omnibus ANOVA supplies MSWMS_W and the full interaction sum of squares that the contrast will be measured against.

HideShow
memory_anova  <- aov(Score ~ Diagnosis * Task, data = mem)
anova(memory_anova)
HideShow
Analysis of Variance Table

Response: Score
               Df Sum Sq Mean Sq F value    Pr(>F)    
Diagnosis       2   5250 2625.00 16.6373  7.64e-06 ***
Task            2   5250 2625.00 16.6373  7.64e-06 ***
Diagnosis:Task  4   5000 1250.00  7.9225 0.0001092 ***
Residuals      36   5680  157.78                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> within cells SS 5,680 on 36 df, MS_W = 157.78 — matches book Table 7.12 (p. 338);
#> interaction SS 5,000 — matches book p. 341

MS_W_mem            <- anova(memory_anova)["Residuals", "Mean Sq"]
SS_interaction_full <- anova(memory_anova)["Diagnosis:Task", "Sum Sq"]
c(MS_W = MS_W_mem, SS_AB = SS_interaction_full)
HideShow
     MS_W     SS_AB 
 157.7778 5000.0000 

The contrast coefficients come from Figures 7.3 and 7.4: 1,−1,01, -1, 0 across diagnoses and 0.5,0.5,−10.5, 0.5, -1 across tasks, multiplied cell by cell. The absolute values of the nine cell coefficients sum to 4, not 2, because an interaction contrast is a contrast of contrasts — which matters for the confidence interval, not for the test.

HideShow
# Contrast of contrasts: (amnesiac - Huntington's) by (implicit - explicit).
task_weights <- c(Grammar = 0.5, Classification = 0.5, Recognition = -1)

psi_hat_mem <- sum(task_weights * cell_means_7_11["Amnesiac", names(task_weights)]) -
               sum(task_weights * cell_means_7_11["Huntington's", names(task_weights)])

# Sum of c^2 / n over the nine cells; the control row carries weights of zero.
sum_c_sq_n_mem <- (sum(task_weights^2) + sum((-task_weights)^2)) / 5

SS_contrast_mem <- psi_hat_mem^2 / sum_c_sq_n_mem        # Equation 4.30
F_contrast_mem  <- SS_contrast_mem / MS_W_mem

cat("Estimate:", psi_hat_mem, "  SS:", SS_contrast_mem, "  F:", F_contrast_mem, "\n")
HideShow
Estimate: 52.5   SS: 4593.75   F: 29.11532 
HideShow
#> psi-hat 52.50, SS 4,593.75, F = 29.12 — matches book Table 7.12 (p. 338)

The estimate of 52.50 is easy to check against the cell means: the task difference is 00 for amnesiacs (the average of 60 and 70 against 65) and −52.50-52.50 for Huntington patients (the average of 40 and 45 against 95).

HideShow
# 95% confidence interval for the contrast (Equation 4.40).
F_crit_mem       <- qf(0.95, 1, 36)
margin_error_mem <- sqrt(F_crit_mem) * sqrt(MS_W_mem * sum_c_sq_n_mem)

cat("Standard error:", sqrt(MS_W_mem * sum_c_sq_n_mem), "\n")
HideShow
Standard error: 9.72968 
HideShow
#> 9.73 — matches book Table 7.12 (p. 338)
cat("95% CI: [", psi_hat_mem - margin_error_mem, ",",
    psi_hat_mem + margin_error_mem, "]\n")
HideShow
95% CI: [ 32.7673 , 72.2327 ]
HideShow
#> [32.77, 72.23] — matches book Table 7.12 (p. 338)

The same contrast with emmeans, which takes the nine cell means from the fitted model and the nine weights in the grid’s own order, reproduces the estimate, its standard error, and the interval without our assembling them.

HideShow
fit_mem <- lm(Score ~ Diagnosis * Task, data = mem)
emm_mem <- emmeans(fit_mem, ~ Diagnosis * Task)
emm_mem
HideShow
 Diagnosis    Task           emmean   SE df lower.CL upper.CL
 Amnesiac     Grammar            60 5.62 36     48.6     71.4
 Huntington's Grammar            40 5.62 36     28.6     51.4
 Control      Grammar            80 5.62 36     68.6     91.4
 Amnesiac     Classification     70 5.62 36     58.6     81.4
 Huntington's Classification     45 5.62 36     33.6     56.4
 Control      Classification     80 5.62 36     68.6     91.4
 Amnesiac     Recognition        65 5.62 36     53.6     76.4
 Huntington's Recognition        95 5.62 36     83.6    106.4
 Control      Recognition        95 5.62 36     83.6    106.4

Confidence level used: 0.95 
HideShow
# The grid varies Diagnosis fastest within Task, so the nine weights are listed
# task by task: (amnesiac, Huntington's, control) for Grammar, then Classification,
# then Recognition.
int_contrast <- list(
  "(Amnesiac - Huntington's) x (implicit - explicit)" =
    c(0.5, -0.5, 0,   0.5, -0.5, 0,   -1, 1, 0)
)
contrast(emm_mem, method = int_contrast)
HideShow
 contrast                                          estimate   SE df t.ratio
 (Amnesiac - Huntington's) x (implicit - explicit)     52.5 9.73 36   5.396
 p.value
 <0.0001
HideShow
confint(contrast(emm_mem, method = int_contrast), level = 0.95)
HideShow
 contrast                                          estimate   SE df lower.CL
 (Amnesiac - Huntington's) x (implicit - explicit)     52.5 9.73 36     32.8
 upper.CL
     72.2

Confidence level used: 0.95 
HideShow
#> estimate 52.5, SE 9.73, t = 5.396 (so F = t^2 = 29.12), CI [32.77, 72.23]
#> — matches book Table 7.12 (p. 338)
The same contrast in DMAR

DMAR’s contrast_test() takes a fitted cell-means model and a vector of cell weights and returns the estimate, its standard error, the test, and the interval in one object. Here the weights are given in the design’s own cell order rather than in an estimated-marginal-means grid order, which is how Figure 7.4 lays them out.

HideShow
# One factor whose levels are the nine cells, in the order of Figure 7.4
# (row by row: amnesiac, then Huntington's, then control).
mem_cells <- mem |>
  mutate(Cell = factor(paste(Diagnosis, Task, sep = "-"),
                       levels = as.vector(t(outer(levels(mem$Diagnosis),
                                                  levels(mem$Task),
                                                  paste, sep = "-")))))
levels(mem_cells$Cell)
HideShow
[1] "Amnesiac-Grammar"            "Amnesiac-Classification"    
[3] "Amnesiac-Recognition"        "Huntington's-Grammar"       
[5] "Huntington's-Classification" "Huntington's-Recognition"   
[7] "Control-Grammar"             "Control-Classification"     
[9] "Control-Recognition"        
HideShow
fit_cells <- lm(Score ~ Cell, data = mem_cells)
contrast_test(
  fit_cells,
  contrasts = list(
    "Figure 7.4 interaction contrast" = c( 0.5,  0.5, -1,     # amnesiac
                                          -0.5, -0.5,  1,     # Huntington's
                                           0,    0,    0)),   # control
  conf_level = 0.95
)
contrast estimate se t_value df p_value p_adjusted ci_lower ci_upper
Figure 7.4 interaction contrast 52.500 9.730 5.396 36 < 0.0001 < 0.0001 32.767 72.233

Confidence level: 95%

HideShow
#> estimate 52.500, se 9.730, t = 5.396, CI [32.767, 72.233]
#> — matches book Table 7.12 (p. 338) to every digit SPSS printed there
How much of the interaction the contrast captures

Ralerting2R^2_{\text{alerting}} for an interaction contrast is the contrast’s sum of squares over the interaction sum of squares (Equation 7.63), and the remaining 3 degrees of freedom can be tested on their own.

HideShow
R2_alerting <- SS_contrast_mem / SS_interaction_full     # Equation 7.63
cat("R^2 alerting:", R2_alerting, "\n")
HideShow
R^2 alerting: 0.91875 
HideShow
#> .92 — matches book p. 341

SS_residual <- SS_interaction_full - SS_contrast_mem
df_residual <- 4 - 1                                     # interaction df minus contrast df
F_residual  <- (SS_residual / df_residual) / MS_W_mem

cat("Residual interaction: SS =", SS_residual, ", F =", F_residual,
    ", p =", pf(F_residual, df_residual, 36, lower.tail = FALSE), "\n")
HideShow
Residual interaction: SS = 406.25 , F = 0.8582746 , p = 0.4715331 
HideShow
#> SS 406.25, F = 0.86, p = .47 — matches book p. 341

The planned contrast is a 52.5-point difference of differences with a 95% interval of [32.77,72.23][32.77, 72.23] that comfortably excludes zero, and it accounts for 92% of the sample interaction. The remaining three degrees of freedom are not significant, so it is plausible that this one contrast reflects the entire population interaction — what Abelson and Prentice called a “canonical outcome.”

Figure 7.5. Interaction plot of diagnosis and task
HideShow
cell_means_7_5 <- mem |>
  group_by(Diagnosis, Task) |>
  summarize(Score = mean(Score), .groups = "drop")

ggplot(cell_means_7_5,
       aes(Task, Score, color = Diagnosis, group = Diagnosis)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3.5) +
  labs(title = "Figure 7.5. Interaction plot of diagnosis and task",
       x = "Task", y = "Sample mean task score", color = "Diagnosis") +
  theme(legend.position = "top")
Figure 7.5. Interaction plot of diagnosis and task.

Figure 7.5. Interaction plot of diagnosis and task.

The amnesiac and Huntington lines cross between the implicit tasks and the explicit (recognition) task, exactly the crossover the theory predicts and the planned interaction contrast tests.

7.7 — Statistical Power

Power belongs to a specific test, not to a study. A two-way ANOVA tests three null hypotheses, so it has three powers. The pwr package shows why the interaction is the hard one to detect.

Suppose we plan a 3 × 3 design and want power of .80 at α=.05\alpha = .05 to detect a medium effect, Cohen’s f=0.25f = 0.25. pwr.f2.test() works in f2f^2, and its total sample size is the denominator degrees of freedom plus the numerator degrees of freedom plus one.

HideShow
# 1. Main effect in a 3 x 3 design: numerator df = 3 - 1 = 2; f^2 = 0.25^2.
main_effect_pwr <- pwr.f2.test(u = 2, f2 = 0.25^2, sig.level = 0.05, power = 0.80)
N_main <- main_effect_pwr$v + main_effect_pwr$u + 1
cat("Unrounded total N for a main effect:", N_main, "\n")
HideShow
Unrounded total N for a main effect: 157.1898 
HideShow
# Nine cells, so round up to a whole number of participants per cell.
cat("Per cell:", ceiling(N_main / 9), " Total N:", 9 * ceiling(N_main / 9), "\n")
HideShow
Per cell: 18  Total N: 162 
HideShow
#> 18 per cell, 162 in all — matches book p. 344

Both main effects need the same sample size, because nothing distinguishes B from A in this example. Now the interaction, at the same effect size.

HideShow
# 2. Interaction in a 3 x 3 design: numerator df = (3 - 1)(3 - 1) = 4.
interaction_pwr <- pwr.f2.test(u = 4, f2 = 0.25^2, sig.level = 0.05, power = 0.80)
N_interaction <- interaction_pwr$v + interaction_pwr$u + 1
cat("Unrounded total N for the interaction:", N_interaction, "\n")
HideShow
Unrounded total N for the interaction: 195.767 
HideShow
cat("Per cell:", ceiling(N_interaction / 9), " Total N:",
    9 * ceiling(N_interaction / 9), "\n")
HideShow
Per cell: 22  Total N: 198 
HideShow
#> 22 per cell, 198 in all — matches book p. 344

Thirty-six more participants, a 22% increase, for the same effect size. The reason is that each marginal mean rests on 3n3n observations whereas each cell mean rests on only nn, and, equivalently, that the expected FF depends on the numerator degrees of freedom as well as the noncentrality parameter: the interaction test has 4 numerator degrees of freedom against the main effects’ 2.

There is a second, independent reason interactions are hard to detect: in practice their effect sizes are often smaller. Whenever an interaction is ordinal — the lines in the interaction plot do not cross — its effect size is necessarily smaller than that of the corresponding main effect. If we expect an ordinal interaction and plan for Cohen’s small f=0.10f = 0.10 instead, the required sample size explodes.

HideShow
# 3. Ordinal interaction in a 3 x 3 design, small effect: f^2 = 0.10^2.
ordinal_pwr <- pwr.f2.test(u = 4, f2 = 0.10^2, sig.level = 0.05, power = 0.80)
N_ordinal <- ordinal_pwr$v + ordinal_pwr$u + 1
cat("Unrounded total N for an ordinal interaction:", N_ordinal, "\n")
HideShow
Unrounded total N for an ordinal interaction: 1198.282 
HideShow
cat("Per cell:", ceiling(N_ordinal / 9), " Total N:", 9 * ceiling(N_ordinal / 9), "\n")
HideShow
Per cell: 134  Total N: 1206 
HideShow
#> 1,206 in all — matches book p. 346

The book reports 158 (G*Power) and 157.3 (WebPower) for the first of these, and 196 and 195.9 for the second; pwr returns 157.19 and 195.77. The small differences are rounding conventions inside each package and disappear once the total is rounded up to a whole number of participants per cell, which is why all three routes land on 162 and 198. Unless a researcher has access to a very large subject pool, a standard laboratory study is badly underpowered for an ordinal interaction.

7.9 — Nonorthogonal Designs

When cell sizes are unequal, the main effects and the interaction are no longer independent. The variance they explain overlaps, so the way the sums of squares are computed changes the answer.

7.9.3 — Analysis of the 2 × 2 Nonorthogonal Design

Table 7.16 holds hypothetical salary data, in thousands of dollars, for 12 newly hired female and 10 newly hired male employees, cross-classified by whether they hold a college degree.

HideShow
data(chapter_7_table_16)

# AMCP codes: Sex 1 = female, 2 = male; Education 1 = college degree, 2 = none.
salary <- chapter_7_table_16 |>
  mutate(
    Female = case_when(
      Sex == 1 ~ "Female",
      Sex == 2 ~ "Male"
    ),
    Degree = case_when(
      Education == 1 ~ "Degree",
      Education == 2 ~ "No Degree"
    ),
    Female = factor(Female, levels = c("Female", "Male")),
    Degree = factor(Degree, levels = c("Degree", "No Degree"))
  )

salary
HideShow
   Sex Education Salary Female    Degree
1    1         1     24 Female    Degree
2    1         1     26 Female    Degree
3    1         1     25 Female    Degree
4    1         1     24 Female    Degree
5    1         1     27 Female    Degree
6    1         1     24 Female    Degree
7    1         1     27 Female    Degree
8    1         1     23 Female    Degree
9    1         2     15 Female No Degree
10   1         2     17 Female No Degree
11   1         2     20 Female No Degree
12   1         2     16 Female No Degree
13   2         1     25   Male    Degree
14   2         1     29   Male    Degree
15   2         1     27   Male    Degree
16   2         2     19   Male No Degree
17   2         2     18   Male No Degree
18   2         2     21   Male No Degree
19   2         2     20   Male No Degree
20   2         2     21   Male No Degree
21   2         2     22   Male No Degree
22   2         2     19   Male No Degree
HideShow
str(salary)
HideShow
'data.frame':   22 obs. of  5 variables:
 $ Sex      : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Education: int  1 1 1 1 1 1 1 1 2 2 ...
 $ Salary   : int  24 26 25 24 27 24 27 23 15 17 ...
 $ Female   : Factor w/ 2 levels "Female","Male": 1 1 1 1 1 1 1 1 1 1 ...
 $ Degree   : Factor w/ 2 levels "Degree","No Degree": 1 1 1 1 1 1 1 1 2 2 ...
HideShow
# The unequal cell sizes that make the design nonorthogonal.
table(salary$Female, salary$Degree)
HideShow
        
         Degree No Degree
  Female      8         4
  Male        3         7
HideShow
#> 8, 4, 3, 7 — matches book Table 7.16 (p. 349)

Ignoring education, the mean salary is $22,333 for the 12 females and $22,100 for the 10 males — a $233 difference favoring females. But a majority of the new female employees are college graduates and a majority of the males are not.

HideShow
# Table 7.17: the four cell means, with the cell sizes that produced them.
tapply(salary$Salary, list(`Sex (A)` = salary$Female,
                           `Educational level (B)` = salary$Degree), mean)
HideShow
        Educational level (B)
Sex (A)  Degree No Degree
  Female     25        17
  Male       27        20
HideShow
#> 25, 17, 27, 20 — matches book Table 7.17 (p. 351)

tapply(salary$Salary, salary$Female, mean)
HideShow
  Female     Male 
22.33333 22.10000 
HideShow
#> 22.333 and 22.100, a difference of 0.233 (that is, $233) — matches book p. 349

7.9.4 — Test of the Interaction

Because the main effect may be hard to interpret if the factors interact, we test the interaction first. In a 2 × 2 design with unequal nn, the interaction sum of squares is Equation 7.71, which is the equal-nn formula with the harmonic mean of the four cell sizes in place of the common nn.

HideShow
cell_n <- as.vector(table(salary$Female, salary$Degree))
n_tilde <- length(cell_n) / sum(1 / cell_n)
cat("Harmonic mean of the cell sizes:", n_tilde, "\n")
HideShow
Harmonic mean of the cell sizes: 4.699301 
HideShow
#> 4.699 — matches book p. 350; the arithmetic mean is 5.5
cat("Arithmetic mean of the cell sizes:", mean(cell_n), "\n")
HideShow
Arithmetic mean of the cell sizes: 5.5 
HideShow
cell_means_7_17 <- tapply(salary$Salary, list(salary$Female, salary$Degree), mean)
psi_hat_AB <- cell_means_7_17["Female", "Degree"] - cell_means_7_17["Female", "No Degree"] -
              cell_means_7_17["Male",   "Degree"] + cell_means_7_17["Male",   "No Degree"]

SS_AB_salary <- n_tilde * psi_hat_AB^2 / 4               # Equation 7.71
cat("SS for the interaction:", SS_AB_salary, "\n")
HideShow
SS for the interaction: 1.174825 
HideShow
#> 1.1748 — matches book p. 351

The mean square within is computed for unequal nn exactly as for equal nn, and the interaction FF follows.

HideShow
salary_lm   <- lm(Salary ~ Female * Degree, data = salary)
MS_W_salary <- deviance(salary_lm) / df.residual(salary_lm)
cat("MS_W:", MS_W_salary, "  F for the interaction:", SS_AB_salary / MS_W_salary, "\n")
HideShow
MS_W: 2.777778   F for the interaction: 0.4229371 
HideShow
#> MS_W = 2.7778 and F = 0.4229 — matches book p. 351

The interaction is nonsignificant, so the gender difference is the same for graduates as for non-graduates, within sampling error.

7.9.5 — Unweighted Marginal Means and Type III Sum of Squares

The unweighted marginal mean for females averages the two cell means 25 and 17 to get 21; for males, 27 and 20 give 23.5. When the factor has two levels, the test of the difference between unweighted marginal means is again a single contrast, and its sum of squares is Equation 7.72, ñ(Y‾1⋅(U)−Y‾2⋅(U))2\tilde{n}(\bar{Y}_{1\cdot(U)} - \bar{Y}_{2\cdot(U)})^2. That quantity is the Type III sum of squares.

HideShow
unweighted <- rowMeans(cell_means_7_17)
unweighted
HideShow
Female   Male 
  21.0   23.5 
HideShow
#> 21.0 for females and 23.5 for males — matches book p. 351

SS_A_typeIII <- n_tilde * unname(unweighted["Female"] - unweighted["Male"])^2   # Equation 7.72
F_A_typeIII  <- SS_A_typeIII / MS_W_salary
cat("Type III SS for sex:", SS_A_typeIII, "  F:", F_A_typeIII,
    "  p:", pf(F_A_typeIII, 1, df.residual(salary_lm), lower.tail = FALSE), "\n")
HideShow
Type III SS for sex: 29.37063   F: 10.57343   p: 0.004428981 
HideShow
#> SS 29.3706, F = 10.5734, p = .0044 — matches book p. 352

The two differences are both numerically correct but answer different questions. Comparing an average female with an average male at the same educational level gives the $2,500 advantage to males; comparing the two weighted marginal means, which average over very different educational mixes, gives the $233 advantage to females.

Type I sums of squares and why order matters

R’s aov() and anova() produce Type I (sequential) sums of squares, so the main effects depend on the order in which the terms enter the model.

HideShow
# Entering Degree first, then Female.
anova(aov(Salary ~ Degree * Female, data = salary))
HideShow
Analysis of Variance Table

Response: Salary
              Df  Sum Sq Mean Sq F value    Pr(>F)    
Degree         1 242.227 242.227 87.2018 2.534e-08 ***
Female         1  30.462  30.462 10.9662  0.003881 ** 
Degree:Female  1   1.175   1.175  0.4229  0.523690    
Residuals     18  50.000   2.778                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
# Entering Female first, then Degree.
anova(aov(Salary ~ Female * Degree, data = salary))
HideShow
Analysis of Variance Table

Response: Salary
              Df  Sum Sq Mean Sq F value    Pr(>F)    
Female         1   0.297   0.297  0.1069    0.7475    
Degree         1 272.392 272.392 98.0611 1.038e-08 ***
Female:Degree  1   1.175   1.175  0.4229    0.5237    
Residuals     18  50.000   2.778                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> the interaction line (SS 1.175, F = 0.4229) and the residual line are identical
#> in both orders, but the two main effects change — matches book p. 351

The interaction and residual lines are identical either way; only the main effects move. For background on why R defaults to this behavior, see W. N. Venables’ Exegeses on Linear Models.

Type III sums of squares with car

The book recommends Type III sums of squares for these designs. The car package’s Anova() (note the capital “A”) produces them, but only if the factors carry sum-to-zero contrasts: with R’s default treatment contrasts the “main effect” being removed is not the effect the Type III hypothesis is about. We therefore set the contrasts in a visible chunk, so that a reader who copies this code gets the same sums of squares.

HideShow
# Sum-to-zero contrasts are required for Type III SS to test the unweighted
# marginal means. This is set here, on the page, rather than behind the scenes.
options(contrasts = c("contr.sum", "contr.poly"))

C7T16_lm <- lm(Salary ~ Female * Degree, data = salary)
Anova(C7T16_lm, type = "III")
HideShow
Anova Table (Type III tests)

Response: Salary
              Sum Sq Df   F value    Pr(>F)    
(Intercept)   9305.8  1 3350.0845 < 2.2e-16 ***
Female          29.4  1   10.5734  0.004429 ** 
Degree         264.3  1   95.1608 1.306e-08 ***
Female:Degree    1.2  1    0.4229  0.523690    
Residuals       50.0 18                        
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Female: SS 29.4 (29.3706), F = 10.5734, p = .0044 — matches book p. 352;
#> Female:Degree: SS 1.175, F = 0.4229 — matches book p. 351

# drop1() tests each term against the full model, so it reproduces the Type III
# table once the contrasts are sum-to-zero.
drop1(C7T16_lm, ~ ., test = "F")
HideShow
Single term deletions

Model:
Salary ~ Female * Degree
              Df Sum of Sq     RSS    AIC F value    Pr(>F)    
<none>                      50.000 26.062                      
Female         1    29.371  79.371 34.228 10.5734  0.004429 ** 
Degree         1   264.336 314.336 64.507 95.1608 1.306e-08 ***
Female:Degree  1     1.175  51.175 24.573  0.4229  0.523690    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> the same Female and Female:Degree lines as Anova(type = "III") above

A caution worth seeing: under R’s default treatment contrasts, drop1() does not give Type III sums of squares, even though it is sometimes recommended for that purpose.

HideShow
options(contrasts = c("contr.treatment", "contr.poly"))

drop1(lm(Salary ~ Female * Degree, data = salary), ~ ., test = "F")
HideShow
Single term deletions

Model:
Salary ~ Female * Degree
              Df Sum of Sq     RSS    AIC F value    Pr(>F)    
<none>                      50.000 26.062                      
Female         1     8.727  58.727 27.601  3.1418   0.09323 .  
Degree         1   170.667 220.667 56.723 61.4400 3.273e-07 ***
Female:Degree  1     1.175  51.175 24.573  0.4229   0.52369    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Female: SS 8.727 — NOT the Type III value of 29.3706; the contrast coding,
#> not the function, is what makes a single-term deletion a Type III test

7.10 — Analysis of the General a × b Nonorthogonal Design

The concepts carry over from the 2 × 2 case, but the arithmetic gets harder because an effect with more than 1 degree of freedom is no longer a single contrast.

7.10.1 — Test of the Interaction

The flowchart of Figure 7.2 says to test the interaction first. The book points out on p. 355 that the three types of sums of squares were never distinguished for the interaction: the interaction tests differences among cell means rather than among marginal means, so how one averages across the other factor is simply not at issue. The three types therefore agree exactly on the highest-order interaction, which we can see directly in the salary data.

HideShow
options(contrasts = c("contr.sum", "contr.poly"))
C7T16_lm <- lm(Salary ~ Female * Degree, data = salary)

# Type I (sequential), Type II, and Type III: look at the Female:Degree line.
anova(C7T16_lm)["Female:Degree", ]
HideShow
Analysis of Variance Table

Response: Salary
              Df Sum Sq Mean Sq F value Pr(>F)
Female:Degree  1 1.1748  1.1748  0.4229 0.5237
HideShow
Anova(C7T16_lm, type = "II")["Female:Degree", ]
HideShow
Anova Table (Type II tests)

Response: Salary
              Sum Sq Df F value Pr(>F)
Female:Degree 1.1748  1  0.4229 0.5237
HideShow
Anova(C7T16_lm, type = "III")["Female:Degree", ]
HideShow
Anova Table (Type III tests)

Response: Salary
              Sum Sq Df F value Pr(>F)
Female:Degree 1.1748  1  0.4229 0.5237
HideShow
#> all three give SS 1.175 and F = 0.4229 — matches book p. 351

options(contrasts = c("contr.treatment", "contr.poly"))

7.10.8 — Numerical Example

A clinical psychologist compares three forms of psychotherapy — cognitive-behavioral, Rogerian, and dialectical — on the Depression scale of the MMPI, and also classifies each of the 45 participants by baseline severity (mild, moderate, severe). Cell sizes range from 3 to 7, so the 3 × 3 design is nonorthogonal. These are the data of Table 7.24.

HideShow
data(chapter_7_table_24)

# AMCP codes: Therapy 1 = cognitive-behavioral, 2 = Rogerian, 3 = dialectical;
# Severity 1 = mild, 2 = moderate, 3 = severe.
mmpi <- chapter_7_table_24 |>
  mutate(
    Therapy = case_when(
      Therapy == 1 ~ "Cognitive-Behavioral",
      Therapy == 2 ~ "Rogerian",
      Therapy == 3 ~ "Dialectical"
    ),
    Severity = case_when(
      Severity == 1 ~ "Mild",
      Severity == 2 ~ "Moderate",
      Severity == 3 ~ "Severe"
    ),
    Therapy  = factor(Therapy,
                      levels = c("Cognitive-Behavioral", "Rogerian", "Dialectical")),
    Severity = factor(Severity, levels = c("Mild", "Moderate", "Severe"))
  )

mmpi
HideShow
                Therapy Severity Score
1  Cognitive-Behavioral     Mild    41
2  Cognitive-Behavioral     Mild    43
3  Cognitive-Behavioral     Mild    50
4  Cognitive-Behavioral Moderate    51
5  Cognitive-Behavioral Moderate    43
6  Cognitive-Behavioral Moderate    53
7  Cognitive-Behavioral Moderate    54
8  Cognitive-Behavioral Moderate    46
9  Cognitive-Behavioral   Severe    45
10 Cognitive-Behavioral   Severe    55
11 Cognitive-Behavioral   Severe    56
12 Cognitive-Behavioral   Severe    60
13 Cognitive-Behavioral   Severe    58
14 Cognitive-Behavioral   Severe    62
15 Cognitive-Behavioral   Severe    62
16             Rogerian     Mild    56
17             Rogerian     Mild    47
18             Rogerian     Mild    45
19             Rogerian     Mild    46
20             Rogerian     Mild    49
21             Rogerian Moderate    58
22             Rogerian Moderate    54
23             Rogerian Moderate    49
24             Rogerian Moderate    61
25             Rogerian Moderate    52
26             Rogerian Moderate    62
27             Rogerian   Severe    59
28             Rogerian   Severe    55
29             Rogerian   Severe    68
30             Rogerian   Severe    63
31          Dialectical     Mild    43
32          Dialectical     Mild    56
33          Dialectical     Mild    48
34          Dialectical     Mild    46
35          Dialectical     Mild    47
36          Dialectical Moderate    59
37          Dialectical Moderate    46
38          Dialectical Moderate    58
39          Dialectical Moderate    54
40          Dialectical   Severe    55
41          Dialectical   Severe    69
42          Dialectical   Severe    63
43          Dialectical   Severe    56
44          Dialectical   Severe    62
45          Dialectical   Severe    67
HideShow
str(mmpi)
HideShow
'data.frame':   45 obs. of  3 variables:
 $ Therapy : Factor w/ 3 levels "Cognitive-Behavioral",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Severity: Factor w/ 3 levels "Mild","Moderate",..: 1 1 1 2 2 2 2 2 3 3 ...
 $ Score   : int  41 43 50 51 43 53 54 46 45 55 ...

Had the psychologist ignored severity and run a one-way ANOVA on therapy alone, the treatment effect would not have been detected.

HideShow
anova(aov(Score ~ Therapy, data = mmpi))
HideShow
Analysis of Variance Table

Response: Score
          Df  Sum Sq Mean Sq F value Pr(>F)
Therapy    2  101.11  50.556  0.9342 0.4009
Residuals 42 2272.80  54.114               
HideShow
#> F = 0.93 on 2 and 42 df, nonsignificant — matches book p. 363

Adding severity as a second factor is post hoc blocking: it moves individual differences in MMPI scores that are attributable to severity out of the error term and so can raise the power of the therapy test.

Cell sizes, cell means, and three kinds of marginal mean
HideShow
# Cell sizes and cell means, the top of Table 7.25.
table(mmpi$Therapy, mmpi$Severity)
HideShow
                      
                       Mild Moderate Severe
  Cognitive-Behavioral    3        5      7
  Rogerian                5        6      4
  Dialectical             5        4      6
HideShow
#> 3, 5, 7 / 5, 6, 4 / 5, 4, 6 — matches book Table 7.25 (p. 364)

round(tapply(mmpi$Score, list(`Type of Therapy (A)` = mmpi$Therapy,
                              `Degree of Severity (B)` = mmpi$Severity), mean), 4)
HideShow
                      Degree of Severity (B)
Type of Therapy (A)       Mild Moderate  Severe
  Cognitive-Behavioral 44.6667    49.40 56.8571
  Rogerian             48.6000    56.00 61.2500
  Dialectical          48.0000    54.25 62.0000
HideShow
#> 44.6667, 49.40, 56.8571 / 48.60, 56.00, 61.25 / 48.00, 54.25, 62.00
#> — matches book Table 7.25 (p. 364)

Table 7.25 reports three different marginal means for each level. The Type I marginal means are the ordinary weighted means — each cell contributes in proportion to its size — and dplyr gives them directly.

HideShow
# Type I (weighted) marginal means, with the cell counts that weight them.
mmpi |> group_by(Therapy) |>
  summarise(mean = mean(Score), sd = sd(Score), n = n(), .groups = "drop")
HideShow
# A tibble: 3 × 4
  Therapy               mean    sd     n
  <fct>                <dbl> <dbl> <int>
1 Cognitive-Behavioral  51.9  7.09    15
2 Rogerian              54.9  6.92    15
3 Dialectical           55.3  8.01    15
HideShow
mmpi |> group_by(Severity) |>
  summarise(mean = mean(Score), sd = sd(Score), n = n(), .groups = "drop")
HideShow
# A tibble: 3 × 4
  Severity  mean    sd     n
  <fct>    <dbl> <dbl> <int>
1 Mild      47.5  4.54    13
2 Moderate  53.3  5.68    15
3 Severe    59.7  5.91    17
HideShow
# The same weighted means, at the precision the book prints them.
round(tapply(mmpi$Score, mmpi$Therapy,  mean), 4)
HideShow
Cognitive-Behavioral             Rogerian          Dialectical 
             51.9333              54.9333              55.2667 
HideShow
#> 51.9333, 54.9333, 55.2667 — matches the "I" rows of book Table 7.25 (p. 364)
round(tapply(mmpi$Score, mmpi$Severity, mean), 4)
HideShow
    Mild Moderate   Severe 
 47.4615  53.3333  59.7059 
HideShow
#> 47.4615, 53.3333, 59.7059 — matches the "I" columns of book Table 7.25 (p. 364)

The Type III marginal means are unweighted — each cell mean counts once, whatever its size — so they are the row and column means of the cell-mean table.

HideShow
cell_means_7_25 <- tapply(mmpi$Score, list(mmpi$Therapy, mmpi$Severity), mean)
round(rowMeans(cell_means_7_25), 4)
HideShow
Cognitive-Behavioral             Rogerian          Dialectical 
             50.3079              55.2833              54.7500 
HideShow
#> 50.3079, 55.2833, 54.75 — matches the "III" rows of book Table 7.25 (p. 364)
round(colMeans(cell_means_7_25), 4)
HideShow
    Mild Moderate   Severe 
 47.0889  53.2167  60.0357 
HideShow
#> 47.0889, 53.2167, 60.0357 — matches the "III" columns of book Table 7.25 (p. 364)
Visualizing the interaction

Plotting the cell means before fitting anything is always worth the trouble.

HideShow
mmpi_cell_means <- mmpi |>
  group_by(Therapy, Severity) |>
  summarize(Score = mean(Score), .groups = "drop")

ggplot(mmpi_cell_means,
       aes(Therapy, Score, color = Severity, group = Severity)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3.5) +
  labs(title = "Interaction plot for MMPI depression scores",
       x = "Type of therapy", y = "Mean MMPI depression score",
       color = "Severity") +
  theme(legend.position = "top")
Cell means of the MMPI depression scores, by type of therapy and degree of severity.

Cell means of the MMPI depression scores, by type of therapy and degree of severity.

The three lines are close to parallel, which is what a nonsignificant interaction looks like.

Type I, II, and III sums of squares

With Type I sums of squares, the therapy main effect depends on whether it is entered first or second.

HideShow
# Therapy entered first: therapy is tested ignoring severity.
anova(aov(Score ~ Therapy * Severity, data = mmpi))
HideShow
Analysis of Variance Table

Response: Score
                 Df  Sum Sq Mean Sq F value    Pr(>F)    
Therapy           2  101.11   50.56  1.8102    0.1782    
Severity          2 1253.19  626.59 22.4357 4.711e-07 ***
Therapy:Severity  4   14.19    3.55  0.1270    0.9717    
Residuals        36 1005.42   27.93                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Therapy SS 101.11, F = 1.81, p = .18 — matches book Table 7.26 (p. 366)

# Severity entered first: therapy is tested allowing for severity.
anova(aov(Score ~ Severity * Therapy, data = mmpi))
HideShow
Analysis of Variance Table

Response: Score
                 Df  Sum Sq Mean Sq F value    Pr(>F)    
Severity          2 1115.82  557.91 19.9764 1.458e-06 ***
Therapy           2  238.48  119.24  4.2695   0.02168 *  
Severity:Therapy  4   14.19    3.55  0.1270   0.97170    
Residuals        36 1005.42   27.93                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Severity SS 1,115.82, F = 19.98; Therapy SS 238.48, F = 4.27, p = .02
#> — matches book Table 7.26 (p. 366)

Type II tests each main effect allowing for the other main effect but ignoring the interaction.

HideShow
C7T24_lm <- lm(Score ~ Therapy * Severity, data = mmpi)
Anova(C7T24_lm, type = "II")
HideShow
Anova Table (Type II tests)

Response: Score
                  Sum Sq Df F value    Pr(>F)    
Therapy           238.48  2  4.2695   0.02168 *  
Severity         1253.19  2 22.4357 4.711e-07 ***
Therapy:Severity   14.19  4  0.1270   0.97170    
Residuals        1005.42 36                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Therapy SS 238.48, F = 4.27, p = .0217; Severity SS 1,253.19, F = 22.44
#> — matches book Table 7.26 (p. 366)

Type III tests each main effect allowing for the other main effect and the interaction, which is the unweighted-marginal-means hypothesis the book recommends reporting. As in Section 7.9.5, the contrasts must be sum-to-zero.

HideShow
options(contrasts = c("contr.sum", "contr.poly"))

C7T24_lm_Type3 <- lm(Score ~ Therapy * Severity, data = mmpi)
Anova(C7T24_lm_Type3, type = "III")
HideShow
Anova Table (Type III tests)

Response: Score
                 Sum Sq Df   F value    Pr(>F)    
(Intercept)      121174  1 4338.7178 < 2.2e-16 ***
Therapy             205  2    3.6658   0.03556 *  
Severity           1181  2   21.1452 8.447e-07 ***
Therapy:Severity     14  4    0.1270   0.97170    
Residuals          1005 36                        
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Therapy F = 3.6658, p = .0356 (SS printed as 205, exactly 204.76 below);
#> Severity F = 21.1452 (SS 1,181.11); Therapy:Severity SS 14.19, F = 0.13,
#> p = .97 — matches book Table 7.26 (p. 366) and the interaction on book p. 365

The interaction is thoroughly nonsignificant (p=.97p = .97), so the main-effect tests can be interpreted. Thanks to the post hoc blocking on severity, the therapy main effect is now significant under both Type III (p=.036p = .036) and Type II (p=.022p = .022), where the one-way ANOVA that ignored severity gave F=0.93F = 0.93. The reason is the smaller error term: severity has a large effect on MMPI scores, and in the two-way design that variability no longer sits in MSWMS_W.

We can reproduce the Type III sum of squares for therapy from Equation 7.77 directly, as a check on what Anova() is doing. The formula needs the “effective” cell size of each row, ñj⋅=b/∑k(1/njk)\tilde{n}_{j\cdot} = b / \sum_k (1/n_{jk}), and a weighted grand mean.

HideShow
cell_n_mmpi <- table(mmpi$Therapy, mmpi$Severity)
b_levels    <- ncol(cell_n_mmpi)

n_tilde_row <- apply(cell_n_mmpi, 1, function(r) b_levels / sum(1 / r))
round(n_tilde_row, 4)
HideShow
Cognitive-Behavioral             Rogerian          Dialectical 
              4.4366               4.8649               4.8649 
HideShow
#> 4.4366, 4.8649, 4.8649 — matches book p. 366

Y_unweighted <- rowMeans(cell_means_7_25)
Y_G_A        <- sum(n_tilde_row * Y_unweighted) / sum(n_tilde_row)
cat("Weighted grand mean for the A effect:", Y_G_A, "\n")
HideShow
Weighted grand mean for the A effect: 53.54199 
HideShow
#> 53.5420 — matches book p. 366

SS_A_III <- sum(b_levels * n_tilde_row * (Y_unweighted - Y_G_A)^2)   # Equation 7.77
cat("Type III SS for therapy:", SS_A_III, "\n")
HideShow
Type III SS for therapy: 204.7617 
HideShow
#> 204.76 — matches book p. 366 and Table 7.26
Post hoc testing of the therapy main effect

The therapy main effect is significant and the factor has three levels, so we ask which therapies differ. Base R’s TukeyHSD() works on the aov object, which carries Type I sums of squares, so it compares weighted marginal means.

HideShow
options(contrasts = c("contr.treatment", "contr.poly"))

C7T24_ANOVA <- aov(Score ~ Therapy * Severity, data = mmpi)
TukeyHSD(C7T24_ANOVA, "Therapy")
HideShow
  Tukey multiple comparisons of means
    95% family-wise confidence level

Fit: aov(formula = Score ~ Therapy * Severity, data = mmpi)

$Therapy
                                      diff       lwr      upr     p adj
Rogerian-Cognitive-Behavioral    3.0000000 -1.716792 7.716792 0.2781897
Dialectical-Cognitive-Behavioral 3.3333333 -1.383458 8.050125 0.2090188
Dialectical-Rogerian             0.3333333 -4.383458 5.050125 0.9836924

None of the pairwise differences is significant — which seems to contradict the significant Type III main effect. The contradiction is only apparent: TukeyHSD() is testing weighted marginal means, and in an unbalanced design those can mask the treatment effect, because the therapy groups do not contain the same mix of severity levels.

To test the unweighted marginal means that the Type III test is about, we use estimated marginal means from the emmeans package, feeding it the sum-to-zero model built above.

HideShow
# The unweighted (Type III) marginal means for therapy.
marginal_means <- emmeans(C7T24_lm_Type3, ~ Therapy)
marginal_means
HideShow
 Therapy              emmean   SE df lower.CL upper.CL
 Cognitive-Behavioral   50.3 1.45 36     47.4     53.2
 Rogerian               55.3 1.38 36     52.5     58.1
 Dialectical            54.8 1.38 36     51.9     57.6

Results are averaged over the levels of: Severity 
Confidence level used: 0.95 
HideShow
#> 50.3, 55.3, 54.8 as emmeans rounds them; the full values 50.3079, 55.2833,
#> 54.7500 printed above are the "III" rows of book Table 7.25 (p. 364)

# Pairwise comparisons of those means, Tukey-adjusted.
# Note: pairs() here is emmeans::pairs(), not the base-graphics scatterplot matrix.
pairwise_results <- pairs(marginal_means, adjust = "tukey")
pairwise_results
HideShow
 contrast                             estimate   SE df t.ratio p.value
 (Cognitive-Behavioral) - Rogerian      -4.975 2.00 36  -2.484  0.0457
 (Cognitive-Behavioral) - Dialectical   -4.442 2.00 36  -2.218  0.0817
 Rogerian - Dialectical                  0.533 1.96 36   0.273  0.9599

Results are averaged over the levels of: Severity 
P value adjustment: tukey method for comparing a family of 3 estimates 

Comparing the unweighted means, cognitive-behavioral therapy differs from Rogerian therapy (p=.046p = .046). The same severity-level imbalance that depressed the one-way FF was hiding this difference from TukeyHSD().

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 7: Two-Way Between-Subjects Factorial Designs (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

Chapter 8: Higher-Order Between-Subjects Factorial Designs

Open the separate reading

Code
Results
On this page

Chapter 1 covers the R groundwork these notes take for granted: installing packages from CRAN, loading them, and the way the book’s data sets are named. This chapter draws on one of them, chapter_8_table_12, the blood pressure data of Table 8.12. The population means of Section 8.3 and the abstract cell means of Figures 8.2 through 8.5 are not data sets at all — they are entered here directly from the printed tables and figures. data(package = "AMCP") lists every data set in the package.

HideShow
# Load all of the packages used.
library(tidyverse)      # data wrangling and plotting (dplyr, ggplot2, and friends)
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(broom)          # tidy model output into data frames
library(effectsize)     # effect sizes (eta-squared, omega-squared)
library(emmeans)        # estimated marginal means and contrasts
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables

8.1 — Overview of Chapter: Research Questions Addressed

Chapter 8 introduces higher-order between-subjects factorial designs, centering on the three-way ANOVA and the concept of a three-way interaction. A three-way interaction tests whether the nature of a two-way interaction changes across the levels of a third factor. When this interaction is statistically significant, it is a warning that interpreting overall main effects or two-way interactions in isolation can be misleading, because the outcome depends on the specific combination of all three variables. To unpack these conditional relationships, the omnibus test is decomposed into simple two-way interactions, then simple main effects, then comparisons of individual cell means. The underlying mathematics scales to any number of factors, but the chapter notes that designs with more than three factors are uncommon in the behavioral sciences, both because of sample-size requirements and because very high-order interactions are not terribly informative to describe.

8.3 — The 2 ×\times 2 ×\times 2 Design

The chapter begins with a 2 ×\times 2 ×\times 2 version of the hypertension study of Chapter 7, adding diet therapy as a third factor. The eight values in Table 8.1 are population means, so there is no sampling error: any nonzero difference is a true effect, and tests of statistical significance are beside the point. Following the book, the drug factor is A, biofeedback is B, and diet is C.

HideShow
# Table 8.1 population means (blood pressure), entered from the book.
pop_8_1 <- expand.grid(
  Drug        = c("Present", "Absent"),
  Biofeedback = c("Present", "Absent"),
  Diet        = c("Absent", "Present"),
  stringsAsFactors = FALSE
) |>
  mutate(
    Drug        = factor(Drug,        levels = c("Present", "Absent")),
    Biofeedback = factor(Biofeedback, levels = c("Present", "Absent")),
    Diet        = factor(Diet,        levels = c("Absent", "Present")),
    BP = c(180, 200, 205, 210,    # diet absent:  (DrugP/BioP, DrugA/BioP, DrugP/BioA, DrugA/BioA)
           170, 185, 190, 190)    # diet present: same order
  )

pop_8_1
HideShow
     Drug Biofeedback    Diet  BP
1 Present     Present  Absent 180
2  Absent     Present  Absent 200
3 Present      Absent  Absent 205
4  Absent      Absent  Absent 210
5 Present     Present Present 170
6  Absent     Present Present 185
7 Present      Absent Present 190
8  Absent      Absent Present 190
HideShow
#> the eight cell means match book Table 8.1, p. 388

8.3.3 — The Meaning of the Three-Way Interaction

A three-way interaction means that the two-way A ×\times B effect is not the same at every level of C. For these population means, that question becomes: is the Drug ×\times Biofeedback interaction the same when diet is absent as when diet is present? Table 8.5 lays the two 2 ×\times 2 tables side by side and takes the difference of differences.

HideShow
# The drug effect (absent minus present) within each Biofeedback x Diet combination,
# then the difference between those drug effects: the two-way interaction at each
# level of Diet. This is the arithmetic of Table 8.5.
drug_effects <- pop_8_1 |>
  pivot_wider(names_from = Drug, values_from = BP, names_prefix = "Drug ") |>
  mutate(`Drug effect` = `Drug Absent` - `Drug Present`)

drug_effects
HideShow
# A tibble: 4 × 5
  Biofeedback Diet    `Drug Present` `Drug Absent` `Drug effect`
  <fct>       <fct>            <dbl>         <dbl>         <dbl>
1 Present     Absent             180           200            20
2 Absent      Absent             205           210             5
3 Present     Present            170           185            15
4 Absent      Present            190           190             0
HideShow
#> drug effects 20, 5 (diet absent) and 15, 0 (diet present) match book Table 8.5, p. 391

drug_effects |>
  group_by(Diet) |>
  summarize(
    `Drug x Biofeedback interaction` =
      `Drug effect`[Biofeedback == "Present"] - `Drug effect`[Biofeedback == "Absent"],
    .groups = "drop"
  )
HideShow
# A tibble: 2 × 2
  Diet    `Drug x Biofeedback interaction`
  <fct>                              <dbl>
1 Absent                                15
2 Present                               15
HideShow
#> 15 and 15 — matches book p. 391: the two-way interaction is 15 at both levels
#> of diet, so the three-way interaction is exactly zero

When diet is absent the drug lowers blood pressure 20 points with biofeedback and 5 points without it, a difference of 15. When diet is present the corresponding drug effects are 15 and 0, again a difference of 15. Because the two-way interaction has the same value at both levels of diet, the three-way interaction is zero in this population.

8.3.4 — Graphical Depiction

Figure 8.1 plots the same eight means, with drug condition on the horizontal axis, a line for each biofeedback condition, and one panel per diet condition.

HideShow
ggplot(pop_8_1, aes(Drug, BP, group = Biofeedback, color = Biofeedback)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  facet_wrap(~ Diet, labeller = labeller(
    Diet = c(Absent = "(a) Diet absent", Present = "(b) Diet present"))) +
  scale_color_brewer(palette = "Dark2") +
  scale_y_continuous(limits = c(160, 220), breaks = seq(170, 210, by = 10)) +
  labs(title = "Figure 8.1. Cell means by diet condition (no three-way interaction)",
       x = "Drug", y = "Population mean blood pressure", color = "Biofeedback") +
  theme(legend.position = "top")
Figure 8.1. Plots of the Table 8.1 cell means as a function of diet condition: (a) diet absent and (b) diet present.

Figure 8.1. Plots of the Table 8.1 cell means as a function of diet condition: (a) diet absent and (b) diet present.

In both panels the lines are non-parallel, so biofeedback and drug interact at each level of diet. The book formalizes the correspondence between the two panels with four simple effects: Δ1\Delta_1 and Δ2\Delta_2 are the biofeedback effects when diet is absent (drug present and drug absent, respectively), and Δ3\Delta_3 and Δ4\Delta_4 are the same two effects when diet is present.

HideShow
# The four simple effects marked by brackets in Figure 8.1: the biofeedback
# effect (absent minus present) within each Drug x Diet combination.
deltas <- pop_8_1 |>
  pivot_wider(names_from = Biofeedback, values_from = BP,
              names_prefix = "Biofeedback ") |>
  mutate(`Biofeedback effect` = `Biofeedback Absent` - `Biofeedback Present`) |>
  dplyr::select(Diet, Drug, `Biofeedback effect`)

deltas
HideShow
# A tibble: 4 × 3
  Diet    Drug    `Biofeedback effect`
  <fct>   <fct>                  <dbl>
1 Absent  Present                   25
2 Absent  Absent                    10
3 Present Present                   20
4 Present Absent                     5
HideShow
#> 25, 10, 20, 5 — matches book p. 392: Delta_1 = 25 (205 - 180), Delta_2 = 10
#> (210 - 200), Delta_3 = 20 (190 - 170), Delta_4 = 5 (190 - 185)

deltas |>
  group_by(Diet) |>
  summarize(`Delta difference` = `Biofeedback effect`[Drug == "Present"] -
                                 `Biofeedback effect`[Drug == "Absent"],
            .groups = "drop")
HideShow
# A tibble: 2 × 2
  Diet    `Delta difference`
  <fct>                <dbl>
1 Absent                  15
2 Present                 15
HideShow
#> 15 and 15 — matches book p. 392: Delta_1 - Delta_2 = Delta_3 - Delta_4 = 15

Underneath each panel of Figure 8.1 the book prints the parameters of two separate two-way full models, one per diet condition, using Equations 7.9–7.12. Those parameters make the equivalence of the two panels exact.

HideShow
# Equations 7.9-7.12 applied separately within each level of diet: the grand
# mean, the two sets of main-effect parameters, and the four interaction
# parameters of a 2 x 2 full model.
two_way_parameters <- function(cells) {
  mu    <- mean(cells$BP)                                     # grand mean
  alpha <- tapply(cells$BP, cells$Drug,        mean) - mu     # drug (A)
  beta  <- tapply(cells$BP, cells$Biofeedback, mean) - mu     # biofeedback (B)
  alphabeta <- matrix(NA_real_, nrow = length(alpha), ncol = length(beta),
                      dimnames = list(Drug = names(alpha), Biofeedback = names(beta)))
  for (j in names(alpha)) {
    for (k in names(beta)) {
      cell <- cells$BP[cells$Drug == j & cells$Biofeedback == k]
      alphabeta[j, k] <- cell - (mu + alpha[j] + beta[k])
    }
  }
  list(mu = mu, alpha = alpha, beta = beta, alphabeta = alphabeta)
}

params_absent  <- two_way_parameters(filter(pop_8_1, Diet == "Absent"))
params_present <- two_way_parameters(filter(pop_8_1, Diet == "Present"))

params_absent
HideShow
$mu
[1] 198.75

$alpha
Present  Absent 
  -6.25    6.25 

$beta
Present  Absent 
  -8.75    8.75 

$alphabeta
         Biofeedback
Drug      Present Absent
  Present   -3.75   3.75
  Absent     3.75  -3.75
HideShow
#> mu = 198.75, alpha = -6.25 / 6.25, beta = -8.75 / 8.75,
#> alphabeta = -3.75, 3.75, 3.75, -3.75 — matches book Figure 8.1(a), p. 393

params_present
HideShow
$mu
[1] 183.75

$alpha
Present  Absent 
  -3.75    3.75 

$beta
Present  Absent 
  -6.25    6.25 

$alphabeta
         Biofeedback
Drug      Present Absent
  Present   -3.75   3.75
  Absent     3.75  -3.75
HideShow
#> mu = 183.75, alpha = -3.75 / 3.75, beta = -6.25 / 6.25,
#> alphabeta = -3.75, 3.75, 3.75, -3.75 — matches book Figure 8.1(b), p. 393

# The three-way interaction is zero exactly when the two sets of alpha-beta
# parameters agree.
all.equal(params_absent$alphabeta, params_present$alphabeta)
HideShow
[1] TRUE
HideShow
#> TRUE — matches book p. 393: "each alpha-beta parameter has the same value
#> when diet is absent as when diet is present"

The grand means and the main-effect parameters differ between the two panels (blood pressure is simply lower when diet is present), but every interaction parameter is identical. That identity is the absence of a three-way interaction.

8.3.5 — Further Consideration of the Three-Way Interaction

Figure 8.1 showed a case with no three-way interaction. To show how a three-way interaction can hide inside an averaged two-way plot, the text works through two small abstract 2 ×\times 2 ×\times 2 examples on a generic outcome Y. These cell means are entered directly from the book’s figures; because they are population means, every difference shown is a true effect.

Figure 8.2. A by B at the two levels of C (first example)

At the first level of C the A ×\times B lines cross, so A and B interact strongly. At the second level of C the two lines are flat and parallel, so A and B do not interact there. Because the A ×\times B interaction is present at C1_1 but absent at C2_2, the two two-way interactions cannot be equal, which is exactly what a three-way interaction means.

HideShow
# Cell means read from the book's Figure 8.2 panels.
ex1 <- expand.grid(A = c("A1", "A2"), B = c("B1", "B2"), C = c("C1", "C2"),
                   stringsAsFactors = FALSE) |>
  mutate(
    A = factor(A, levels = c("A1", "A2")),
    B = factor(B, levels = c("B1", "B2")),
    C = factor(C, levels = c("C1", "C2")),
    Y = c(2, 6, 6, 2,     # at C1: B1 rises 2 -> 6, B2 falls 6 -> 2 (lines cross)
          5, 5, 3, 3)     # at C2: B1 flat at 5, B2 flat at 3 (parallel)
  )
#> cell means match book Figure 8.2, p. 395

a_labels <- c(A1 = "A₁", A2 = "A₂")
b_labels <- c(B1 = "B₁", B2 = "B₂")

ggplot(ex1, aes(A, Y, group = B, color = B)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  facet_wrap(~ C, labeller = labeller(
    C = c(C1 = "(a) At the first level of C", C2 = "(b) At the second level of C"))) +
  scale_x_discrete(labels = a_labels) +
  scale_color_brewer(palette = "Dark2", labels = b_labels) +
  scale_y_continuous(limits = c(1, 7), breaks = 1:7) +
  labs(title = "Figure 8.2. A by B at each level of C (interaction at C₁ only)",
       x = "Factor A", y = expression("Population cell mean of" ~ italic(Y)),
       color = "Factor B") +
  theme(legend.position = "top")
Figure 8.2. Interaction plots for A and B at (a) the first level of C and (b) the second level of C.

Figure 8.2. Interaction plots for A and B at (a) the first level of C and (b) the second level of C.

Figure 8.3. A by B averaging over C (first example)

The same example, now collapsed over C: each plotted mean averages the C1_1 and C2_2 values from Figure 8.2. The lines cross, so there is a non-zero A ×\times B interaction on average. But this averaged picture blends a strong interaction at C1_1 with no interaction at C2_2. The better summary is that A and B interact at C1_1 but not at C2_2, which is why a three-way interaction calls for interpreting simple effects rather than averaged effects.

HideShow
ex1_avg <- ex1 |>
  group_by(A, B) |>
  summarise(Y = mean(Y), .groups = "drop")

ex1_avg
HideShow
# A tibble: 4 × 3
  A     B         Y
  <fct> <fct> <dbl>
1 A1    B1      3.5
2 A1    B2      4.5
3 A2    B1      5.5
4 A2    B2      2.5
HideShow
#> 3.5, 5.5 (B1) and 4.5, 2.5 (B2) — matches book Figure 8.3, p. 396

ggplot(ex1_avg, aes(A, Y, group = B, color = B)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  scale_x_discrete(labels = a_labels) +
  scale_color_brewer(palette = "Dark2", labels = b_labels) +
  scale_y_continuous(limits = c(2, 6), breaks = seq(2, 6, by = 0.5)) +
  labs(title = "Figure 8.3. A by B averaging over C (interaction survives the average)",
       x = "Factor A", y = expression("Population marginal mean of" ~ italic(Y)),
       color = "Factor B") +
  theme(legend.position = "top")
Figure 8.3. Interaction plot for A and B averaging over the levels of C (first example).

Figure 8.3. Interaction plot for A and B averaging over the levels of C (first example).

Figure 8.4. A by B at the two levels of C (second example)

A second, unrelated abstract 2 ×\times 2 ×\times 2 example. Here A and B interact at both levels of C, but in opposite directions: at C1_1 the B1_1 line rises while B2_2 stays flat, and at C2_2 the B1_1 line falls while B2_2 stays flat. The two two-way interactions are equal in size and opposite in sign, so they cancel when averaged.

HideShow
# Cell means read from the book's Figure 8.4 panels.
ex2 <- expand.grid(A = c("A1", "A2"), B = c("B1", "B2"), C = c("C1", "C2"),
                   stringsAsFactors = FALSE) |>
  mutate(
    A = factor(A, levels = c("A1", "A2")),
    B = factor(B, levels = c("B1", "B2")),
    C = factor(C, levels = c("C1", "C2")),
    Y = c(2, 6, 5, 5,     # at C1: B1 rises 2 -> 6, B2 flat at 5
          6, 2, 3, 3)     # at C2: B1 falls 6 -> 2, B2 flat at 3
  )
#> cell means match book Figure 8.4, p. 397

ggplot(ex2, aes(A, Y, group = B, color = B)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  facet_wrap(~ C, labeller = labeller(
    C = c(C1 = "(a) At the first level of C", C2 = "(b) At the second level of C"))) +
  scale_x_discrete(labels = a_labels) +
  scale_color_brewer(palette = "Dark2", labels = b_labels) +
  scale_y_continuous(limits = c(1, 7), breaks = 1:7) +
  labs(title = "Figure 8.4. A by B at each level of C (opposite interactions)",
       x = "Factor A", y = expression("Population cell mean of" ~ italic(Y)),
       color = "Factor B") +
  theme(legend.position = "top")
Figure 8.4. Interaction plots for A and B at (a) the first level of C and (b) the second level of C (second example).

Figure 8.4. Interaction plots for A and B at (a) the first level of C and (b) the second level of C (second example).

Figure 8.5. A by B averaging over C (second example)

Averaging the second example over C gives a population mean of 4 for every combination of A and B, so the B1_1 and B2_2 lines lie exactly on top of one another. After averaging there is no A main effect, no B main effect, and no A ×\times B interaction. Yet A and B interact at both levels of C; the two interactions simply cancel. Reading the averaged plot as “A and B do not interact” would obscure the real structure of the data, which is the central caution of the chapter.

HideShow
ex2_avg <- ex2 |>
  group_by(A, B) |>
  summarise(Y = mean(Y), .groups = "drop")

ex2_avg
HideShow
# A tibble: 4 × 3
  A     B         Y
  <fct> <fct> <dbl>
1 A1    B1        4
2 A1    B2        4
3 A2    B1        4
4 A2    B2        4
HideShow
#> all four means equal 4 — matches book p. 396, where the text gives the four
#> averaged cell means; the plot of them is Figure 8.5, p. 398

# The A1 - A2 difference within each B x C combination, which the averaged plot hides.
ex2 |>
  pivot_wider(names_from = A, values_from = Y) |>
  mutate(`A1 - A2` = A1 - A2) |>
  select(B, C, `A1 - A2`)
HideShow
# A tibble: 4 × 3
  B     C     `A1 - A2`
  <fct> <fct>     <dbl>
1 B1    C1           -4
2 B2    C1            0
3 B1    C2            4
4 B2    C2            0
HideShow
#> -4, 0, 4, 0 for B1C1, B2C1, B1C2, B2C2 — matches book p. 397

ggplot(ex2_avg, aes(A, Y, group = B, color = B)) +
  # Nudge the second line slightly so the coincident lines are both visible.
  geom_line(aes(linetype = B),
            linewidth = 1,
            position = position_dodge(width = 0.04)) +
  geom_point(aes(shape = B), size = 3,
             position = position_dodge(width = 0.04)) +
  scale_x_discrete(labels = a_labels) +
  scale_color_brewer(palette = "Dark2", labels = b_labels) +
  scale_linetype_discrete(labels = b_labels) +
  scale_shape_discrete(labels = b_labels) +
  scale_y_continuous(limits = c(2, 4.5), breaks = seq(2, 4.5, by = 0.5)) +
  labs(title = "Figure 8.5. A by B averaging over C (interactions cancel)",
       x = "Factor A", y = expression("Population marginal mean of" ~ italic(Y)),
       color = "Factor B", linetype = "Factor B", shape = "Factor B") +
  theme(legend.position = "top")
Figure 8.5. Interaction plot for A and B averaging over C (second example): the two lines coincide.

Figure 8.5. Interaction plot for A and B averaging over C (second example): the two lines coincide.

8.5 — Numerical Example

The numerical example extends the Chapter 7 hypertension data by adding a diet factor: biofeedback (A, two levels), drug therapy (B, three levels), and diet (C, two levels), a 2 ×\times 3 ×\times 2 design with n=6n = 6 per cell and N=72N = 72. The data for the diet-absent condition are the same scores used in Chapter 7.

HideShow
# Table 8.12: the blood pressure data.
data(chapter_8_table_12)
str(chapter_8_table_12)
HideShow
'data.frame':   72 obs. of  4 variables:
 $ BP         : int  170 175 165 180 160 158 161 173 157 152 ...
 $ Drug       : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Biofeedback: int  2 2 2 2 2 2 2 2 2 2 ...
 $ Diet       : int  1 1 1 1 1 1 2 2 2 2 ...
HideShow
# Spell out each numeric code, then set the level order to match the book's tables.
bp <- chapter_8_table_12 |>
  as_tibble() |>
  mutate(
    Biofeedback = case_when(
      Biofeedback == 1 ~ "Absent",
      Biofeedback == 2 ~ "Present"
    ),
    Drug = case_when(
      Drug == 1 ~ "X",
      Drug == 2 ~ "Y",
      Drug == 3 ~ "Z"
    ),
    Diet = case_when(
      Diet == 1 ~ "Absent",
      Diet == 2 ~ "Present"
    )
  ) |>
  mutate(
    Biofeedback = factor(Biofeedback, levels = c("Present", "Absent")),
    Drug        = factor(Drug,        levels = c("X", "Y", "Z")),
    Diet        = factor(Diet,        levels = c("Absent", "Present"))
  )

head(bp, 10)
HideShow
# A tibble: 10 × 4
      BP Drug  Biofeedback Diet   
   <int> <fct> <fct>       <fct>  
 1   170 X     Present     Absent 
 2   175 X     Present     Absent 
 3   165 X     Present     Absent 
 4   180 X     Present     Absent 
 5   160 X     Present     Absent 
 6   158 X     Present     Absent 
 7   161 X     Present     Present
 8   173 X     Present     Present
 9   157 X     Present     Present
10   152 X     Present     Present

Table 8.13 reports the cell means, arranged as two 2 ×\times 3 tables, one per diet condition.

HideShow
# Cell means and standard deviations (the book's Table 8.13 shows the means).
bp |>
  group_by(Diet, Biofeedback, Drug) |>
  summarise(mean_BP = mean(BP), sd_BP = sd(BP), n = n(), .groups = "drop")
HideShow
# A tibble: 12 × 6
   Diet    Biofeedback Drug  mean_BP sd_BP     n
   <fct>   <fct>       <fct>   <dbl> <dbl> <int>
 1 Absent  Present     X         168  8.60     6
 2 Absent  Present     Y         204 12.7      6
 3 Absent  Present     Z         189 12.6      6
 4 Absent  Absent      X         188 10.9      6
 5 Absent  Absent      Y         200 10.1      6
 6 Absent  Absent      Z         209 14.4      6
 7 Present Present     X         169 14.8      6
 8 Present Present     Y         172 10.9      6
 9 Present Present     Z         173 11.7      6
10 Present Absent      X         173  9.80     6
11 Present Absent      Y         187 14.0      6
12 Present Absent      Z         182 17.1      6
HideShow
#> diet absent  168, 204, 189 / 188, 200, 209
#> diet present 169, 172, 173 / 173, 187, 182 — all match book Table 8.13, p. 405

# The marginal means that Table 8.13 also displays.
bp |> group_by(Diet, Biofeedback) |> summarise(mean_BP = mean(BP), .groups = "drop")
HideShow
# A tibble: 4 × 3
  Diet    Biofeedback mean_BP
  <fct>   <fct>         <dbl>
1 Absent  Present        187 
2 Absent  Absent         199 
3 Present Present        171.
4 Present Absent         181.
HideShow
#> 187, 199, 171.33, 180.67 — matches book Table 8.13, p. 405

bp |> group_by(Diet, Drug) |> summarise(mean_BP = mean(BP), .groups = "drop")
HideShow
# A tibble: 6 × 3
  Diet    Drug  mean_BP
  <fct>   <fct>   <dbl>
1 Absent  X        178 
2 Absent  Y        202 
3 Absent  Z        199 
4 Present X        171 
5 Present Y        180.
6 Present Z        178.
HideShow
#> 178, 202, 199, 171, 179.5, 177.5 — matches book Table 8.13, p. 405

bp |> group_by(Diet) |> summarise(mean_BP = mean(BP), .groups = "drop")
HideShow
# A tibble: 2 × 2
  Diet    mean_BP
  <fct>     <dbl>
1 Absent      193
2 Present     176
HideShow
#> 193 and 176 — matches book Table 8.13, p. 405
The omnibus three-way ANOVA

The design is balanced, so Type I, Type II, and Type III sums of squares all agree and base R’s aov() reproduces the book’s omnibus table directly.

HideShow
# Three-way omnibus ANOVA (Table 8.14).
ANOVA_3Way <- aov(BP ~ Biofeedback * Drug * Diet, data = bp)
summary(ANOVA_3Way)
HideShow
                      Df Sum Sq Mean Sq F value   Pr(>F)    
Biofeedback            1   2048    2048  13.072 0.000615 ***
Drug                   2   3675    1837  11.729 5.02e-05 ***
Diet                   1   5202    5202  33.204 3.05e-07 ***
Biofeedback:Drug       2    259     129   0.827 0.442457    
Biofeedback:Diet       1     32      32   0.204 0.652937    
Drug:Diet              2    903     451   2.882 0.063815 .  
Biofeedback:Drug:Diet  2   1075     537   3.431 0.038834 *  
Residuals             60   9400     157                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> SS 2048, 3675, 5202, 259, 32, 903, 1075, 9400 and F 13.07, 11.73, 33.20,
#> 0.83, 0.20, 2.88, 3.43 — match book Table 8.14, p. 406. The book prints that
#> table's p column to two decimals, so its .440, .650, .060, and .040 are the
#> .4425, .6529, .0638, and .0388 computed here.

The same ANOVA as an APA-style table. We build it from broom::tidy() and format it with gt, adding partial η2\eta^2 for each effect alongside the sums of squares, dfdf, mean squares, FF, and pp:

HideShow
aov_tbl <- broom::tidy(ANOVA_3Way)
ss_res  <- aov_tbl$sumsq[aov_tbl$term == "Residuals"]   # error SS, for partial eta^2

aov_tbl |>
  transmute(
    Source = term, SS = sumsq, df = df, MS = meansq,
    Fstat  = statistic, p = p.value,
    # Partial eta-squared: each effect's SS over effect-plus-error SS.
    peta   = if_else(term == "Residuals", NA_real_, sumsq / (sumsq + ss_res))
  ) |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("**Table 8.14**. Three-Way Analysis of Variance for Blood Pressure")) |>
  cols_align(align = "center", columns = -Source)
Table 8.14. Three-Way Analysis of Variance for Blood Pressure
Source SS df MS F p Partial η2
Biofeedback 2,048.00 1 2,048.00 13.07 0.0006 0.179
Drug 3,675.00 2 1,837.50 11.73 0.0001 0.281
Diet 5,202.00 1 5,202.00 33.20 0.0000 0.356
Biofeedback:Drug 259.00 2 129.50 0.83 0.4425 0.027
Biofeedback:Diet 32.00 1 32.00 0.20 0.6529 0.003
Drug:Diet 903.00 2 451.50 2.88 0.0638 0.088
Biofeedback:Drug:Diet 1,075.00 2 537.50 3.43 0.0388 0.103
Residuals 9,400.00 60 156.67


HideShow
#> the SS, df, MS, F, and p columns match book Table 8.14, p. 406;
#> partial eta-squared is an addition, not part of the book's table
Each effect as a model comparison

Table 8.14 is a summary of seven model comparisons. Section 8.4.2 spells out the restricted model for each effect (Table 8.10, p. 401) and Table 8.11 (p. 404) gives the resulting sums of squares and degrees of freedom. Working the comparisons explicitly shows where each line of the ANOVA table comes from: SSeffect=ER−EFSS_{\text{effect}} = E_R - E_F, and

F=(ER−EF)/(dfR−dfF)EF/dfF. F = \frac{(E_R - E_F)/(df_R - df_F)}{E_F/df_F}.

Dropping a main effect from an R formula while its interactions remain leaves the model spanning the same space, so update() and anova() would report a comparison with zero degrees of freedom. We therefore build each restricted model from the full design matrix, deleting the columns that belong to the effect being tested. Sum-to-zero coding makes those columns exactly the parameters the book sets to zero in Table 8.10; in a balanced design the resulting sums of squares do not depend on the coding.

HideShow
# One design matrix for the full model, with sum-to-zero coding for all three factors.
X <- model.matrix(~ Biofeedback * Drug * Diet, data = bp,
                  contrasts.arg = list(Biofeedback = "contr.sum",
                                       Drug        = "contr.sum",
                                       Diet        = "contr.sum"))
effect_of_column <- attr(X, "assign")   # 0 = intercept, 1-7 = the seven omnibus effects
effect_names <- attr(terms(BP ~ Biofeedback * Drug * Diet), "term.labels")

# Error sum of squares for the model that keeps only the named columns.
error_ss <- function(cols) sum(lm.fit(x = X[, cols, drop = FALSE], y = bp$BP)$residuals^2)

all_columns <- seq_len(ncol(X))
E_F  <- error_ss(all_columns)
df_F <- nrow(X) - ncol(X)

map_dfr(seq_along(effect_names), function(j) {
  dropped <- which(effect_of_column == j)
  E_R     <- error_ss(setdiff(all_columns, dropped))
  df_diff <- length(dropped)
  F_stat  <- ((E_R - E_F) / df_diff) / (E_F / df_F)
  tibble(Effect = effect_names[j],
         E_R = E_R, E_F = E_F, SS = E_R - E_F, df = df_diff,
         F_stat = F_stat,
         p = pf(F_stat, df_diff, df_F, lower.tail = FALSE))
})
HideShow
# A tibble: 7 × 7
  Effect                   E_R   E_F     SS    df F_stat           p
  <chr>                  <dbl> <dbl>  <dbl> <int>  <dbl>       <dbl>
1 Biofeedback           11448   9400 2048.      1 13.1   0.000615   
2 Drug                  13075   9400 3675.      2 11.7   0.0000502  
3 Diet                  14602   9400 5202.      1 33.2   0.000000305
4 Biofeedback:Drug       9659   9400  259.      2  0.827 0.442      
5 Biofeedback:Diet       9432   9400   32.0     1  0.204 0.653      
6 Drug:Diet             10303   9400  903.      2  2.88  0.0638     
7 Biofeedback:Drug:Diet 10475.  9400 1075.      2  3.43  0.0388     
HideShow
#> E_F = 9400 with df_F = 60 is the within-cells line of Table 8.14; the SS column
#> reproduces 2048, 3675, 5202, 259, 32, 903, 1075 and the F column 13.07, 11.73,
#> 33.20, 0.83, 0.20, 2.88, 3.43 — matches book Table 8.14, p. 406
In DMAR

The DMAR package assembles the same table from a formula and adds, for every effect, partial η2\eta^2 and partial ω̂2\hat\omega^2 with noncentral-FF confidence intervals — quantities aov() does not report.

HideShow
DMAR::factorial_anova(BP ~ Biofeedback * Drug * Diet, data = bp, ss_type = 3L)
effect SS df F_value p_value eta_squared_partial eta_squared_partial_ci_lower eta_squared_partial_ci_upper omega_squared_partial omega_squared_partial_ci_lower omega_squared_partial_ci_upper
Biofeedback 2048.000 1 13.072 0.0006 0.179 0.032 0.308 0.144 0.032 0.308
Drug 3675.000 2 11.729 < 0.0001 0.281 0.082 0.397 0.230 0.082 0.397
Diet 5202.000 1 33.204 < 0.0001 0.356 0.148 0.468 0.309 0.148 0.468
Biofeedback:Drug 259.000 2 0.827 0.4425 0.027 0.000 0.111 0.000 0.000 0.111
Biofeedback:Diet 32.000 1 0.204 0.6529 0.003 0.000 0.072 0.000 0.000 0.072
Drug:Diet 903.000 2 2.882 0.0638 0.088 0.000 0.200 0.050 0.000 0.200
Biofeedback:Drug:Diet 1075.000 2 3.431 0.0388 0.103 0.000 0.218 0.063 0.000 0.218
Residuals 9400.000 60 NA NA NA NA NA NA NA NA

Sum of squares: Type III

Confidence level: 95%

HideShow
#> SS 2048, 3675, 5202, 259, 32, 903, 1075, 9400 and F 13.07, 11.73, 33.20, 0.83,
#> 0.20, 2.88, 3.43 — the same values as aov() above and as book Table 8.14, p. 406.
#> Type III equals Type I here because the design is balanced.

8.5.1 — Implications of a Three-Way Interaction

All three main effects are highly statistically significant. None of the two-way interactions reaches the .05 level, although Drug ×\times Diet just misses it, and the three-way Biofeedback ×\times Drug ×\times Diet interaction is statistically significant.

The book supplements these tests with partial ω̂2\hat\omega^2 for each effect (Equation 7.46), treating the “off factors” as extrinsic.

HideShow
# Partial omega-squared for each effect (Table 8.15).
effectsize::omega_squared(ANOVA_3Way, partial = TRUE)
HideShow
# Effect Size for ANOVA (Type I)

Parameter             | Omega2 (partial) |       95% CI
-------------------------------------------------------
Biofeedback           |             0.14 | [0.03, 1.00]
Drug                  |             0.23 | [0.08, 1.00]
Diet                  |             0.31 | [0.16, 1.00]
Biofeedback:Drug      |             0.00 | [0.00, 1.00]
Biofeedback:Diet      |             0.00 | [0.00, 1.00]
Drug:Diet             |             0.05 | [0.00, 1.00]
Biofeedback:Drug:Diet |             0.06 | [0.00, 1.00]

- One-sided CIs: upper bound fixed at [1.00].
HideShow
#> A .14, B .23, C .31, AB .00, AC .00, BC .05, ABC .06 — matches book Table 8.15,
#> p. 407. The A x B and A x C values are set to zero because their F values are
#> below 1, exactly as the book notes.

A statistically significant three-way interaction means lower-order effects should not be interpreted in isolation: the two-way interactions, and the main effects, are not consistent across levels of the third factor. Judging the “best” drug from its marginal means is misleading here, because the drug’s effectiveness depends on the particular combination of diet and biofeedback. The decomposition in Section 8.5.2 replaces those average effects with conditional ones.

In DMAR

DMAR returns the same per-effect partial ω̂2\hat\omega^2 from a call that takes a fitted model directly, and ci_omega_squared() attaches a noncentral-FF confidence interval to each one. We first build a parallel lm() fit of the same three-way model; the numbers are identical to the aov() fit above.

HideShow
fit_full <- lm(BP ~ Biofeedback * Drug * Diet, data = bp)

DMAR::omega_squared(fit_full, estimand = "partial")
effect omega_squared_partial F_value df_effect df_error N
Biofeedback 0.144 13.072 1 60 72
Drug 0.230 11.729 2 60 72
Diet 0.309 33.204 1 60 72
Biofeedback:Drug 0.000 0.827 2 60 72
Biofeedback:Diet 0.000 0.204 1 60 72
Drug:Diet 0.050 2.882 2 60 72
Biofeedback:Drug:Diet 0.063 3.431 2 60 72

Sum of squares: Type III

HideShow
#> .144, .230, .309, .000, .000, .050, .063 — the same values as
#> effectsize::omega_squared() above, and they match book Table 8.15, p. 407

DMAR::ci_omega_squared(fit_full, estimand = "partial", conf_level = 0.95)
effect omega_squared_partial omega_squared_partial_ci_lower omega_squared_partial_ci_upper F_value df_effect df_error N
Biofeedback 0.144 0.032 0.308 13.072 1 60 72
Drug 0.230 0.082 0.397 11.729 2 60 72
Diet 0.309 0.148 0.468 33.204 1 60 72
Biofeedback:Drug 0.000 0.000 0.111 0.827 2 60 72
Biofeedback:Diet 0.000 0.000 0.072 0.204 1 60 72
Drug:Diet 0.050 0.000 0.200 2.882 2 60 72
Biofeedback:Drug:Diet 0.063 0.000 0.218 3.431 2 60 72

Sum of squares: Type III

Confidence level: 95%

HideShow
#> point estimates again match book Table 8.15, p. 407; the confidence intervals
#> are an addition — the book reports the point estimates only

Like the book, DMAR clamps a negative estimate to zero, which is what happens whenever F<1F < 1.

The cell-means model in regression form

The lm() fit is the same model written as a regression, where each coefficient is a deviation from the reference cell (biofeedback present, Drug X, diet absent). A modelsummary table lays out the estimates with standard errors beneath them:

HideShow
modelsummary(
  list("Three-way factorial" = fit_full),
  estimate  = "{estimate}",
  statistic = "({std.error})",   # standard errors in parentheses, APA style
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  output    = "gt"               # gt backend, to match the gtsummary table below
)
Three-way factorial
(Intercept) 168.000
(5.110)
BiofeedbackAbsent 20.000
(7.226)
DrugY 36.000
(7.226)
DrugZ 21.000
(7.226)
DietPresent 1.000
(7.226)
BiofeedbackAbsent × DrugY -24.000
(10.220)
BiofeedbackAbsent × DrugZ 0.000
(10.220)
BiofeedbackAbsent × DietPresent -16.000
(10.220)
DrugY × DietPresent -33.000
(10.220)
DrugZ × DietPresent -17.000
(10.220)
BiofeedbackAbsent × DrugY × DietPresent 35.000
(14.453)
BiofeedbackAbsent × DrugZ × DietPresent 5.000
(14.453)
Num.Obs. 72
AIC 581.1
BIC 610.7
Log.Lik. -277.548
HideShow
#> the intercept is the Biofeedback present / Drug X / Diet absent cell mean of
#> 168 — matches book Table 8.13, p. 405

The same fit as a gtsummary tbl_regression() table, with the 95% confidence interval for each coefficient:

HideShow
tbl_regression(fit_full, intercept = TRUE)
Characteristic Beta 95% CI p-value
(Intercept) 168 158, 178 <0.001
Biofeedback


    Present — —
    Absent 20 5.5, 34 0.007
Drug


    X — —
    Y 36 22, 50 <0.001
    Z 21 6.5, 35 0.005
Diet


    Absent — —
    Present 1.0 -13, 15 0.9
Biofeedback * Drug


    Absent * Y -24 -44, -3.6 0.022
    Absent * Z 0.00 -20, 20 >0.9
Biofeedback * Diet


    Absent * Present -16 -36, 4.4 0.12
Drug * Diet


    Y * Present -33 -53, -13 0.002
    Z * Present -17 -37, 3.4 0.10
Biofeedback * Drug * Diet


    Absent * Y * Present 35 6.1, 64 0.018
    Absent * Z * Present 5.0 -24, 34 0.7
Abbreviation: CI = Confidence Interval

8.5.2 — General Guideline for Analyzing Effects

Figure 8.6 (p. 409) gives a flowchart for analyzing a three-factor design. Since the three-way interaction is statistically significant, the first branch asks whether the Biofeedback ×\times Drug interaction is significant at each level of diet.

The obvious way to answer that question is to split the data by diet and run two separate two-way ANOVAs, but then the error term comes from only the 30 degrees of freedom inside that half of the design. The book instead uses the pooled MSWMS_W from the full three-way model, on 60 degrees of freedom, under the assumption of homogeneity of variance across all twelve cells; p. 410 sets out the choice between the two error terms explicitly. emmeans::joint_tests() carries the full model’s error term into every simple effect, which is what makes it reproduce the book’s tables.

HideShow
# Simple interaction tests: Biofeedback x Drug at each level of Diet (Table 8.16).
# These use the pooled error term (MS_W = 156.7, df = 60) from ANOVA_3Way.
joint_tests(ANOVA_3Way, by = "Diet")
HideShow
Diet = Absent:
 model term       df1 df2 F.ratio p.value
 Biofeedback        1  60   8.272  0.0056
 Drug               2  60  13.098 <0.0001
 Biofeedback:Drug   2  60   3.677  0.0312

Diet = Present:
 model term       df1 df2 F.ratio p.value
 Biofeedback        1  60   5.004  0.0290
 Drug               2  60   1.513  0.2286
 Biofeedback:Drug   2  60   0.581  0.5625
HideShow
#> Biofeedback:Drug F = 3.677 when diet is absent and 0.581 when diet is present
#> — matches book Table 8.16, p. 411 (F = 3.68, p = .03; F = 0.58, p = .56)

The Biofeedback ×\times Drug interaction is significant when diet is absent (p=.0312p = .0312) but not when diet is present (p=.5625p = .5625). That contrast is what the significant three-way interaction was pointing at, and it means the follow-up analysis must take a different path for each diet condition.

Path 1: diet absent (significant simple interaction). Because biofeedback and drug interact when diet is absent, the next step is simple, simple main effects: the biofeedback effect at each level of drug, and the drug effect at each level of biofeedback, with diet held at absent (Table 8.17).

HideShow
# Simple, simple main effects of Biofeedback within each Drug (diet absent).
joint_tests(ANOVA_3Way, by = c("Diet", "Drug")) |>
  filter(Diet == "Absent")
HideShow
Diet = Absent, Drug = X:
 model term  df1 df2 F.ratio p.value
 Biofeedback   1  60   7.660  0.0075

Diet = Absent, Drug = Y:
 model term  df1 df2 F.ratio p.value
 Biofeedback   1  60   0.306  0.5820

Diet = Absent, Drug = Z:
 model term  df1 df2 F.ratio p.value
 Biofeedback   1  60   7.660  0.0075
HideShow
#> F = 7.660 for Drug X, 0.306 for Drug Y, 7.660 for Drug Z — matches book
#> Table 8.17, p. 411 (7.66, 0.31, 7.66; p = .007, .582, .007)

# Simple, simple main effects of Drug within each Biofeedback level (diet absent).
joint_tests(ANOVA_3Way, by = c("Diet", "Biofeedback")) |>
  filter(Diet == "Absent")
HideShow
Diet = Absent, Biofeedback = Present:
 model term df1 df2 F.ratio p.value
 Drug         2  60  12.523 <0.0001

Diet = Absent, Biofeedback = Absent:
 model term df1 df2 F.ratio p.value
 Drug         2  60   4.251  0.0188
HideShow
#> F = 12.523 with biofeedback present and 4.251 with biofeedback absent —
#> matches book Table 8.17, p. 411 (12.52, p < .001; 4.25, p = .019)

When diet is absent, drug matters whether or not biofeedback is present, but biofeedback matters only for patients on Drug X or Drug Z.

Biofeedback has only two levels, so no further comparison is needed once its simple, simple main effect is significant. Drug has three levels, so the book compares individual cell means within each biofeedback condition, defining a family as one combination of biofeedback and diet and using Tukey’s HSD to hold αFW\alpha_{FW} at .05 (Table 8.18).

HideShow
# Pairwise comparisons of drugs within each Biofeedback x Diet combination.
drug_comparisons <- emmeans(ANOVA_3Way, specs = pairwise ~ Drug | Biofeedback * Diet)

drug_comparisons$contrasts |>
  as.data.frame() |>
  filter(Diet == "Absent") |>
  mutate(F_equivalent = t.ratio^2)   # for a 1-df test, F = t^2
HideShow
  contrast Biofeedback   Diet estimate       SE df   t.ratio      p.value
1    X - Y     Present Absent      -36 7.226494 60 -4.981669 1.672017e-05
2    X - Z     Present Absent      -21 7.226494 60 -2.905973 1.398245e-02
3    Y - Z     Present Absent       15 7.226494 60  2.075695 1.035313e-01
4    X - Y      Absent Absent      -12 7.226494 60 -1.660556 2.287808e-01
5    X - Z      Absent Absent      -21 7.226494 60 -2.905973 1.398245e-02
6    Y - Z      Absent Absent       -9 7.226494 60 -1.245417 4.314940e-01
  F_equivalent
1    24.817021
2     8.444681
3     4.308511
4     2.757447
5     8.444681
6     1.551064
HideShow
#> F_equivalent 24.82, 8.44, 4.31 (biofeedback present) and 2.76, 8.44, 1.55
#> (biofeedback absent) — matches book Table 8.18, p. 412

The book’s decision rule for this family is that an observed FF must exceed q2/2=5.78q^2/2 = 5.78, where q=3.40q = 3.40 is the critical studentized range for α=.05\alpha = .05, df=60df = 60, and three means (p. 411). We can check that critical value directly, and emmeans applies the equivalent Tukey adjustment to the pp values:

HideShow
q_crit <- qtukey(p = 0.95, nmeans = 3, df = 60)
c(q = q_crit, F_criterion = q_crit^2 / 2)
HideShow
          q F_criterion 
   3.398661    5.775449 
HideShow
#> q = 3.40 and the F criterion 5.78 — matches book p. 411

Three of the six comparisons clear that criterion: when diet is absent, Drug X differs from Drug Y and from Drug Z with biofeedback present, and Drug X differs from Drug Z with biofeedback absent.

Path 2: diet present (non-significant simple interaction). Because biofeedback and drug do not interact when diet is present, their effects within that diet condition can be read from simple main effects — biofeedback averaging over drug, and drug averaging over biofeedback (Table 8.19).

HideShow
joint_tests(ANOVA_3Way, by = "Diet") |>
  filter(Diet == "Present")
HideShow
Diet = Present:
 model term       df1 df2 F.ratio p.value
 Biofeedback        1  60   5.004  0.0290
 Drug               2  60   1.513  0.2286
 Biofeedback:Drug   2  60   0.581  0.5625
HideShow
#> Biofeedback F = 5.004, p = .0290 and Drug F = 1.513, p = .2286 — matches book
#> Table 8.19, p. 412 (F = 5.00, p = .029; F = 1.51, p = .229)

Drug has no statistically significant effect when diet is present. Biofeedback does, and because biofeedback has only two levels, the marginal means (171.33 with biofeedback, 180.67 without) tell the whole story.

In DMAR

DMAR’s simple_effects_AB() reports a whole family of simple main effects for a two-factor fit — both A-within-B and B-within-A — together with partial η2\eta^2 and its confidence interval for every row, which joint_tests() does not give. It takes a two-factor model, so we fit Biofeedback * Drug separately within each diet condition.

An important consequence: each fit pools error only within its own half of the design, so these tests use MSWMS_W on 30 degrees of freedom rather than the 60 of the full model. That is the other error term the book explicitly raises on p. 410 — the one appropriate if heterogeneity of variance across levels of C is suspected — so the FF values below are deliberately not the ones in Table 8.17, even though the pattern of results is the same.

HideShow
fit_diet_absent  <- lm(BP ~ Biofeedback * Drug, data = filter(bp, Diet == "Absent"))
fit_diet_present <- lm(BP ~ Biofeedback * Drug, data = filter(bp, Diet == "Present"))

# Diet absent: both families of simple main effects, on the subset's own error term.
DMAR::simple_effects_AB(fit_diet_absent)
effect focal_factor conditioning_factor conditioning_level F_value df_effect df_error p_value p_adjusted eta_squared_partial ci_lower ci_upper n_at_level
Biofeedback | Drug = X Biofeedback Drug X 8.785 1 30 0.0059 0.0059 0.227 0.019 0.414 12
Biofeedback | Drug = Y Biofeedback Drug Y 0.351 1 30 0.5578 0.5578 0.012 0.000 0.152 12
Biofeedback | Drug = Z Biofeedback Drug Z 8.785 1 30 0.0059 0.0059 0.227 0.019 0.414 12
Drug | Biofeedback = Present Drug Biofeedback Present 14.363 2 30 < 0.0001 < 0.0001 0.489 0.180 0.618 18
Drug | Biofeedback = Absent Drug Biofeedback Absent 4.876 2 30 0.0147 0.0147 0.245 0.010 0.419 18

Confidence level: 95%

Pooled-error partial eta squared with a noncentral-F interval.

HideShow
#> df_error = 30, not the 60 of book Table 8.17, so the F values are larger
#> (8.785, 0.351, 8.785, 14.363, 4.876). The pattern is the book's: biofeedback
#> matters within Drug X and Drug Z but not Drug Y, and drug matters within both
#> biofeedback conditions.

# Diet present: the same family, where nothing reaches significance.
DMAR::simple_effects_AB(fit_diet_present)
effect focal_factor conditioning_factor conditioning_level F_value df_effect df_error p_value p_adjusted eta_squared_partial ci_lower ci_upper n_at_level
Biofeedback | Drug = X Biofeedback Drug X 0.272 1 30 0.6061 0.6061 0.009 0.000 0.144 12
Biofeedback | Drug = Y Biofeedback Drug Y 3.819 1 30 0.0600 0.0600 0.113 0.000 0.303 12
Biofeedback | Drug = Z Biofeedback Drug Z 1.375 1 30 0.2502 0.2502 0.044 0.000 0.216 12
Drug | Biofeedback = Present Drug Biofeedback Present 0.147 2 30 0.8638 0.8638 0.010 0.000 0.092 18
Drug | Biofeedback = Absent Drug Biofeedback Absent 1.709 2 30 0.1982 0.1982 0.102 0.000 0.271 18

Confidence level: 95%

Pooled-error partial eta squared with a noncentral-F interval.

Comparing the two sets makes the decomposition concrete: when diet is absent the biofeedback effect is large within Drug X and Drug Z and negligible within Drug Y, and drug differences are large within each biofeedback level; when diet is present none of these simple effects is significant. That difference between the two diet conditions is the structural pattern driving the significant three-way interaction.

8.5.3 — Summary of Results

Table 8.20 repeats the Table 8.13 means and attaches superscripts marking which means within a row or a column differ. The pieces behind those superscripts are the cell means and marginal means already computed, assembled here in the layout the book uses.

HideShow
# Cell means, diet absent (the top panel of Table 8.20).
bp |>
  filter(Diet == "Absent") |>
  group_by(Biofeedback, Drug) |>
  summarise(Mean = mean(BP), .groups = "drop") |>
  pivot_wider(names_from = Drug, values_from = Mean)
HideShow
# A tibble: 2 × 4
  Biofeedback     X     Y     Z
  <fct>       <dbl> <dbl> <dbl>
1 Present       168   204   189
2 Absent        188   200   209
HideShow
#> 168, 204, 189 / 188, 200, 209 — matches book Table 8.20, p. 413

# Cell means, diet present (the bottom panel).
bp |>
  filter(Diet == "Present") |>
  group_by(Biofeedback, Drug) |>
  summarise(Mean = mean(BP), .groups = "drop") |>
  pivot_wider(names_from = Drug, values_from = Mean)
HideShow
# A tibble: 2 × 4
  Biofeedback     X     Y     Z
  <fct>       <dbl> <dbl> <dbl>
1 Present       169   172   173
2 Absent        173   187   182
HideShow
#> 169, 172, 173 / 173, 187, 182 — matches book Table 8.20, p. 413

# The marginal means that carry the superscripts when diet is present.
emmeans(ANOVA_3Way, ~ Biofeedback | Diet) |>
  as.data.frame() |>
  dplyr::select(Diet, Biofeedback, emmean)
HideShow
     Diet Biofeedback   emmean
1  Absent     Present 187.0000
2  Absent      Absent 199.0000
3 Present     Present 171.3333
4 Present      Absent 180.6667
HideShow
#> 187, 199 (diet absent) and 171.33, 180.67 (diet present) — matches book
#> Table 8.20, p. 413

emmeans(ANOVA_3Way, ~ Drug | Diet) |>
  as.data.frame() |>
  dplyr::select(Diet, Drug, emmean)
HideShow
     Diet Drug emmean
1  Absent    X  178.0
2  Absent    Y  202.0
3  Absent    Z  199.0
4 Present    X  171.0
5 Present    Y  179.5
6 Present    Z  177.5
HideShow
#> 178, 202, 199 (diet absent) and 171, 179.5, 177.5 (diet present) — matches
#> book Table 8.20, p. 413

The cell means show what the tests found. When diet is absent, adding biofeedback drops blood pressure substantially for patients on Drug X (188 to 168) and Drug Z (209 to 189) but does little for patients on Drug Y (200 to 204). The marginal means mask that pattern, which is why the superscripts in the diet-absent half of Table 8.20 sit on cell means rather than on marginal means.

8.5.4 — Graphical Depiction of Data

Plotting the cell means (Figure 8.7) is often the most direct way to see a three-way interaction: the shape of the two-way interaction changes across the levels of the third factor.

HideShow
cell_means <- bp |>
  group_by(Diet, Biofeedback, Drug) |>
  summarise(mean_BP = mean(BP), .groups = "drop")

ggplot(cell_means, aes(Drug, mean_BP, group = Biofeedback, color = Biofeedback)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  facet_wrap(~ Diet, labeller = labeller(
    Diet = c(Absent = "(a) Diet absent", Present = "(b) Diet present"))) +
  scale_color_brewer(palette = "Dark2") +
  scale_y_continuous(limits = c(165, 210), breaks = seq(165, 210, by = 5)) +
  labs(title = "Figure 8.7. Cell means by diet condition (numerical example)",
       x = "Drug", y = "Sample mean blood pressure", color = "Biofeedback") +
  theme(legend.position = "top")
Figure 8.7. Plot of the Table 8.13 cell means as a function of diet condition: (a) diet absent and (b) diet present.

Figure 8.7. Plot of the Table 8.13 cell means as a function of diet condition: (a) diet absent and (b) diet present.

The two panels look very different. When diet is absent the lines cross — a strong Biofeedback ×\times Drug interaction. When diet is present they are nearly parallel: biofeedback lowers blood pressure, but the drugs do not differ from one another. That the left panel looks so unlike the right panel is the three-way interaction, and it agrees with the FF tests of Table 8.16.

8.5.5 — Confidence Intervals for Single Degree of Freedom Effects

Rather than stopping at pp values, we can form confidence intervals for single-degree-of-freedom effects. For the biofeedback effect within Drug X when diet is absent, the standard error uses the pooled MSW=156.7MS_W = 156.7 on 60 degrees of freedom and the n=6n = 6 of the two cells being compared, so from Table 5.17 the interval is

(168−188)±4.00156.7(16+16). (168 - 188) \pm \sqrt{4.00}\,\sqrt{156.7\left(\tfrac{1}{6} + \tfrac{1}{6}\right)}.

HideShow
# 95% CIs for the biofeedback effect within each Drug (diet absent).
biofeedback_by_drug <- emmeans(ANOVA_3Way, specs = pairwise ~ Biofeedback | Drug * Diet)

confint(biofeedback_by_drug$contrasts) |>
  as.data.frame() |>
  filter(Diet == "Absent")
HideShow
Drug = X, Diet = Absent:
 contrast         estimate       SE df  lower.CL  upper.CL
 Present - Absent      -20 7.226494 60 -34.45514 -5.544859

Drug = Y, Diet = Absent:
 contrast         estimate       SE df  lower.CL  upper.CL
 Present - Absent        4 7.226494 60 -10.45514 18.455141

Drug = Z, Diet = Absent:
 contrast         estimate       SE df  lower.CL  upper.CL
 Present - Absent      -20 7.226494 60 -34.45514 -5.544859

Confidence level used: 0.95 
HideShow
#> Drug X: estimate -20.00, 95% CI [-34.46, -5.54] — matches the limits the book
#> quotes from Table 8.21 on p. 416. The Drug Y (+4.00) and Drug Z (-20.00) rows
#> are the other two intervals of Table 8.21; the book shows them in the table
#> but does not quote their limits in the text.

The interval for Drug X is centered on 168−188=−20168 - 188 = -20, the difference between the two cell means in Table 8.13, and it excludes zero, consistent with the p<.05p < .05 for that effect in Table 8.17.

The last line of Table 8.21 is the biofeedback effect when diet is present. It is not reported drug by drug, because biofeedback and drug do not interact there, so it averages over drug and is based on 18 observations per mean rather than 6:

(171.33−180.67)±4.00156.7(118+118). (171.33 - 180.67) \pm \sqrt{4.00}\,\sqrt{156.7\left(\tfrac{1}{18} + \tfrac{1}{18}\right)}.

HideShow
biofeedback_marginal <- emmeans(ANOVA_3Way, specs = pairwise ~ Biofeedback | Diet)

confint(biofeedback_marginal$contrasts) |>
  as.data.frame() |>
  filter(Diet == "Present")
HideShow
Diet = Present:
 contrast          estimate       SE df  lower.CL   upper.CL
 Present - Absent -9.333333 4.172219 60 -17.67901 -0.9876537

Results are averaged over the levels of: Drug 
Confidence level used: 0.95 
HideShow
#> estimate -9.33 = 171.33 - 180.67 — matches book p. 416; the limits reproduce
#> the p. 416 formula above

# The same interval, worked straight from the book's expression on p. 416.
-9.333333 + c(-1, 1) * sqrt(4.00) * sqrt((9400 / 60) * (1/18 + 1/18))
HideShow
[1] -17.677770  -0.988896
HideShow
#> [-17.68, -0.99], the same limits confint() returns above; the book's sqrt(4.00)
#> is a rounded stand-in for t(.975, 60) = 2.0003, which is why it agrees "within
#> rounding error", exactly as the book says

This interval is much narrower than the three diet-absent intervals, because averaging over drug raises the effective sample size behind each mean from 6 to 18.

These are 95% intervals one at a time. To cover a family of effects, the width uses a multiple-comparison multiplier instead. Table 8.22 does this for the drug comparisons of Table 8.18, with a simultaneous 95% level under Tukey’s HSD:

HideShow
confint(drug_comparisons$contrasts) |>
  as.data.frame() |>
  filter(Diet == "Absent")
HideShow
Biofeedback = Present, Diet = Absent:
 contrast estimate       SE df  lower.CL  upper.CL
 X - Y         -36 7.226494 60 -53.36683 -18.63317
 X - Z         -21 7.226494 60 -38.36683  -3.63317
 Y - Z          15 7.226494 60  -2.36683  32.36683

Biofeedback = Absent, Diet = Absent:
 contrast estimate       SE df  lower.CL  upper.CL
 X - Y         -12 7.226494 60 -29.36683   5.36683
 X - Z         -21 7.226494 60 -38.36683  -3.63317
 Y - Z          -9 7.226494 60 -26.36683   8.36683

Confidence level used: 0.95 
Conf-level adjustment: tukey method for comparing a family of 3 estimates 
HideShow
#> X - Y with biofeedback present: -36.00, 95% simultaneous CI [-53.37, -18.63]
#> — matches book Table 8.22 and the limits quoted on p. 417

8.5.6 — Other Questions of Potential Interest

All three main effects are significant, so it is tempting to combine the best level of each: biofeedback present, Drug X, and diet present. Table 8.23 gives the marginal means for each main effect and their deviations from the grand mean, which are the estimated effect parameters.

HideShow
grand_mean <- mean(bp$BP)
grand_mean
HideShow
[1] 184.5
HideShow
#> 184.5 — matches book p. 417

marginal_means <- bind_rows(
  as.data.frame(emmeans(ANOVA_3Way, ~ Biofeedback)) |>
    transmute(Effect = paste("Biofeedback", tolower(Biofeedback)), emmean),
  as.data.frame(emmeans(ANOVA_3Way, ~ Drug)) |>
    transmute(Effect = paste("Drug", Drug), emmean),
  as.data.frame(emmeans(ANOVA_3Way, ~ Diet)) |>
    transmute(Effect = paste("Diet", tolower(Diet)), emmean)
) |>
  mutate(`Deviation from grand mean` = emmean - grand_mean)

marginal_means
HideShow
               Effect   emmean Deviation from grand mean
1 Biofeedback present 179.1667                 -5.333333
2  Biofeedback absent 189.8333                  5.333333
3              Drug X 174.5000                -10.000000
4              Drug Y 190.7500                  6.250000
5              Drug Z 188.2500                  3.750000
6         Diet absent 193.0000                  8.500000
7        Diet present 176.0000                 -8.500000
HideShow
#> 179.17, 189.83, 174.50, 190.75, 188.25, 193.00, 176.00 with deviations
#> -5.33, 5.33, -10.00, 6.25, 3.75, 8.50, -8.50 — matches book Table 8.23, p. 418

If the three therapies combined additively, the cell mean for biofeedback plus Drug X plus diet would be the grand mean plus the three main-effect parameters. Equation 8.9 (p. 418) says the actual cell mean also carries the three two-way interaction parameters and the three-way parameter. model.tables() extracts all of them from the fitted model.

HideShow
effects_table <- model.tables(ANOVA_3Way, type = "effects")

# Main-effect parameters for this particular combination.
alpha_1 <- as.numeric(effects_table$tables$Biofeedback["Present"])
beta_1  <- as.numeric(effects_table$tables$Drug["X"])
gamma_2 <- as.numeric(effects_table$tables$Diet["Present"])
c(alpha_1 = alpha_1, beta_1 = beta_1, gamma_2 = gamma_2)
HideShow
   alpha_1     beta_1    gamma_2 
 -5.333333 -10.000000  -8.500000 
HideShow
#> -5.33, -10.00, -8.50 — matches book p. 418

# What the cell mean would be if the three factors combined additively.
expected_BP <- grand_mean + alpha_1 + beta_1 + gamma_2
expected_BP
HideShow
[1] 160.6667
HideShow
#> 160.67 — matches book p. 417

# The interaction parameters for the same combination.
ab_11   <- effects_table$tables$`Biofeedback:Drug`["Present", "X"]
ac_12   <- effects_table$tables$`Biofeedback:Diet`["Present", "Present"]
bc_12   <- effects_table$tables$`Drug:Diet`["X", "Present"]
abc_112 <- effects_table$tables$`Biofeedback:Drug:Diet`["Present", "X", "Present"]
c(ab_11 = ab_11, ac_12 = ac_12, bc_12 = bc_12, abc_112 = abc_112)
HideShow
     ab_11      ac_12      bc_12    abc_112 
-0.6666667  0.6666667  5.0000000  3.3333333 
HideShow
#> -0.67, 0.67, 5.00, 3.33 — matches book p. 418

# Equation 8.9: the full model reproduces the observed cell mean exactly.
actual_BP <- expected_BP + ab_11 + ac_12 + bc_12 + abc_112
actual_BP
HideShow
[1] 169
HideShow
#> 169 — matches book p. 418, the observed mean for this cell in Table 8.13

Had the therapies combined additively, this group’s mean would have been 160.67. The observed mean is 169. Two parameters account for the whole of that 8.33-point gap, because the other two cancel: the Drug X ×\times diet combination is 5 points less effective than their separate effects imply — an antagonistic two-way interaction — and the three-way combination costs a further 3.33 points.

HideShow
# The lowest cell mean in the design, and the diet-present alternatives.
cell_means |> arrange(mean_BP) |> head(4)
HideShow
# A tibble: 4 × 4
  Diet    Biofeedback Drug  mean_BP
  <fct>   <fct>       <fct>   <dbl>
1 Absent  Present     X         168
2 Present Present     X         169
3 Present Present     Y         172
4 Present Present     Z         173
HideShow
#> 168 for biofeedback present / Drug X / diet absent is the lowest mean in the
#> design — matches book p. 418

Because of those interactions, the most effective combination in these data is biofeedback with Drug X and without the diet (mean 168), and combining the diet with Drug Y or Drug Z under biofeedback is only slightly higher. As the book cautions, a clinical choice would also weigh side effects, cost, and compliance; the statistical point is that treatments in combination can behave differently from what their separate effects suggest.

8.6 — Statistical Power

Power in a three-way design works exactly as in earlier chapters: it depends on α\alpha, the numerator and denominator degrees of freedom, and the noncentrality parameter of a noncentral FF. Equations 8.10–8.16 (p. 422) give one noncentrality parameter per omnibus effect, each of the form λeffect=Nfeffect2\lambda_{\text{effect}} = N f^2_{\text{effect}}, so seven effects can carry seven different power values. Equation 3.104 adds that E(F)≈1+λ/dfnumeratorE(F) \approx 1 + \lambda/df_{\text{numerator}}, which is why an effect with larger numerator dfdf tends to have lower power at the same λ\lambda.

The book works the details through end-of-chapter exercises rather than a numerical illustration, so what follows applies its formulas to this design rather than reproducing a printed value. Take the three-way interaction in this 2 ×\times 3 ×\times 2 design, with Cohen’s medium f=.25f = .25 (p. 423) and the study’s own N=72N = 72. Base R needs nothing beyond the FF distribution functions:

HideShow
N <- 72                     # total sample size, 6 per cell in 12 cells
f <- 0.25                   # Cohen's medium value of f (p. 423)
df_effect <- 2              # (a - 1)(b - 1)(c - 1) = 1 x 2 x 1
df_error  <- N - 2 * 3 * 2  # N - abc

lambda <- N * f^2           # Equation 8.16 / 8.19
lambda
HideShow
[1] 4.5
HideShow
#> 4.5

# Expected value of the F statistic, Equation 3.104 (p. 423).
1 + lambda / df_effect
HideShow
[1] 3.25
HideShow
#> 3.25

# Power: the chance of exceeding the central-F critical value when the
# noncentral F with this lambda is the true distribution.
F_crit <- qf(0.95, df1 = df_effect, df2 = df_error)
pf(F_crit, df1 = df_effect, df2 = df_error, ncp = lambda, lower.tail = FALSE)
HideShow
[1] 0.4408624
HideShow
#> 0.4409

So a medium three-way interaction would be detected only about 44% of the time at n=6n = 6 per cell — a concrete version of the chapter’s warning that three-way interactions are often the hardest effect in the design to detect.

In DMAR

ss_power_factorial_anova() does the same calculation from the design description rather than from degrees of freedom worked out by hand, and it will also solve for the nn per cell that reaches a target power — which the base R call does not do.

HideShow
# Power at the design actually used: n = 6 per cell.
DMAR::ss_power_factorial_anova(
  factor_levels        = c(2, 3, 2),   # biofeedback, drug, diet
  effect_indices       = c(1, 2, 3),   # the three-way interaction
  true_f               = 0.25,
  alpha_level          = 0.05,
  specified_n_per_cell = 6
)
term value
specified_n_per_cell 6
total_N 72
df_effect 2
df_error 60
noncentral_f_parm 4.500
actual_power 0.441
HideShow
#> noncentral_f_parm 4.500 and power 0.441 — the same lambda and power as the
#> base R calculation above

# The n per cell needed for .80 power on that same interaction.
DMAR::ss_power_factorial_anova(
  factor_levels  = c(2, 3, 2),
  effect_indices = c(1, 2, 3),
  true_f         = 0.25,
  desired_power  = 0.80,
  alpha_level    = 0.05
)
term value
necessary_n_per_cell 14
total_N 168
df_effect 2
df_error 156
noncentral_f_parm 10.500
actual_power 0.827

8.7 — Designs with More Than Three Factors

The logic of the chapter extends to any number of factors. Two counting results are useful: a completely crossed design with FF factors has 2F−12^F - 1 omnibus effects, and the number of effects of order RR is F!/[(R+1)!(F−R−1)!]F!/[(R+1)!\,(F-R-1)!] (Equation 8.21, p. 424). That second expression is just a binomial coefficient, so choose() evaluates it directly.

HideShow
# Table 8.24: number of effects of each order in a completely crossed design.
tibble(Factors = 2:5) |>
  mutate(
    `Main effects`     = choose(Factors, 1),
    `Two-way`          = choose(Factors, 2),
    `Three-way`        = choose(Factors, 3),
    `Four-way`         = choose(Factors, 4),
    `Five-way`         = choose(Factors, 5),
    `Total omnibus effects` = 2^Factors - 1
  ) |>
  gt() |>
  tab_spanner(label = "Interactions",
              columns = c(`Two-way`, `Three-way`, `Four-way`, `Five-way`)) |>
  tab_header(title = md("**Table 8.24**. Number of Effects of Each Order in a Completely Crossed Factorial Design")) |>
  cols_align(align = "center")
Table 8.24. Number of Effects of Each Order in a Completely Crossed Factorial Design
Factors Main effects
Interactions
Total omnibus effects
Two-way Three-way Four-way Five-way
2 2 1 0 0 0 3
3 3 3 1 0 0 7
4 4 6 4 1 0 15
5 5 10 10 5 1 31
HideShow
#> 2 factors: 2, 1, total 3; 3 factors: 3, 3, 1, total 7; 4 factors: 4, 6, 4, 1,
#> total 15; 5 factors: 5, 10, 10, 5, 1, total 31 — matches book Table 8.24,
#> p. 425 (the book prints a dash where this table prints 0)

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 8: Higher-Order Between-Subjects Factorial Designs (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

Chapter 9: Designs with Covariates: ANCOVA and Blocking

Open the separate reading

Code
Results
On this page

Chapter 9 takes up designs that include a concomitant variable, chiefly through the analysis of covariance (ANCOVA), which uses a covariate both to reduce error variance and to adjust the group means. The chapter develops the linear models behind ANCOVA and the assumptions they carry, and shows what a well-chosen covariate buys in power and precision — as well as what goes wrong when the covariate is measured with error or when the groups were not formed at random. It then weighs the alternatives for handling pre-existing differences: an ANOVA of residuals, gain scores, blocking, and propensity score matching. The chapter extension takes up what to do when the parallel-slopes assumption fails, developing the center of accuracy and the Johnson-Neyman regions of significance within which a treatment effect can be declared.

Chapter 1 explains how the AMCP package names the book’s data sets; this chapter uses chapter_9_table_1 (Table 9.1), chapter_9_table_7 (the Beck Depression data of Table 9.7), chapter_9_table_12 (the randomized block data of Table 9.12), chapter_9_extension_table_1 (Table 9E.1), and chapter_9_extension_figures_4_and_5 (the Pygmalion data behind Figures 9E.4 and 9E.5).

HideShow
# Load all of the packages used.
library(dplyr)          # data manipulation
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(car)            # Anova() for Type II/III tests and regression diagnostics
library(emmeans)        # estimated marginal means and contrasts
library(MatchIt)        # matching for observational designs
library(pwr)            # power analysis for common designs
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables
library(ggplot2)        # data figures
library(patchwork)      # arrange multi-panel ggplot figures

9.4 — ANCOVA

9.4.2 — Linear Models for ANCOVA

ANCOVA represents a shift in our linear models, moving from using only discrete dummy variables to including continuous predictors. To test the main effect of our treatment while controlling for a covariate, we compare a Full model against a Restricted model:

  • Full Model: Yij=μ+αj+βXij+εijY_{ij} = \mu + \alpha_j + \beta X_{ij} + \varepsilon_{ij}

  • Restricted Model: Yij=μ+βXij+εijY_{ij} = \mu + \beta X_{ij} + \varepsilon_{ij}

Here, αj\alpha_j represents the group effect, and βXij\beta X_{ij} represents the regression slope of the covariate.

Let’s look at how this is executed in R using the hypothetical data from Table 9.1. The data come from the AMCP package, loaded above.

HideShow
data(chapter_9_table_1)
chapter_9_table_1
HideShow
  Group X  Y
1     1 1  4
2     1 2  9
3     1 3  8
4     2 3 12
5     2 4 11
6     2 5 16
HideShow
chapter_9_table_1$Group <- as.factor(chapter_9_table_1$Group)
str(chapter_9_table_1)
HideShow
'data.frame':   6 obs. of  3 variables:
 $ Group: Factor w/ 2 levels "1","2": 1 1 1 2 2 2
 $ X    : int  1 2 3 3 4 5
 $ Y    : int  4 9 8 12 11 16

First, we can partition the data to observe the relationship between the covariate (XX) and the dependent variable (YY) within each specific group. This helps us see the β\beta slope in action before we combine everything into a single ANCOVA model. Compare this output to Table 9.4 in the text.

HideShow
# Regressions separated by group
lm_1 <- lm(Y ~ X, data=chapter_9_table_1[chapter_9_table_1$Group=="1",])
lm_2 <- lm(Y ~ X, data=chapter_9_table_1[chapter_9_table_1$Group=="2",])

summary(lm_1)
HideShow

Call:
lm(formula = Y ~ X, data = chapter_9_table_1[chapter_9_table_1$Group == 
    "1", ])

Residuals:
 1  2  3 
-1  2 -1 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)    3.000      3.742   0.802    0.570
X              2.000      1.732   1.155    0.454

Residual standard error: 2.449 on 1 degrees of freedom
Multiple R-squared:  0.5714,    Adjusted R-squared:  0.1429 
F-statistic: 1.333 on 1 and 1 DF,  p-value: 0.4544
HideShow
summary(lm_2)
HideShow

Call:
lm(formula = Y ~ X, data = chapter_9_table_1[chapter_9_table_1$Group == 
    "2", ])

Residuals:
 4  5  6 
 1 -2  1 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)    5.000      7.071   0.707    0.608
X              2.000      1.732   1.155    0.454

Residual standard error: 2.449 on 1 degrees of freedom
Multiple R-squared:  0.5714,    Adjusted R-squared:  0.1429 
F-statistic: 1.333 on 1 and 1 DF,  p-value: 0.4544
HideShow
#> b_1 = 2, a_1 = 3 and b_2 = 2, a_2 = 5 — matches book p. 448 (Table 9.4).
#> Because the two separate slopes are both 2, the pooled within-group slope
#> b_W is also 2 (book p. 448, Equations 9.12 and 9.13).
9.4.2.1 — Parameter Estimates

In ANOVA, the restricted model makes the same prediction for every subject (the grand mean, represented by a flat horizontal line). In ANCOVA, the restricted model incorporates the covariate XX, allowing predictions to fall along a sloped regression line. This dramatically minimizes the error (the vertical distance from the data points to the line).

To find the “optimal” parameter estimates for these models, we use the least squares criterion. We can use R to recreate the manual calculations from Table 9.1 to find the error sum of squares for the restricted model (ERE_R) and the full model (EFE_F)

HideShow
# Re-verifying the error sum of squares (E_R and E_F) for the models from Table 9.1
# Restricted Model Error (ER)
Restricted.Model <- lm(Y ~ X, data=chapter_9_table_1)
E_R <- sum(resid(Restricted.Model)^2)
cat("Restricted Model Error Sum of Squares (ER):", E_R, "\n")
HideShow
Restricted Model Error Sum of Squares (ER): 14.4 
HideShow
#> E_R = 14.40 — matches book p. 446 (Table 9.3)

# The restricted model's intercept and slope themselves:
coef(Restricted.Model)
HideShow
(Intercept)           X 
        2.2         2.6 
HideShow
#> a = 2.2 and b_T = 2.6 — matches book p. 445 (Table 9.2, Equation 9.9)

# Full Model Error (EF)
# Note: The textbook calculates a pooled within-group slope (b_W = 2).
# The ANCOVA model fits this automatically.
Full.Model <- lm(Y ~ Group + X, data=chapter_9_table_1)
E_F <- sum(resid(Full.Model)^2)
cat("Full Model Error Sum of Squares (EF):", E_F, "\n")
HideShow
Full Model Error Sum of Squares (EF): 12 
HideShow
#> E_F = 12.0 — matches book p. 450 (Table 9.5), where the two models are
#> compared as "a value of E_F of 12.0 and a value of E_R of 14.4"

As shown in the output, the Restricted Model (which only uses the covariate XX to predict YY) leaves us with an Error Sum of Squares (ERE_R) of 14.4. When we add the Group parameter to create the Full Model, the Error Sum of Squares (EFE_F) drops to 12.0.

This means the addition of the Group effect only reduced our unexplained variance by 2.4 units. In general, we run formal FF-tests to determine if reductions in error like these are statistically significant.

Visualizing the Errors and Predictions (Figures 9.1 to 9.3)

The book’s Figures 9.1 (p. 443), 9.2 (p. 447), and 9.3 (p. 453) make this logic visible on exactly the same six points of Table 9.1. They contrast the errors and the predictions of the ANOVA and ANCOVA models. Because an ANCOVA prediction line is free to slope, it sits much closer to the data than the flat lines an ANOVA must use, so its errors are smaller. We first prepare the Table 9.1 data, the models used across all three figures, and the intercepts and slopes used to draw the lines.

HideShow
# The Table 9.1 data: six subjects, two groups, a covariate X and outcome Y.
# Build a separate, labeled copy so the chapter's chapter_9_table_1 is untouched.
d9 <- chapter_9_table_1 |>
  mutate(Group = case_when(
    Group == "1" ~ "Group 1",
    Group == "2" ~ "Group 2"
  )) |>
  mutate(Group = factor(Group, levels = c("Group 1", "Group 2")))

# Models used across Figures 9.1-9.3.
restricted_ancova <- lm(Y ~ X, data = d9)             # single regression line
full_ancova       <- lm(Y ~ Group + X, data = d9)     # parallel within-group lines
grand_mean_Y      <- mean(d9$Y)                        # = 10

# Fitted values and the group means used to draw the ANOVA lines.
d9 <- d9 |>
  group_by(Group) |>
  mutate(group_mean_Y = mean(Y)) |>
  ungroup() |>
  mutate(fit_restricted = predict(restricted_ancova),
         fit_full       = predict(full_ancova))

# Intercepts and slopes pulled once for the abline-style layers below.
a_restricted <- coef(restricted_ancova)[["(Intercept)"]]   # 2.2 — book p. 445
b_restricted <- coef(restricted_ancova)[["X"]]             # 2.6 — book p. 445
b_full       <- coef(full_ancova)[["X"]]                   # 2 (pooled b_W) — book p. 448
int_g1       <- coef(full_ancova)[["(Intercept)"]]         # a_1 = 3 — book p. 448
int_g2       <- int_g1 + coef(full_ancova)[["GroupGroup 2"]]   # a_2 = 5 — book p. 448

Figure 9.1. Errors in the restricted models. Both restricted models ignore group membership. The ANOVA restricted model predicts the grand mean for everyone, so its prediction is a flat line at Y‾=10\bar{Y} = 10 and the errors (the vertical segments) are large. The ANCOVA restricted model predicts along a single regression line, Ŷ=2.2+2.6X\hat{Y} = 2.2 + 2.6X, which sits much closer to the points, so the errors are far smaller. Circles mark Group 1 and triangles mark Group 2, but the models do not use that distinction.

HideShow
p9_1a <- ggplot(d9, aes(X, Y)) +
  geom_hline(yintercept = grand_mean_Y, color = "#F8766D",
             linewidth = 1) +
  geom_segment(aes(xend = X, yend = grand_mean_Y), color = "black",
               linewidth = 0.4, linetype = "dashed") +
  geom_point(aes(shape = Group), color = "black", size = 3) +
  scale_shape_manual(values = c("Group 1" = 16, "Group 2" = 17)) +
  scale_x_continuous(limits = c(0, 6), breaks = 0:6) +
  labs(subtitle = "(a) ANOVA restricted model: flat line at the grand mean",
       x = expression("Covariate" ~ (italic(X))),
       y = expression("Outcome" ~ (italic(Y))), shape = NULL) +
  theme(legend.position = "top")

p9_1b <- ggplot(d9, aes(X, Y)) +
  geom_abline(intercept = a_restricted, slope = b_restricted,
              color = "#F8766D", linewidth = 1) +
  geom_segment(aes(xend = X, yend = fit_restricted), color = "black",
               linewidth = 0.4, linetype = "dashed") +
  geom_point(aes(shape = Group), color = "black", size = 3) +
  scale_shape_manual(values = c("Group 1" = 16, "Group 2" = 17)) +
  scale_x_continuous(limits = c(0, 6), breaks = 0:6) +
  labs(subtitle = "(b) ANCOVA restricted model: single regression line",
       x = expression("Covariate" ~ (italic(X))),
       y = expression("Outcome" ~ (italic(Y))), shape = NULL) +
  theme(legend.position = "top")

(p9_1a | p9_1b) +
  plot_annotation(
    title = "Figure 9.1. Comparison of errors for data in Table 9.1 in (a) the ANOVA and (b) the ANCOVA restricted models",
    theme = theme(plot.title = element_text(color = "black",
                                            face = "bold", size = rel(1.0))))
Figure 9.1. Comparison of errors for data in Table 9.1 in (a) the ANOVA and (b) the ANCOVA restricted models.

Figure 9.1. Comparison of errors for data in Table 9.1 in (a) the ANOVA and (b) the ANCOVA restricted models.

Figure 9.2. Errors in the full models. The full models add a group effect. The ANOVA full model fits two flat lines, one at each group mean (7 for Group 1, 13 for Group 2). The ANCOVA full model fits two parallel sloped lines that share a single pooled slope of 2; tilting the lines lets them sit close to the data while staying parallel. As in Figure 9.1, the ANCOVA errors are smaller than the ANOVA errors.

HideShow
p9_2a <- ggplot(d9, aes(X, Y, color = Group)) +
  geom_segment(aes(x = min(X) - 0.3, xend = max(X) + 0.3,
                   y = group_mean_Y, yend = group_mean_Y), linewidth = 1) +
  geom_segment(aes(xend = X, yend = group_mean_Y), linewidth = 0.4,
               linetype = "dashed") +
  geom_point(aes(shape = Group), size = 3) +
  scale_color_manual(values = c("Group 1" = "#F8766D",
                                "Group 2" = "#00BFC4")) +
  scale_shape_manual(values = c("Group 1" = 16, "Group 2" = 17)) +
  scale_x_continuous(limits = c(0, 6), breaks = 0:6) +
  labs(subtitle = "(a) ANOVA full model: a flat line at each group mean",
       x = expression("Covariate" ~ (italic(X))),
       y = expression("Outcome" ~ (italic(Y))), color = NULL, shape = NULL) +
  theme(legend.position = "top")

p9_2b <- ggplot(d9, aes(X, Y, color = Group)) +
  geom_abline(intercept = int_g1, slope = b_full,
              color = "#F8766D", linewidth = 1) +
  geom_abline(intercept = int_g2, slope = b_full,
              color = "#00BFC4", linewidth = 1) +
  geom_segment(aes(xend = X, yend = fit_full), linewidth = 0.4,
               linetype = "dashed") +
  geom_point(aes(shape = Group), size = 3) +
  scale_color_manual(values = c("Group 1" = "#F8766D",
                                "Group 2" = "#00BFC4")) +
  scale_shape_manual(values = c("Group 1" = 16, "Group 2" = 17)) +
  scale_x_continuous(limits = c(0, 6), breaks = 0:6) +
  labs(subtitle = "(b) ANCOVA full model: two parallel sloped lines",
       x = expression("Covariate" ~ (italic(X))),
       y = expression("Outcome" ~ (italic(Y))), color = NULL, shape = NULL) +
  theme(legend.position = "top")

(p9_2a | p9_2b) +
  plot_annotation(
    title = "Figure 9.2. Comparison of errors for data in Table 9.1 in (a) the ANOVA and (b) the ANCOVA full models",
    theme = theme(plot.title = element_text(color = "black",
                                            face = "bold", size = rel(1.0))))
Figure 9.2. Comparison of errors for data in Table 9.1 in (a) the ANOVA and (b) the ANCOVA full models.

Figure 9.2. Comparison of errors for data in Table 9.1 in (a) the ANOVA and (b) the ANCOVA full models.

Figure 9.3. Full-model minus restricted-model predictions. The sum of squares for the group effect grows with how far the full-model predictions (the solid lines) depart from the restricted-model prediction (the dashed line). For the ANOVA, the two group-mean lines sit far above and below the grand-mean line, so the effect is large. For the ANCOVA, the steep regression draws the two parallel full-model lines in close to the single restricted line, so the same group effect shrinks. This is why ANCOVA adjusts the magnitude of the group effect, not just its error term.

HideShow
p9_3a <- ggplot(d9, aes(X, Y, color = Group)) +
  geom_hline(yintercept = grand_mean_Y, color = "gray40",
             linewidth = 0.9, linetype = "dashed") +
  geom_segment(aes(x = min(X) - 0.3, xend = max(X) + 0.3,
                   y = group_mean_Y, yend = group_mean_Y), linewidth = 1) +
  geom_point(aes(shape = Group), size = 3) +
  scale_color_manual(values = c("Group 1" = "#F8766D",
                                "Group 2" = "#00BFC4")) +
  scale_shape_manual(values = c("Group 1" = 16, "Group 2" = 17)) +
  scale_x_continuous(limits = c(0, 6), breaks = 0:6) +
  labs(subtitle = "(a) ANOVA: full predictions (solid) vs. restricted (dashed)",
       x = expression("Covariate" ~ (italic(X))),
       y = expression("Outcome" ~ (italic(Y))), color = NULL, shape = NULL) +
  theme(legend.position = "top")

p9_3b <- ggplot(d9, aes(X, Y, color = Group)) +
  geom_abline(intercept = a_restricted, slope = b_restricted,
              color = "gray40", linewidth = 0.9, linetype = "dashed") +
  geom_abline(intercept = int_g1, slope = b_full,
              color = "#F8766D", linewidth = 1) +
  geom_abline(intercept = int_g2, slope = b_full,
              color = "#00BFC4", linewidth = 1) +
  geom_point(aes(shape = Group), size = 3) +
  scale_color_manual(values = c("Group 1" = "#F8766D",
                                "Group 2" = "#00BFC4")) +
  scale_shape_manual(values = c("Group 1" = 16, "Group 2" = 17)) +
  scale_x_continuous(limits = c(0, 6), breaks = 0:6) +
  labs(subtitle = "(b) ANCOVA: full predictions (solid) vs. restricted (dashed)",
       x = expression("Covariate" ~ (italic(X))),
       y = expression("Outcome" ~ (italic(Y))), color = NULL, shape = NULL) +
  theme(legend.position = "top")

(p9_3a | p9_3b) +
  plot_annotation(
    title = "Figure 9.3. Difference between full-model and restricted-model predictions for the Table 9.1 data",
    theme = theme(plot.title = element_text(color = "black",
                                            face = "bold", size = rel(1.0))))
Figure 9.3. Difference between full-model and restricted-model predictions for the Table 9.1 data in (a) the ANOVA and (b) the ANCOVA.

Figure 9.3. Difference between full-model and restricted-model predictions for the Table 9.1 data in (a) the ANOVA and (b) the ANCOVA.

9.4.2.2 — Comparison of Models

Now we perform the actual model comparison. We run a standard ANOVA model (ignoring the covariate) and an ANCOVA model (including the covariate XX). By using the anova() and summary() functions on these objects, R defaults to providing Type I (sequential) sums of squares.

HideShow
ANOVA_9_1 <- lm(Y ~ Group, data=chapter_9_table_1)
ANCOVA_9_1 <- lm(Y ~ X+Group, data=chapter_9_table_1)

# Standard ANOVA output
anova(ANOVA_9_1)
HideShow
Analysis of Variance Table

Response: Y
          Df Sum Sq Mean Sq F value  Pr(>F)  
Group      1     54      54  7.7143 0.04995 *
Residuals  4     28       7                  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Group SS = 54, Error SS = 28, F = 7.714 — matches book p. 451 (Table 9.6),
#> the ANOVA that ignores the covariate.
summary(ANOVA_9_1)
HideShow

Call:
lm(formula = Y ~ Group, data = chapter_9_table_1)

Residuals:
 1  2  3  4  5  6 
-3  2  1 -1 -2  3 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)  
(Intercept)    7.000      1.528   4.583   0.0102 *
Group2         6.000      2.160   2.777   0.0499 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.646 on 4 degrees of freedom
Multiple R-squared:  0.6585,    Adjusted R-squared:  0.5732 
F-statistic: 7.714 on 1 and 4 DF,  p-value: 0.04995
HideShow
# ANCOVA output
anova(ANCOVA_9_1)
HideShow
Analysis of Variance Table

Response: Y
          Df Sum Sq Mean Sq F value  Pr(>F)  
X          1   67.6    67.6    16.9 0.02607 *
Group      1    2.4     2.4     0.6 0.49503  
Residuals  3   12.0     4.0                  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Group SS = 2.4, Error SS = 12.0, F = 0.6 — matches book p. 451 (Equation 9.22)
summary(ANCOVA_9_1)
HideShow

Call:
lm(formula = Y ~ X + Group, data = chapter_9_table_1)

Residuals:
 1  2  3  4  5  6 
-1  2 -1  1 -2  1 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)    3.000      2.309   1.299    0.285
X              2.000      1.000   2.000    0.139
Group2         2.000      2.582   0.775    0.495

Residual standard error: 2 on 3 degrees of freedom
Multiple R-squared:  0.8537,    Adjusted R-squared:  0.7561 
F-statistic:  8.75 on 2 and 3 DF,  p-value: 0.05598

Using the Anova() function from the car package (see the Chapter 7 R code), Type III sums of squares can be obtained. With one factor and one covariate and no interaction in the model, the Type III test of Group is exactly the comparison of Equation 9.1 against Equation 9.2, so it returns the same sum of squares as the sequential table above.

HideShow
Anova(ANCOVA_9_1, type="III")
HideShow
Anova Table (Type III tests)

Response: Y
            Sum Sq Df F value Pr(>F)
(Intercept)   6.75  1  1.6875 0.2848
X            16.00  1  4.0000 0.1393
Group         2.40  1  0.6000 0.4950
Residuals    12.00  3               
HideShow
#> Group SS = 2.40, F = 0.6 — matches book p. 451 (Equation 9.22)

Because the ANOVA full model is nested within the ANCOVA full model, a model comparison can be done using the anova() function, where two different (but nested) linear models are provided as input. This is the book’s test of regression: it asks whether the slope parameter β\beta buys a significant reduction in error.

HideShow
anova(ANOVA_9_1, ANCOVA_9_1)
HideShow
Analysis of Variance Table

Model 1: Y ~ Group
Model 2: Y ~ X + Group
  Res.Df RSS Df Sum of Sq  F Pr(>F)
1      4  28                       
2      3  12  1        16  4 0.1393
HideShow
#> F = (28 - 12)/1 / (12/3) = 16/4 = 4 — matches book p. 452 (Equation 9.24),
#> which notes this is short of the critical value of 10.1 at alpha = .05.

The test of the group effect itself is the comparison the book carries out in Equation 9.22: the full ANCOVA model against the ANCOVA restricted model that drops the group effect but keeps the covariate. Plugging the error sums of squares straight into the FF formula reproduces the book’s value:

HideShow
# F = [(E_R - E_F)/(df_R - df_F)] / (E_F / df_F), full vs. restricted ANCOVA.
df_R <- Restricted.Model$df.residual   # Y ~ X
df_F <- Full.Model$df.residual         # Y ~ Group + X
F_group <- ((E_R - E_F) / (df_R - df_F)) / (E_F / df_F)
F_group
HideShow
[1] 0.6
HideShow
#> F = (2.4/1) / (12/3) = 0.6 — matches book p. 451 (Equation 9.22)
9.4.3 — Two Consequences of Using ANCOVA

Including a covariate changes our analysis in two main ways: it reduces the sum of squared errors, and it adjusts the estimated magnitude of the group effect.

9.4.3.1 — Test of Regression

The first consequence – the reduction in error – is exactly what the test of regression above measures: adding the covariate cut the sum of squared errors from 28 to 12, less than half its original value (book p. 452).

9.4.3.2 — Estimated Conditional Means

The second consequence is the adjustment of the group means. Because ANCOVA adjusts for the covariate, the raw, observed means of the dependent variable are no longer the most accurate representation of the group differences. Instead, we must calculate the adjusted means (also called estimated conditional means). This tells us what the group means for YY would be if all groups were held perfectly constant at the grand mean of the covariate XX.

We can extract these using the predict() function, but note that this is only one way to do it.

HideShow
# Compute the grand mean across all groups on the covariate X
X_Grand_Mean <- mean(chapter_9_table_1$X)

# Create a prediction data frame using the group levels and the grand mean of X
Group_Predict <- data.frame(
  Group = factor(c(1,2), levels=c(1,2)),
  X = rep(X_Grand_Mean, 2)
)

# Step 3: Use the ANCOVA model to predict Y at the grand mean of X
Adj_Means <- predict(ANCOVA_9_1, Group_Predict)

# Compare the observed raw means to the adjusted means
Obs_Mean_X <- c(mean(chapter_9_table_1[chapter_9_table_1$Group==1, "X"]),
                mean(chapter_9_table_1[chapter_9_table_1$Group==2, "X"]))

Obs_Mean_Y <- c(mean(chapter_9_table_1[chapter_9_table_1$Group==1, "Y"]),
                mean(chapter_9_table_1[chapter_9_table_1$Group==2, "Y"]))

Summary_of_Means = data.frame(
  Obs_Mean_X = Obs_Mean_X,
  X_Grand_Mean = X_Grand_Mean,
  Obs_Mean_Y = Obs_Mean_Y,
  Adjusted_Group_Means_Y = Adj_Means
)

Summary_of_Means
HideShow
  Obs_Mean_X X_Grand_Mean Obs_Mean_Y Adjusted_Group_Means_Y
1          2            3          7                      9
2          4            3         13                     11
HideShow
#> The adjustment moves Group 1 from an observed mean of 7 to an adjusted mean
#> of 9, and Group 2 from 13 to 11 — matches book p. 454 (Equation 9.27) and
#> the computations displayed in Figure 9.4, p. 455.

The same adjusted means come out of emmeans(), which is the tool we use for the three-group example later in the chapter. Asking for the estimated marginal means of Group evaluates the full model at the grand mean of the covariate, which is precisely the definition of an adjusted mean:

HideShow
emmeans(ANCOVA_9_1, ~ Group)
HideShow
 Group emmean   SE df lower.CL upper.CL
 1          9 1.53  3     4.14     13.9
 2         11 1.53  3     6.14     15.9

Confidence level used: 0.95 
HideShow
#> 9 and 11 — the same adjusted means, matching book p. 454
Visualizing the Adjustment: a Pretest-Posttest Scatterplot

To understand how ANCOVA adjusts these effects, it is helpful to visualize it.

Here is the code that formed the basis for the textbook’s cover art. It uses Rosenthal’s Pygmalion data to plot the pretest (covariate) against the posttest (dependent variable) for Treatment and Control groups.

The plot maps the raw data, the individual group regression lines, and the restricted model line to visually demonstrate how the conditional means are pulled from the slopes.

HideShow
Data <- rbind(
c(0,61.00,86.00,25.00),
c(0,79.00,82.00,3.00),
c(0,86.00,103.00,17.00),
c(0,91.00,90.00,-1.00),
c(0,92.00,105.00,13.00),
c(0,100.00,120.00,20.00),
c(0,111.00,105.00,-6.00),
c(1,60.00,97.00,37.00),
c(1,61.00,106.00,45.00),
c(1,84.00,107.00,23.00),
c(1,88.00,128.00,40.00),
c(1,95.00,113.00,18.00),
c(1,100.00,108.00,8.00),
c(1,116.00,137.00,21.00))
colnames(Data) <- c("Treatment", "IQ.Pre", "IQ.8", "IQ.Gain")
Data <- as.data.frame(Data)
Data$Condition <- factor(ifelse(Data$Treatment == 1, "Treatment, T", "Control, C"),
                         levels = c("Treatment, T", "Control, C"))

# The ANCOVA full model (parallel lines) and the restricted model (one line).
Result   <- lm(IQ.8 ~ Condition + IQ.Pre, data = Data)
b.0      <- coef(Result)[["(Intercept)"]]            # intercept for Treatment
b.Control <- coef(Result)[["ConditionControl, C"]]   # Control minus Treatment
b.W      <- coef(Result)[["IQ.Pre"]]                 # pooled within-group slope
Result.R <- lm(IQ.8 ~ IQ.Pre, data = Data)

# Observed group means and the grand mean on the posttest.
mean_T <- mean(Data$IQ.8[Data$Treatment == 1])
mean_C <- mean(Data$IQ.8[Data$Treatment == 0])
mean_G <- mean(Data$IQ.8)

# Labels sit just outside the plotting region on the right.
x_lab  <- 123
labels_right <- data.frame(
  x     = x_lab,
  y     = c(b.0 + b.W * x_lab,
            b.0 + b.Control + b.W * x_lab,
            coef(Result.R)[[1]] + coef(Result.R)[[2]] * x_lab,
            mean_T, mean_C, mean_G),
  label = c("hat(italic(Y))[T]", "hat(italic(Y))[C]",
            "hat(italic(Y))[Restricted]",
            "bar(italic(Y))[T]", "bar(italic(Y))[C]", "bar(italic(Y))"))

ggplot(Data, aes(IQ.Pre, IQ.8)) +
  # The two flat lines at the observed group means, and the grand mean.
  geom_hline(yintercept = c(mean_T, mean_C), color = "gray55", linewidth = 0.4) +
  geom_hline(yintercept = mean_G, color = "gray55", linewidth = 0.4) +
  # ANCOVA full model: two parallel lines, one per condition.
  geom_abline(intercept = b.0, slope = b.W, color = "#00BFC4", linewidth = 1) +
  geom_abline(intercept = b.0 + b.Control, slope = b.W,
              color = "#F8766D", linewidth = 1) +
  # ANCOVA restricted model: a single line ignoring condition.
  geom_abline(intercept = coef(Result.R)[[1]], slope = coef(Result.R)[[2]],
              color = "#0C2340", linetype = "dashed", linewidth = 1) +
  geom_point(aes(shape = Condition, color = Condition), size = 3) +
  geom_text(data = labels_right, aes(x, y, label = label),
            parse = TRUE, hjust = 0, size = 3.6, inherit.aes = FALSE) +
  scale_shape_manual(values = c("Treatment, T" = 16, "Control, C" = 1)) +
  scale_color_manual(values = c("Treatment, T" = "#00BFC4",
                                "Control, C" = "#F8766D")) +
  coord_cartesian(xlim = c(60, 120), ylim = c(80, 140), clip = "off") +
  labs(x = "Pretest", y = "Posttest", shape = NULL, color = NULL) +
  theme(legend.position = "top", plot.margin = margin(5.5, 58, 5.5, 5.5))

The fitted values of the ANCOVA full model, group by group, are the heights of the two sloped lines at each subject’s pretest score:

HideShow
Data.Fitted <- cbind(Data, y.hat = fitted(Result))

Data.Fitted[Data.Fitted$Treatment == 0, "y.hat"]
HideShow
[1]  83.76818  93.52574  97.32035 100.03078 100.57287 104.90956 110.87252
HideShow
Data.Fitted[Data.Fitted$Treatment == 1, "y.hat"]
HideShow
[1]  99.46515 100.00723 112.47523 114.64358 118.43819 121.14862 129.82201

The plot above has details that may not be necessary. Here we show just the ANCOVA part of it: the two parallel within-group regression lines and the restricted-model line, with the flat ANOVA lines at the observed means dropped. (The “Restricted” line could be dropped as well if desired.)

HideShow
ggplot(Data, aes(IQ.Pre, IQ.8)) +
  geom_abline(intercept = b.0, slope = b.W, color = "#00BFC4", linewidth = 1) +
  geom_abline(intercept = b.0 + b.Control, slope = b.W,
              color = "#F8766D", linewidth = 1) +
  geom_abline(intercept = coef(Result.R)[[1]], slope = coef(Result.R)[[2]],
              color = "#0C2340", linetype = "dashed", linewidth = 1) +
  geom_point(aes(shape = Condition, color = Condition), size = 3) +
  geom_text(data = labels_right[1:3, ], aes(x, y, label = label),
            parse = TRUE, hjust = 0, size = 3.6, inherit.aes = FALSE) +
  scale_shape_manual(values = c("Treatment, T" = 16, "Control, C" = 1)) +
  scale_color_manual(values = c("Treatment, T" = "#00BFC4",
                                "Control, C" = "#F8766D")) +
  coord_cartesian(xlim = c(60, 120), ylim = c(80, 140), clip = "off") +
  labs(title = "The ANCOVA model visually",
       x = "Pretest", y = "Posttest", shape = NULL, color = NULL) +
  theme(legend.position = "top", plot.margin = margin(5.5, 58, 5.5, 5.5))

9.4.4 — Assumptions in ANCOVA
9.4.4.2 — Lack of Independence of Treatment and Covariate

To test if the treatment and covariate are independent, the textbook suggests running an ANOVA with the covariate (XX) as the dependent variable. We can demonstrate this using our chapter_9_table_1 data from earlier.

HideShow
# Testing for lack of independence (Covariate Imbalance)
# We predict the covariate X using the Group variable
Independence_Test <- lm(X ~ Group, data = chapter_9_table_1)

# View the ANOVA table
anova(Independence_Test)
HideShow
Analysis of Variance Table

Response: X
          Df Sum Sq Mean Sq F value  Pr(>F)  
Group      1      6       6       6 0.07048 .
Residuals  4      4       1                  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

If the Pr(>F) was less than .05, it would indicate our groups differ significantly on the covariate, violating the assumption of independence.

9.4.4.3 — Measurement Error in Covariate

The text provides a specific numerical example about IQ and home environment to demonstrate how a fallible covariate (proportion of true-score variance = .5) mathematically underadjusts the group differences (Equations 9.29 and 9.30). We can use R to reproduce this example.

HideShow
# Parameters provided in the textbook example
mean_Y_W <- 108       # Mean IQ Whites
mean_Y_B <- 92        # Mean IQ Blacks
mean_X_W <- 80        # Mean Home Env Whites
mean_X_B <- 40        # Mean Home Env Blacks
beta_true <- 0.4      # True regression slope
reliability <- 0.5    # Proportion of true score variance

# True Adjusted Effect (if we had a perfect measure of the covariate)
true_adj_effect <- (mean_Y_W - mean_Y_B) - beta_true * (mean_X_W - mean_X_B)
cat("True Adjusted Effect (Perfect Covariate):", true_adj_effect, "\n")
HideShow
True Adjusted Effect (Perfect Covariate): 0 
HideShow
#> 0 — matches book p. 465: 16 - 0.4(40) = 0, "a correct adjustment would
#> result in identical mean IQ scores"

# Fallible Regression Slope (Equation 9.29)
beta_fallible <- beta_true * reliability
cat("Fallible Regression Slope:", beta_fallible, "\n")
HideShow
Fallible Regression Slope: 0.2 
HideShow
#> 0.2 — matches book p. 465 (Equation 9.29: beta_fallible = beta_true times
#> the proportion of true-score variance)

# Estimated Adjusted Effect with Fallible Covariate (Equation 9.30)
fallible_adj_effect <- (mean_Y_W - mean_Y_B) - beta_fallible * (mean_X_W - mean_X_B)
cat("Estimated Adjusted Effect (Fallible Covariate):", fallible_adj_effect, "\n")
HideShow
Estimated Adjusted Effect (Fallible Covariate): 8 
HideShow
#> 8 — matches book p. 465-466 (Equation 9.30; Figure 9.7 on p. 466): the
#> observed difference "was reduced only half as much as it should have been"

Notice how the R output matches the textbook’s conclusion: A perfect measure adjusts the group difference down to 0, but the fallible measure leaves an artificial gap of 8 points.

9.4.5 — Numerical Example

Here we perform the numerical example using the Beck Depression data from Table 9.7 to summarize the points made so far. The data represents a hypothetical three-group study assessing different interventions for depression: (1) SSRI, (2) Placebo, or (3) Wait List.

HideShow
# Load and prepare the Beck Depression data
data(chapter_9_table_7)

# Recode Condition into a categorical Group factor, spelling out each level.
chapter_9_table_7 <- chapter_9_table_7 |>
  mutate(Group = case_when(
    Condition == 1 ~ "SSRI",
    Condition == 2 ~ "Placebo",
    Condition == 3 ~ "Wait List"
  )) |>
  mutate(Group = factor(Group, levels = c("SSRI", "Placebo", "Wait List")))

str(chapter_9_table_7)
HideShow
'data.frame':   30 obs. of  4 variables:
 $ Condition: int  1 1 1 1 1 1 1 1 1 1 ...
 $ Pre      : int  18 16 16 15 14 20 14 21 25 11 ...
 $ Post     : int  12 0 10 9 0 11 2 4 15 10 ...
 $ Group    : Factor w/ 3 levels "SSRI","Placebo",..: 1 1 1 1 1 1 1 1 1 1 ...

First, let’s look at the unadjusted descriptive statistics for the Pretest and Posttest. Notice that, as expected with random assignment, there are minimal differences in the pretest means, but much larger differences emerge on the posttest.

HideShow
group_by(chapter_9_table_7, Group) %>%
summarise(mean=mean(Pre), sd=sd(Pre), n=n())
HideShow
# A tibble: 3 × 4
  Group      mean    sd     n
  <fct>     <dbl> <dbl> <int>
1 SSRI       17    4.08    10
2 Placebo    17.7  5.21    10
3 Wait List  17.4  6.31    10
HideShow
#> pretest means 17.0, 17.7, 17.4 — matches book p. 467 (Table 9.7, last line)

group_by(chapter_9_table_7, Group) %>%
summarise(mean=mean(Post), sd=sd(Post), n=n())
HideShow
# A tibble: 3 × 4
  Group      mean    sd     n
  <fct>     <dbl> <dbl> <int>
1 SSRI        7.3  5.36    10
2 Placebo    12.2  5.73    10
3 Wait List  14    7.57    10
HideShow
#> posttest means 7.3, 12.2, 14.0 — matches book p. 467 (Table 9.7, last line)

mean(chapter_9_table_7$Pre)
HideShow
[1] 17.36667
HideShow
#> 17.367 — the grand mean on the covariate, book p. 467

Here we perform a linear model and ask for the ANOVA-based output (via anova()) and the regression-based output (via summary()). This yields, per the R default, Type I sums of squares. See the first part of Table 9.9.

HideShow
Beck_ANOVA_Model <- lm(Post ~ Group, data=chapter_9_table_7)
Beck_ANCOVA_Model <- lm(Post~ Group + Pre, data=chapter_9_table_7)

# ANOVA, ignoring the pretest entirely
anova(Beck_ANOVA_Model)
HideShow
Analysis of Variance Table

Response: Post
          Df  Sum Sq Mean Sq F value  Pr(>F)  
Group      2  240.47 120.233  3.0348 0.06473 .
Residuals 27 1069.70  39.619                  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Group SS = 240.47 and Error SS = 1069.70 — matches book p. 470-471, where
#> 240.47 is the Type I (unadjusted) group sum of squares and 1,069.70 the
#> error sum of squares of the full ANOVA model.

# Type I (sequential) ANCOVA table: Group entered first, then Pre
anova(Beck_ANCOVA_Model)
HideShow
Analysis of Variance Table

Response: Post
          Df Sum Sq Mean Sq F value   Pr(>F)   
Group      2 240.47  120.23  4.1332 0.027629 * 
Pre        1 313.37  313.37 10.7723 0.002937 **
Residuals 26 756.33   29.09                    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> matches book p. 468 (Table 9.9, "Type I SS"): Group SS = 240.47, F = 4.13,
#> p = .0276; Pre SS = 313.37, F = 10.77, p = .0029

The first significance test SAS prints for these data compares the full ANCOVA model against the restricted model that allows for neither group effects nor the covariate. In R that is the omnibus FF of the fitted ANCOVA:

HideShow
anova(lm(Post ~ 1, data = chapter_9_table_7), Beck_ANCOVA_Model)
HideShow
Analysis of Variance Table

Model 1: Post ~ 1
Model 2: Post ~ Group + Pre
  Res.Df     RSS Df Sum of Sq      F   Pr(>F)   
1     29 1310.17                                
2     26  756.33  3    553.83 6.3462 0.002252 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F(3, 26) = 6.35, p = .0023 — matches book p. 468 (Table 9.9, "Model" line)
#> and the discussion on p. 469.

As the book stresses (p. 469), this omnibus FF tells us only that the group effects and the regression coefficient are not all zero; it does not isolate the group effect. For that we need the Type III test.

Now, we perform the ANOVA using the Type III sums of squares. See the second part of Table 9.9.

HideShow
# ANCOVA Output (Type III SS) - See second part of Table 9.9
Anova(Beck_ANCOVA_Model, type="III")
HideShow
Anova Table (Type III tests)

Response: Post
            Sum Sq Df F value   Pr(>F)   
(Intercept)  27.83  1  0.9567 0.337029   
Group       217.15  2  3.7324 0.037584 * 
Pre         313.37  1 10.7723 0.002937 **
Residuals   756.33 26                    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Type III Group F = 3.73, p = .0376 — matches book p. 469; Group SS = 217.15
#> and Error (E_F) = 756.33 — matches book p. 470 (both read off Table 9.9,
#> p. 468)

# Regression coefficients
summary(Beck_ANCOVA_Model)
HideShow

Call:
lm(formula = Post ~ Group + Pre, data = chapter_9_table_7)

Residuals:
     Min       1Q   Median       3Q      Max 
-10.6842  -3.9615   0.6448   3.8773   9.9675 

Coefficients:
               Estimate Std. Error t value Pr(>|t|)   
(Intercept)     -3.6704     3.7525  -0.978  0.33703   
GroupPlacebo     4.4483     2.4160   1.841  0.07703 . 
GroupWait List   6.4419     2.4133   2.669  0.01292 * 
Pre              0.6453     0.1966   3.282  0.00294 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.393 on 26 degrees of freedom
Multiple R-squared:  0.4227,    Adjusted R-squared:  0.3561 
F-statistic: 6.346 on 3 and 26 DF,  p-value: 0.002252
HideShow
#> b_W (coefficient on Pre) = 0.6453 — matches book p. 469 ("approximately
#> 0.65") and Table 9.9, p. 468

Note: The regression coefficient for Pre(bWb_W) is approximately 0.65. We will use this to calculate the adjusted means.

R and SAS do not code a factor the same way, so the Group coefficients above are not the ones printed in Table 9.9: R takes the first level (SSRI) as the reference, whereas SAS PROC GLM takes the last (Wait List). Releveling to the wait-list control reproduces the book’s parameter estimates exactly:

HideShow
chapter_9_table_7_B <- chapter_9_table_7
chapter_9_table_7_B$Group <- relevel(chapter_9_table_7_B$Group, ref = "Wait List")

Beck_ANCOVA_Model2 <- lm(Post ~ Group + Pre, data = chapter_9_table_7_B)
summary(Beck_ANCOVA_Model2)
HideShow

Call:
lm(formula = Post ~ Group + Pre, data = chapter_9_table_7_B)

Residuals:
     Min       1Q   Median       3Q      Max 
-10.6842  -3.9615   0.6448   3.8773   9.9675 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)   
(Intercept)    2.7715     3.8227   0.725  0.47492   
GroupSSRI     -6.4419     2.4133  -2.669  0.01292 * 
GroupPlacebo  -1.9936     2.4128  -0.826  0.41617   
Pre            0.6453     0.1966   3.282  0.00294 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.393 on 26 degrees of freedom
Multiple R-squared:  0.4227,    Adjusted R-squared:  0.3561 
F-statistic: 6.346 on 3 and 26 DF,  p-value: 0.002252
HideShow
#> Intercept 2.7715, GroupSSRI -6.4419 (t = -2.67, p = .0129),
#> GroupPlacebo -1.9936 (t = -0.83, p = .4162), Pre 0.6453 (t = 3.28,
#> p = .0029) — matches book p. 468 (Table 9.9, parameter estimates)

(More generally, relevel() is how you change the reference level whenever you want to compare specific groups against a particular control.)

The two models the book contrasts—the ANOVA that ignores the pretest and the ANCOVA that adjusts for it—are easiest to read side by side. With modelsummary, each model is a column and the fit statistics sit at the foot. Standard errors are in parentheses under each coefficient (APA style):

HideShow
modelsummary(
  list("ANOVA (Post ~ Group)" = Beck_ANOVA_Model,
       "ANCOVA (Post ~ Group + Pre)" = Beck_ANCOVA_Model),
  estimate  = "{estimate}",
  statistic = "({std.error})",   # standard errors in parentheses, APA style
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  output    = "gt"
)
ANOVA (Post ~ Group) ANCOVA (Post ~ Group + Pre)
(Intercept) 7.300 -3.670
(1.990) (3.752)
GroupPlacebo 4.900 4.448
(2.815) (2.416)
GroupWait List 6.700 6.442
(2.815) (2.413)
Pre 0.645
(0.197)
Num.Obs. 30 30
AIC 200.4 192.0
BIC 206.0 199.0
Log.Lik. -96.177 -90.977

The same two fits as a gtsummary table, each under its own spanning header. Adding the Pre covariate sharpens the Group coefficients (smaller standard errors) by removing pretest variability from the error term:

HideShow
t_anova  <- tbl_regression(Beck_ANOVA_Model,  intercept = TRUE)
t_ancova <- tbl_regression(Beck_ANCOVA_Model, intercept = TRUE)
tbl_merge(list(t_anova, t_ancova),
          tab_spanner = c("**ANOVA**", "**ANCOVA**"))
Characteristic
ANOVA
ANCOVA
Beta 95% CI p-value Beta 95% CI p-value
(Intercept) 7.3 3.2, 11 0.001 -3.7 -11, 4.0 0.3
Group





    SSRI — —
— —
    Placebo 4.9 -0.88, 11 0.093 4.4 -0.52, 9.4 0.077
    Wait List 6.7 0.92, 12 0.025 6.4 1.5, 11 0.013
Pre


0.65 0.24, 1.0 0.003
Abbreviation: CI = Confidence Interval

The classical ANCOVA source table of Table 9.9 reads more clearly as an APA-style table—sums of squares, df, F, p, and partial η2\eta^2— than as raw Anova() output. We build it from the Type III table with gt. Partial η2\eta^2 is each effect’s share of effect-plus-error variance:

HideShow
beck_t3 <- car::Anova(Beck_ANCOVA_Model, type = "III")
ss_res_beck <- beck_t3["Residuals", "Sum Sq"]   # error SS, for partial eta^2
beck_t3 |>
  as.data.frame() |>
  tibble::rownames_to_column("Source") |>
  dplyr::filter(Source != "(Intercept)") |>
  dplyr::transmute(
    Source = dplyr::recode(Source, "Pre" = "Pre (covariate)"),
    SS = `Sum Sq`, df = Df, MS = `Sum Sq` / Df,
    Fstat = `F value`, p = `Pr(>F)`,
    peta = dplyr::if_else(Source == "Residuals", NA_real_,
                          `Sum Sq` / (`Sum Sq` + ss_res_beck))
  ) |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("Analysis of Covariance for Posttest Depression"),
             subtitle = md("The Type III portion of the book's Table 9.9 (p. 468), reformatted")) |>
  cols_align(align = "center", columns = -Source)
Analysis of Covariance for Posttest Depression
The Type III portion of the book’s Table 9.9 (p. 468), reformatted
Source SS df MS F p Partial η2
Group 217.15 2 108.57 3.73 0.0376 0.223
Pre (covariate) 313.37 1 313.37 10.77 0.0029 0.293
Residuals 756.33 26 29.09


ANCOVA compares adjusted means. We can use the emmeans package in R to easily replicate the SAS LSMEANS output from Table 9.8. This calculates what the group posttest means would be if all groups started at the exact grand mean of the pretest (17.367).

HideShow
# Calculate Estimated Marginal Means (Adjusted Means)
Adjusted_Means <- emmeans(Beck_ANCOVA_Model, ~ Group)
Adjusted_Means
HideShow
 Group     emmean   SE df lower.CL upper.CL
 SSRI        7.54 1.71 26     4.03     11.0
 Placebo    11.98 1.71 26     8.48     15.5
 Wait List  13.98 1.71 26    10.47     17.5

Confidence level used: 0.95 
HideShow
#> 7.5366, 11.9849, 13.9785 — matches book p. 468 (Table 9.8, SAS LSMEANS),
#> which the book rounds to 7.5, 12.0, and 14.0 on p. 467

Notice that the adjusted means (approx. 7.5, 12.0, 14.0) are very similar to the unadjusted means. This is precisely what we expect in a randomized study. However, using ANCOVA properly controls our error rates and capitalizes on increased power and precision.

In DMAR

Everything above came from lm(), car::Anova(), and emmeans(). DMAR’s ancova() packages that same analysis into one call and adds what those three do not give in one place: effect sizes with confidence intervals and a homogeneity-of-regression test. We pass the names of the outcome, treatment, and covariate columns from the prepared chapter_9_table_7 data frame.

HideShow
ancova(
  data       = chapter_9_table_7,
  outcome    = "Post",
  treatment  = "Group",
  covariates = "Pre",
  conf_level = 0.95
)
term value
F_value 3.732
df_1 2
df_2 26
p_value 0.0376
sum_of_squares_type 3
eta_squared_partial 0.223
eta_squared_partial_ci_lower 0.000
eta_squared_partial_ci_upper 0.421
omega_squared_partial 0.154
omega_squared_partial_ci_lower 0.000
omega_squared_partial_ci_upper 0.421
adjusted_mean[SSRI] 7.537
adjusted_mean[Placebo] 11.985
adjusted_mean[Wait List] 13.978
se_adjusted_mean[SSRI] 1.707
se_adjusted_mean[Placebo] 1.707
se_adjusted_mean[Wait List] 1.706
F_homogeneity_of_regression 1.062
df_homogeneity_of_regression 2
p_homogeneity_of_regression 0.3614

Confidence level: 95%

HideShow
#> F_value = 3.732, df = 2 and 26, p = .0376 — the Type III test, matching
#> Anova(type = "III") above and book p. 469.
#> adjusted_mean rows 7.537, 11.985, 13.978 — matches book p. 468 (Table 9.8).
#> eta_squared_partial = 0.223 — the same quantity as the extrinsic R^2 of
#> .22 computed by hand in the next section (book p. 470).

The FF, its degrees of freedom, and the adjusted_mean[...] rows reproduce the base-R and emmeans results exactly; what the single call adds is partial η̂2\hat{\eta}^2 and partial ω̂2\hat{\omega}^2 with noncentral-FF confidence intervals, the standard errors of the adjusted means, and F_homogeneity_of_regression, the test of the parallel-slopes assumption developed in the chapter extension. Note that omega_squared_partial treats the covariate as extrinsic; it is not the intrinsic ω̂2\hat{\omega}^2 of Equation 9.31, which we compute by hand in the next section.

The efficiency of ANCOVA as a variance-reduction device is governed by the within-groups partial correlation rYX⋅Groupr_{YX \cdot \text{Group}} of the covariate with the outcome, after removing the group means. That correlation is a one-line base R computation; DMAR then adds its asymptotic (Olkin-Finn) variance and its expected sample value, which are useful at the design stage because the downward bias grows with the number of variables partialled out.

HideShow
# Within-groups partial correlation of Pre and Post (controlling for Group),
# computed from the residuals of each variable regressed on Group.
r_partial_obs <-
  with(chapter_9_table_7,
       cor(residuals(lm(Post ~ Group)),
           residuals(lm(Pre  ~ Group))))
r_partial_obs
HideShow
[1] 0.5412457
HideShow
# Asymptotic (Olkin-Finn) variance of the partial correlation. Here p = 3:
# the regression of Post on Pre carries two dummy predictors for the
# three-level Group factor, so two variables are partialled out.
var_partial_r(r = r_partial_obs, N = nrow(chapter_9_table_7), p = 3)
term value
var_partial_r 0.019
HideShow
# Expected sample partial r if the population value equaled the observed one:
expected_partial_r(true_cor = r_partial_obs,
                   N = nrow(chapter_9_table_7), p = 3)
true_cor N p expected_partial_r bias relative_bias
0.541 30 3 0.534 0.007 0.013
9.4.6 — Measures of Effect

In ANCOVA, we can conceptualize the covariate as either an extrinsic or intrinsic component of the design.

  • Extrinsic: The covariate contributes additional variance over and above natural variability (usually a manipulated factor). If we treat it this way, we are looking at the variance accounted for only among individuals with identical pretest scores.

  • Intrinsic: The covariate correlates with natural variability (usually a naturally occurring individual difference, like a pretest). If we treat it this way, we look at the variance accounted for in the entire population. The book emphasizes this approach.

We can calculate R2R^2 for both conceptualizations by extracting the Sums of Squares (SS) from our previous models.

HideShow
# 1. Extrinsic R-squared (Controlling for the covariate)
anova_ancova_type3 <- car::Anova(Beck_ANCOVA_Model, type="III")
SS_group_ext <- anova_ancova_type3["Group", "Sum Sq"]
SS_error_ext <- anova_ancova_type3["Residuals", "Sum Sq"]

R2_extrinsic <- SS_group_ext / (SS_error_ext + SS_group_ext)
cat("Extrinsic R-squared:", round(R2_extrinsic, 2), "\n")
HideShow
Extrinsic R-squared: 0.22 
HideShow
#> R^2 = 0.22 — matches book p. 470: (E_R - E_F)/E_R with E_F = 756.33 and
#> E_R = 756.33 + 217.15 = 973.48

The intervention effect accounts for 22% of the variance in posttest depression once we control for pretest depression. Stated differently, if we only looked at individuals who had the exact same pretest scores, the intervention explains 22% of the variance in their final scores.

HideShow
# 2. Intrinsic R-squared (Total variance in the population)
anova_standard <- anova(Beck_ANOVA_Model)
SS_group_int <- anova_standard["Group", "Sum Sq"]
SS_total <- sum(anova_standard$`Sum Sq`)

R2_intrinsic <- SS_group_int / SS_total
cat("Intrinsic R-squared:", round(R2_intrinsic, 2), "\n")
HideShow
Intrinsic R-squared: 0.18 
HideShow
#> R^2 = 0.18 — matches book p. 470: 240.47 / 1310.17

The intervention effect accounts for 18% of the total variance in posttest depression across everyone in the sample, regardless of where they started.

Because R2R^2 describes the sample, we often prefer Omega Squared (ω̂2\hat{\omega}^2) to estimate the population effect size. Assuming an intrinsic covariate, the formula is:ω̂2=dfeffect(MSeffect−MSerror)SStotal+MSerror\hat{\omega}^2 = \frac{df_{effect}(MS_{effect} - MS_{error})}{SS_{total} + MS_{error}}

(Equation 9.31)

HideShow
# Calculating Omega Squared using values from the Type III ANCOVA table
df_effect <- anova_ancova_type3["Group", "Df"]
MS_effect <- anova_ancova_type3["Group", "Sum Sq"] / df_effect
MS_error <- anova_ancova_type3["Residuals", "Sum Sq"] / anova_ancova_type3["Residuals", "Df"]

omega_squared <- (df_effect * (MS_effect - MS_error)) / (SS_total + MS_error)
cat("Omega Squared:", round(omega_squared, 2), "\n")
HideShow
Omega Squared: 0.12 
HideShow
#> omega^2 = 0.12 — matches book p. 471 (Equation 9.31):
#> df_effect = 2, MS_effect = 108.57, MS_error = 29.09, SS_total = 1310.17

We estimate that the intervention accounts for 12% of the total variance in posttest depression scores in the true population.

In DMAR

The hand computation above gives a point estimate and nothing else. DMAR’s ci_omega_squared() adds the interval: it inverts the noncentral FF distribution, given the FF statistic, its two degrees of freedom, and the total sample size. We pass the Type III (adjusted) FF for the group effect — the same 3.73 the book reports on p. 469.

HideShow
# Pull the Type III Group F and its degrees of freedom from the table we
# already built, then invert the noncentral F distribution for the interval.
F_group_t3   <- anova_ancova_type3["Group", "F value"]
df_effect_ci <- anova_ancova_type3["Group", "Df"]
df_error_ci  <- anova_ancova_type3["Residuals", "Df"]
N_total      <- nrow(chapter_9_table_7)

ci_omega_squared(F_value = F_group_t3, df_effect = df_effect_ci,
                 df_error = df_error_ci, N = N_total,
                 estimand = "partial", conf_level = 0.95)
effect omega_squared_partial omega_squared_partial_ci_lower omega_squared_partial_ci_upper F_value df_effect df_error N
overall 0.154 0.000 0.421 3.732 2 26 30

Confidence level: 95%

HideShow
#> partial omega^2 = 0.154, 95% CI [0, 0.421]. This is the *partial* omega^2,
#> which treats the covariate as extrinsic, so it is not the book's intrinsic
#> value of .12 from Equation 9.31 (p. 471): Equation 9.31 puts SS_total in the
#> denominator, whereas the partial version removes the covariate's variance
#> from it. The lower limit is 0 because the observed F does not exceed the
#> lower critical value -- which is exactly the information a point estimate
#> alone hides.

To calculate Cohen’s dd for specific group comparisons (standardized mean differences), we divide the difference between the adjusted means by the within-group standard deviation from a model that omits the covariate (the standard ANOVA model).d=Y‾l′−Y‾m′MSWd = \frac{\bar{Y}'_l - \bar{Y}'_m}{\sqrt{MS_W}}

(Equation 9.32)

HideShow
# Extract MS_W (Mean Square Within/Error) from the standard ANOVA model
MS_W <- anova_standard["Residuals", "Sum Sq"] / anova_standard["Residuals", "Df"]
SD_within <- sqrt(MS_W)
cat("MS_W:", round(MS_W, 2), " SD_within:", round(SD_within, 2), "\n")
HideShow
MS_W: 39.62  SD_within: 6.29 
HideShow
#> MS_W = 39.62, sqrt(MS_W) = 6.29 — matches book p. 471

# Extract the adjusted means we calculated earlier using emmeans
adj_means_df <- as.data.frame(Adjusted_Means)
mean_SSRI <- adj_means_df$emmean[adj_means_df$Group == "SSRI"]
mean_WaitList <- adj_means_df$emmean[adj_means_df$Group == "Wait List"]

# Calculate Cohen's d comparing Wait List to SSRI
cohens_d <- (mean_WaitList - mean_SSRI) / SD_within
cat("Cohen's d (Wait List vs SSRI):", round(cohens_d, 2), "\n")
HideShow
Cohen's d (Wait List vs SSRI): 1.02 
HideShow
#> d = 1.02 from the unrounded adjusted means. The book reports 1.03 (p. 472)
#> from the rounded adjusted means, (14.0 - 7.5)/6.29 = 1.03; the difference is
#> entirely the rounding of the adjusted means.

A dd of about 1.0 indicates that the adjusted mean for the Wait List group is roughly a full standard deviation higher (more depressed) than the adjusted mean for the SSRI group.

In DMAR

The book reports a 95% confidence interval of [0.214, 1.815] (p. 472). DMAR’s ci_sc_ancova() uses the adjusted means, group sizes, contrast weights, and covariate summaries given in endnote 7 (p. 523), along with the ANOVA and ANCOVA residual standard deviations.

HideShow
# Within-group sum of squares on the covariate, from the ANOVA of Pre on Group.
SSwithin_Pre <- sum(residuals(lm(Pre ~ Group, data = chapter_9_table_7))^2)
SSwithin_Pre
HideShow
[1] 752.5
HideShow
#> 752.5 — matches the SSwithin.x value in the book's endnote 7, p. 523

# s_ancova is the root mean square error of the ANCOVA full model; s_anova is
# the sqrt(MS_W) computed above. We round both to the book's endnote values.
c(s_anova = SD_within,
  s_ancova = sqrt(sum(resid(Beck_ANCOVA_Model)^2) / Beck_ANCOVA_Model$df.residual))
HideShow
 s_anova s_ancova 
6.294324 5.393496 
HideShow
#> 6.294 and 5.393 — the two standard deviations used in the book's endnote 7

ci_sc_ancova(
  adj_means    = c(7.54, 11.98, 13.98),      # adjusted means, from emmeans
  s_anova      = 6.294,                      # sqrt(MS_W), the standardizer
  s_ancova     = 5.393,                      # sqrt(MS error) of the ANCOVA
  c_weights    = c(-1, 0, 1),                # Wait List minus SSRI
  n_per_group  = c(10, 10, 10),
  cov_means    = c(17, 17.7, 17.4),          # pretest means, Table 9.7
  SS_within_x  = 752.5,
  standardizer = "s_anova",
  conf_level   = 0.95
)
term value
ci_lower 0.214
std_contrast 1.023
ci_upper 1.815

Confidence level: 95%

HideShow
#> standardized contrast 1.023 with a 95% CI of [0.214, 1.815] — matches book
#> p. 472. The interval is wide, spanning most of the plausible range for a
#> standardized difference; what it does establish is that the effect is
#> nonzero. That width is precisely the book's point in reporting it.
9.4.7 — Comparisons among Adjusted Group Means

When the overall ANCOVA is significant, we typically want to perform specific pairwise comparisons between the adjusted means. Because we are making multiple comparisons, we need to adjust our confidence intervals and pp-values to control the familywise error rate (e.g., using a Tukey adjustment).

The textbook provides SAS output (Table 9.10) showing the simultaneous 95% confidence intervals for all pairwise comparisons using the Tukey adjustment. We can replicate this using the emmeans object we created earlier.

HideShow
# Table 9.10
Pairwise_Comparisons <- pairs(Adjusted_Means, adjust = "tukey")

# Show the simultaneous 95% confidence intervals for those differences
confint(Pairwise_Comparisons)
HideShow
 contrast            estimate   SE df lower.CL upper.CL
 SSRI - Placebo         -4.45 2.42 26   -10.45    1.555
 SSRI - Wait List       -6.44 2.41 26   -12.44   -0.445
 Placebo - Wait List    -1.99 2.41 26    -7.99    4.002

Confidence level used: 0.95 
Conf-level adjustment: tukey method for comparing a family of 3 estimates 
HideShow
#> matches book p. 474 (Table 9.10, simultaneous 95% Tukey limits):
#> SSRI - Placebo:    -4.448, [-10.451,  1.555]
#> SSRI - Wait List:  -6.442, [-12.439, -0.445]
#> Placebo - Wait:    -1.994, [ -7.989,  4.002]

Looking at the output above, we can conclude:

  • SSRI vs. Placebo: The estimated difference is -4.45 points, but the 95% CI ranges from -10.45 to 1.55. Because this interval contains zero, the difference is not statistically significant.

  • SSRI vs. Wait List: The estimated difference is -6.44. The CI ranges from -12.44 to -0.45. Because this interval does not contain zero, we can infer that the SSRI truly lowers depression scores (by an estimated 6.44 points) compared to the waitlist control.

  • Placebo vs. Wait List: The interval (-7.99 to 4.00) contains zero, so this difference is not significant.

In DMAR

The textbook also discusses the Bryant-Paulson approach, which treats the covariate as a random effect rather than fixed, and notes (p. 474) that at the time of writing no major statistical package provided its critical values — so the book derives the interval by hand, pulling an estimated standard error of 2.41 out of Table 9.10 and interpolating a critical value of 3.59 from Appendix Table A.8. DMAR supplies both pieces directly, which is the one thing emmeans cannot do here.

HideShow
# The Bryant-Paulson critical value for alpha = .05, 3 groups, 26 df,
# 1 covariate -- the value the book interpolates from Appendix Table A.8.
cv_bryant_paulson(alpha_level = 0.05, df = 26, n_groups = 3,
                  n_covariates = 1, procedure = "tukey")
term value area_less area_greater
upper_cv 3.586 0.950 0.050
HideShow
#> 3.586 — matches the book's interpolated 3.59 (p. 474)

# The Bryant-Paulson simultaneous interval for SSRI minus Placebo.
ci_c_ancova_bp(
  adj_means      = summary(Adjusted_Means)$emmean,
  s_ancova       = sqrt(sum(resid(Beck_ANCOVA_Model)^2) /
                        Beck_ANCOVA_Model$df.residual),
  c_weights      = c(1, -1, 0),             # SSRI minus Placebo
  n_per_group    = c(10, 10, 10),
  n_covariates   = 1,
  df             = 26,
  conf_level     = 0.95,
  contrast_type  = "pairwise"
)
contrast estimate ci_lower ci_upper
contrast_1 -4.448 -10.564 1.668

Confidence level: 95%

HideShow
#> -4.448, [-10.564, 1.668] — matches the book's hand computation of
#> -10.57 to 1.67 (p. 474), and is wider than the Tukey interval above,
#> as the book says it should be.
9.4.8 — Generalizations of the ANCOVA Model

The basic ANCOVA model can be easily generalized to accommodate more complex research designs. While the textbook does not provide a new dataset for these, the standard R syntax using the lm() function for possible generalized models is below.

Multiple covariates (Section 9.4.8.1, Equation 9.43): if you have a second covariate (ZZ), you simply add it to the model formula.

HideShow
# Syntax template for multiple covariates (X and Z)

# Model_Multiple <- lm(Y ~ Group + X + Z, data = my_data)
# car::Anova(Model_Multiple, type = "III")

Nonlinear relationships (Section 9.4.8.2, Equation 9.45): if you suspect the relationship between the covariate and the dependent variable is curvilinear (quadratic), you can add a squared term for the covariate (X2X^2) to the model.

HideShow
# Syntax template for a quadratic covariate relationship

# Model_Quadratic <- lm(Y ~ Group + X + I(X^2), data = my_data)

Multifactor studies (Section 9.4.8.3): you can combine a factorial ANOVA (multiple independent variables) with a covariate.

HideShow
# Syntax template for a two-way ANCOVA (Factors A and C, plus Covariate X)
# Model_Factorial <- lm(Y ~ Factor_A * Factor_C + X, data = my_data)
9.4.9 — Choosing Covariates in Randomized Designs

Choosing which covariates to include should ideally be done in the design phase, not by sifting through the data (which inflates Type I error).

Raab, Day, and Sales (2000) offer a mathematical heuristic to decide if adding covariates is worth the loss in degrees of freedom. For comparing two groups, rr additional covariates will increase power and precision if:r<R2(N−b−2)r < R^2(N - b - 2)

(Equation 9.48)

We can code the textbook’s hypothetical numerical examples to demonstrate this threshold.

HideShow
# Example 1: One covariate (r=1) that correlates .40 with Y, N = 50, b = 0.
N <- 50
b <- 0
r_covariates <- 1
R_squared <- 0.40^2  # 0.16

threshold <- R_squared * (N - b - 2)

cat("Example 1 Threshold:", threshold, "\n")
HideShow
Example 1 Threshold: 7.68 
HideShow
cat("Should we include? ", r_covariates < threshold)
HideShow
Should we include?  TRUE
HideShow
#> threshold = 7.68 — matches book p. 477: "r here is only 1, which is less
#> than 7.68 [i.e., (.40^2)(48)]"
HideShow
# Example 2: Two covariates (r=2) that together explain 20% of the variance in Y,
# N = 50, b = 0.

r_covariates_2 <- 2
R_squared_2 <- 0.20

threshold_2 <- R_squared_2 * (N - b - 2)

cat("Example 2 Threshold:", threshold_2, "\n")
HideShow
Example 2 Threshold: 9.6 
HideShow
cat("Should we include? ", r_covariates_2 < threshold_2)
HideShow
Should we include?  TRUE
HideShow
#> threshold = 9.6 — matches book p. 477: "2 is less than 9.6"
9.4.10 — Sample Size Planning and Power Analysis in ANCOVA

Including a covariate in a randomized design reduces the unexplained error variance, which increases your effect size and power. The unexplained error variance in ANCOVA is related to the ANOVA error variance by the following formula:σε(ANCOVA)2=σε(ANOVA)2(1−ρ2)\sigma^2_{\varepsilon(\text{ANCOVA})} = \sigma^2_{\varepsilon(\text{ANOVA})}(1-\rho^2) (Equation 9.49)

Where ρ\rho is the population correlation between the covariate and the dependent variable. Because the error variance is smaller, the standardized effect size (ff) becomes larger:fANCOVA=fANOVA1−ρ2f_{\text{ANCOVA}} = \frac{f_{\text{ANOVA}}}{\sqrt{1-\rho^2}}

We can use R to replicate the textbook’s power analysis example. The book assumes a 3-group design with an initial ANOVA effect size of f=0.4082f = 0.4082. We want to see how adding a covariate that correlates at .50 with the dependent variable changes our required sample size to achieve 80% power.

HideShow
# Standard ANOVA Power Analysis
k_groups <- 3
f_anova <- 0.4082
power_target <- 0.80
alpha <- 0.05

anova_power <- pwr.anova.test(k = k_groups, f = f_anova,
                              sig.level = alpha, power = power_target)

# Multiply n per group by number of groups and round up for total N
N_anova <- ceiling(anova_power$n) * k_groups
cat("Total Sample Size Required for ANOVA:", N_anova, "\n")
HideShow
Total Sample Size Required for ANOVA: 63 
HideShow
#> 21 per group, 63 in total — matches book p. 478
HideShow
# ANCOVA Power Analysis (Covariate correlation = .50)
rho <- 0.50
f_ancova <- f_anova / sqrt(1 - rho^2)

cat("Adjusted Effect Size (f) for ANCOVA:", round(f_ancova, 4), "\n")
HideShow
Adjusted Effect Size (f) for ANCOVA: 0.4713 
HideShow
#> f = 0.4713. The book reports 0.4714 (p. 478) because it divides by the
#> rounded sqrt(1 - .5^2) = 0.866; R carries the full precision.

ancova_power <- pwr.anova.test(k = k_groups, f = f_ancova,
                               sig.level = alpha, power = power_target)

# Multiply n per group by number of groups and round up for total N
N_ancova <- ceiling(ancova_power$n) * k_groups
cat("Total Sample Size Required for ANCOVA:", N_ancova, "\n")
HideShow
Total Sample Size Required for ANCOVA: 48 
HideShow
#> 16 per group, 48 in total — matches book p. 479, which reports the same
#> 48 from the SAS GLMPOWER output of Table 9.11

As the output shows, conducting a standard ANOVA requires a total sample size of 63 to achieve 80% power. However, by including a covariate that correlates .50 with the outcome variable, the adjusted effect size increases to about 0.471, and the required sample size drops to 48. ANCOVA allows us to conduct a study with the same statistical power while using nearly 25% fewer participants, which is the book’s conclusion on p. 479.

In DMAR

The pwr analysis above plans for the omnibus effect. When the planning target is a specific contrast among the adjusted means, DMAR supplies dedicated planners that pwr does not have. The accuracy-in-parameter-estimation (AIPE) planner ss_aipe_sc_ancova() solves for the sample size needed so that the confidence interval on a standardized ANCOVA contrast is no wider than a target width, given the covariate-outcome correlation.

HideShow
# Plan n so the 95% CI on a standardized contrast is at most 0.3 wide,
# for a contrast comparing group 1 against the average of groups 2 and 3,
# with a covariate correlating 0.6 with the outcome.
ss_aipe_sc_ancova(
  true_std_contrast = 0.5,
  c_weights         = c(1, -0.5, -0.5),
  width             = 0.3,
  true_cor          = 0.6,
  conf_level        = 0.95
)
term value
necessary_n_per_group 264

Confidence level: 95%

If instead the parameter of interest is the covariate-outcome partial correlation itself, ss_aipe_partial_r() returns the NN needed for a target CI width. As above, p = 3 because a three-level grouping factor contributes two dummy predictors alongside the covariate.

HideShow
ss_aipe_partial_r(true_cor = 0.6, p = 3, width = 0.15, conf_level = 0.95)
term value
necessary_N 283
expected_width 0.150
true_cor 0.600
p 3
width 0.150
conf_level 0.950

Confidence level: 95%

And for a power-analytic (rather than precision-analytic) target on a contrast, ss_power_contrast() returns the per-group and total sample size, the achieved power, and the implied standardized effect size ff. ANCOVA’s gain in power is captured by supplying the residual (covariate-adjusted) error variance.

HideShow
ss_power_contrast(
  c_weights      = c(1, -0.5, -0.5),
  true_means     = c(10, 8, 8),
  true_var_error = 4,
  desired_power  = 0.80,
  alpha_level    = 0.05
)
term value
necessary_n_per_group 13
total_N 39
actual_power 0.817
noncentral_t_parm 2.944
true_f 0.471

9.5 — Alternate Methods of Analyzing Designs with Concomitant Variables

While ANCOVA is generally the most flexible and powerful approach, it is worth understanding other methods often seen in the literature. The book considers four: the ANOVA of residuals, the analysis of gain scores, blocking, and propensity score matching.

9.5.1 — ANOVA of Residuals

This method involves regressing the dependent variable on the covariate, extracting the residuals, and then running an ANOVA on those residuals.

Recommendation: As the textbook notes (p. 480), this strategy should be avoided. Maxwell, Delaney, and Manheimer (1985) showed that it results in parameter estimates that are not least squares estimates for the model being fitted, so the test statistic is not appropriately distributed.

9.5.2 — Gain Scores

When the covariate and the dependent variable are measured on the exact same scale (e.g., a pretest and a posttest), you can calculate a difference score for each subject:Dij=Yij−XijD_{ij} = Y_{ij} - X_{ij}

You can then run a standard ANOVA on these gain scores. Let’s look at how to do this in R using the hypothetical dataset from Table 9.1. In this dataset, X represents our pre-measure, Y represents our post-measure, and we want to see if the amount of change differs between the two groups.

HideShow
Table_9_1 <- chapter_9_table_1

# 1. Ensure Group is treated as a categorical factor
Table_9_1$Group <- as.factor(Table_9_1$Group)

# 2. Calculate the Gain Score (Posttest Y - Pretest X)
Table_9_1$Gain <- Table_9_1$Y - Table_9_1$X

# 3. Run a standard ANOVA on the Gain Scores
Gain_Model <- lm(Gain ~ Group, data = Table_9_1)
car::Anova(Gain_Model, type = "III")
HideShow
Anova Table (Type III tests)

Response: Gain
            Sum Sq Df F value  Pr(>F)  
(Intercept)     75  1   18.75 0.01235 *
Group           24  1    6.00 0.07048 .
Residuals       16  4                  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The ANOVA table tests whether the average change from XX to YY is significantly different between Group 1 and Group 2. If the Group effect is significant (p<.05p < .05), it means one group experienced a statistically larger gain (or drop) than the other.

In a randomized study, ANCOVA and an ANOVA on gain scores test the exact same null hypothesis (book p. 481, Equations 9.54 and 9.55). However, ANCOVA is almost always preferred because it is more powerful and precise: as the book shows on p. 482, the ANCOVA error variance is σε2(1−ρ2)\sigma^2_{\varepsilon}(1-\rho^2) (Equation 9.49) while the gain-score error variance is 2σε2(1−ρ)2\sigma^2_{\varepsilon}(1-\rho) (Equation 9.56), and 1−ρ21-\rho^2 is always smaller than 2(1−ρ)2(1-\rho) except in the unrealistic case ρ=1\rho = 1.

Lord’s Paradox (Figure 9.8)

With intact (nonrandomized) groups, the gain-score and ANCOVA answers can disagree sharply. Lord’s (1967) hypothetical example, which the book presents on pp. 482-484 with the scatterplots of Figure 9.8 (p. 483), imagines weighing male and female students at the start and end of an academic year. Within each sex the weight distribution is unchanged over the year, so the mean gain is zero for both groups and an analysis of gain scores finds no effect. ANCOVA, however, asks a different question: for students who started at the same weight, do the sexes differ at the end? The within-group regression lines (the ANCOVA full-model predictions, dashed) are clearly separated vertically, so ANCOVA reports a sex effect. The discrepancy between the two answers is the paradox.

The book presents this example conceptually rather than from a stored data set, so the points below are simulated to match its structure: equal-variance initial and final weights with a within-sex correlation below 1 (producing regression toward the group mean) and means held constant from start to finish. The group means of 120 and 160 pounds are the ones the book uses on p. 483. The solid line is the line of no change, where final weight equals initial weight.

HideShow
# Hypothetical Lord (1967) data. Each sex keeps the same mean and variance from
# initial to final weight; the within-sex correlation (rho) is below 1, so the
# regression of final on initial slopes less than 1 (regression toward the mean).
set.seed(113)
make_sex <- function(mean_weight, n, sd_weight = 12, rho = 0.7) {
  initial <- rnorm(n, mean_weight, sd_weight)
  final   <- mean_weight + rho * (initial - mean_weight) +
             rnorm(n, 0, sd_weight * sqrt(1 - rho^2))
  data.frame(Initial = initial, Final = final)
}
lord <- dplyr::bind_rows(
  cbind(make_sex(120, 60), Sex = "Female students"),
  cbind(make_sex(160, 60), Sex = "Male students")
)
lord$Sex <- factor(lord$Sex, levels = c("Female students", "Male students"))

# ANCOVA full model: parallel within-group lines, separated by the Sex effect.
lord_ancova <- lm(Final ~ Initial + Sex, data = lord)
b_lord  <- coef(lord_ancova)[["Initial"]]
int_f   <- coef(lord_ancova)[["(Intercept)"]]
int_m   <- int_f + coef(lord_ancova)[["SexMale students"]]
x_lord  <- range(lord$Initial)

ggplot(lord, aes(Initial, Final, color = Sex, shape = Sex)) +
  geom_abline(slope = 1, intercept = 0, color = "gray45", linewidth = 0.8) +
  geom_point(size = 2.2, alpha = 0.85) +
  annotate("segment", x = x_lord[1], xend = x_lord[2],
           y = int_f + b_lord * x_lord[1], yend = int_f + b_lord * x_lord[2],
           color = "#F8766D", linewidth = 1, linetype = "dashed") +
  annotate("segment", x = x_lord[1], xend = x_lord[2],
           y = int_m + b_lord * x_lord[1], yend = int_m + b_lord * x_lord[2],
           color = "#00BFC4", linewidth = 1, linetype = "dashed") +
  scale_color_manual(values = c("Female students" = "#F8766D",
                                "Male students" = "#00BFC4")) +
  scale_shape_manual(values = c("Female students" = 16, "Male students" = 17)) +
  labs(title = "Figure 9.8. Scatterplots of initial and final weights for male and female students (after Lord, 1967)",
       x = "Initial weight (pounds)", y = "Final weight (pounds)",
       color = NULL, shape = NULL) +
  theme(legend.position = "top")
Figure 9.8. Scatterplots of initial and final weights for male and female students, after Lord (1967). Dashed lines are the ANCOVA full-model predictions for each group; the solid line marks no change in weight.

Figure 9.8. Scatterplots of initial and final weights for male and female students, after Lord (1967). Dashed lines are the ANCOVA full-model predictions for each group; the solid line marks no change in weight.

9.5.3 — Blocking

Blocking (or stratification) is an alternative to ANCOVA. Instead of treating the concomitant variable (like age) as a continuous covariate, you split the participants into discrete categories or “blocks” (e.g., 60s, 70s, 80s) and then randomly assign treatments within those blocks. The full model for a randomized block design is essentially a two-way ANOVA: Yijk=μ+αj+βk+αβjk+εijkY_{ijk} = \mu + \alpha_j + \beta_k + \alpha\beta_{jk} + \varepsilon_{ijk} (Equation 9.57)

Where αj\alpha_j is the treatment effect, βk\beta_k is the block effect, and αβjk\alpha\beta_{jk} is their interaction.

To see how a Randomized Block analysis compares to both a standard ANOVA and an ANCOVA, let’s recreate the data from Table 9.12. This dataset represents older adults categorized into three age blocks, assigned to three motor-control tasks, with the number of errors (Y) as the dependent variable and exact age (X) as the continuous covariate.

HideShow
# Pull in data with AMCP package
data("chapter_9_table_12")
head(chapter_9_table_12)
HideShow
  Block Task  X  Y
1     1    1 60 14
2     1    1 69 24
3     1    2 62 10
4     1    2 66 16
5     1    3 63 19
6     1    3 67 25
HideShow
# Ensure the grouping variables are treated as categorical factors
chapter_9_table_12$Task <- as.factor(chapter_9_table_12$Task)
chapter_9_table_12$Block <- as.factor(chapter_9_table_12$Block)

The cell and marginal means reproduce the summary table printed underneath the data in Table 9.12. Note how little the three Task conditions differ on the covariate: that is what the restricted randomization within blocks bought.

HideShow
chapter_9_table_12 |>
  group_by(Block, Task) |>
  summarise(mean_X = mean(X), mean_Y = mean(Y), .groups = "drop")
HideShow
# A tibble: 9 × 4
  Block Task  mean_X mean_Y
  <fct> <fct>  <dbl>  <dbl>
1 1     1       64.5     19
2 1     2       64       13
3 1     3       65       22
4 2     1       75       21
5 2     2       74.5     26
6 2     3       74.5     33
7 3     1       83.5     38
8 3     2       85       44
9 3     3       86.5     47
HideShow
#> cell means match book p. 486 (Table 9.12, "Cell and Marginal Means")

chapter_9_table_12 |>
  group_by(Task) |>
  summarise(mean_X = mean(X), mean_Y = mean(Y), .groups = "drop")
HideShow
# A tibble: 3 × 3
  Task  mean_X mean_Y
  <fct>  <dbl>  <dbl>
1 1       74.3   26  
2 2       74.5   27.7
3 3       75.3   34  
HideShow
#> Task marginals 74.33 / 26.00, 74.50 / 27.67, 75.33 / 34.00 — matches
#> book p. 486 (Table 9.12)

The textbook demonstrates the difference in statistical sensitivity by running three different models on the exact same data. We can replicate this in R.

  1. Standard One-Way ANOVA

If we simply look at the Task effect and ignore the age of the participants, the unexplained variance (error) is massive.

HideShow
Model_ANOVA <- lm(Y ~ Task, data = chapter_9_table_12)
car::Anova(Model_ANOVA, type = "III")
HideShow
Anova Table (Type III tests)

Response: Y
            Sum Sq Df F value   Pr(>F)    
(Intercept) 4056.0  1 26.8807 0.000111 ***
Task         213.8  2  0.7084 0.508186    
Residuals   2263.3 15                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Task SS = 213.78, F = 0.71, p = .508; Error SS = 2263.33 — matches book
#> p. 486 (Table 9.13, "Source Table for ANOVA")
  1. Randomized Block Design

If we use our discrete “Block” factor, we account for a lot of the variance caused by age, shrinking the error term.

HideShow
Model_Block <- lm(Y ~ Task * Block, data = chapter_9_table_12)
car::Anova(Model_Block, type = "III")
HideShow
Anova Table (Type III tests)

Response: Y
            Sum Sq Df F value   Pr(>F)    
(Intercept) 722.00  1 28.2522 0.000484 ***
Task         84.00  2  1.6435 0.246372    
Block       436.00  2  8.5304 0.008359 ** 
Task:Block   99.56  4  0.9739 0.467627    
Residuals   230.00  9                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The book’s “Source Table for Randomized Block Design” in Table 9.13 is built from sequential (Type I) sums of squares, which for this equal-nn design partition the total orthogonally into Task, Block, Task × Block, and Error. The Type III table above gives different main-effect sums of squares because, with the interaction in the model, a Type III main effect is tested after the interaction and its value depends on how the factors are coded. To reproduce the book’s randomized-block source table, use the sequential anova():

HideShow
anova(Model_Block)
HideShow
Analysis of Variance Table

Response: Y
           Df  Sum Sq Mean Sq F value    Pr(>F)    
Task        2  213.78  106.89  4.1826   0.05194 .  
Block       2 1933.78  966.89 37.8348 4.162e-05 ***
Task:Block  4   99.56   24.89  0.9739   0.46763    
Residuals   9  230.00   25.56                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> matches book p. 486 (Table 9.13, "Source Table for Randomized Block
#> Design"):
#> Task        SS =  213.78, MS = 106.89, F =  4.18, p = .052
#> Block       SS = 1933.78, MS = 966.89, F = 37.83, p = .001
#> Task:Block  SS =   99.56, MS =  24.89, F =  0.97, p = .468
#> Error       SS =  230.00, MS =  25.56
#> The book's table carries p to three decimals, so the Block effect appears
#> there as .001; R prints its exact value, 4.16e-05.

That sequential source table reads more clearly as an APA-style gt table. Partial η2\eta^2 is each effect’s share of effect-plus-error variance:

HideShow
block_seq <- anova(Model_Block)
ss_res_block <- block_seq["Residuals", "Sum Sq"]   # error SS, for partial eta^2
block_seq |>
  as.data.frame() |>
  tibble::rownames_to_column("Source") |>
  dplyr::transmute(
    Source = dplyr::recode(Source,
               "Task" = "Task (A)", "Block" = "Block (B)",
               "Task:Block" = "Task x Block (AB)", "Residuals" = "Error"),
    SS = `Sum Sq`, df = Df, MS = `Mean Sq`,
    Fstat = `F value`, p = `Pr(>F)`,
    # No partial eta^2 for the error line itself.
    peta = dplyr::if_else(Source == "Error", NA_real_,
                          `Sum Sq` / (`Sum Sq` + ss_res_block))
  ) |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("Randomized Block Design for Number of Errors"),
             subtitle = md("The randomized-block portion of the book's Table 9.13 (p. 486), reformatted")) |>
  cols_align(align = "center", columns = -Source)
Randomized Block Design for Number of Errors
The randomized-block portion of the book’s Table 9.13 (p. 486), reformatted
Source SS df MS F p Partial η2
Task (A) 213.78 2 106.89 4.18 0.0519 0.482
Block (B) 1,933.78 2 966.89 37.83 0.0000 0.894
Task x Block (AB) 99.56 4 24.89 0.97 0.4676 0.302
Error 230.00 9 25.56


  1. ANCOVA

Instead of artificially grouping ages into decades, ANCOVA uses the exact continuous age (X) of every participant.

HideShow
Model_ANCOVA <- lm(Y ~ Task + X, data = chapter_9_table_12)
car::Anova(Model_ANCOVA, type = "III")
HideShow
Anova Table (Type III tests)

Response: Y
             Sum Sq Df  F value    Pr(>F)    
(Intercept) 1011.54  1  69.8023 8.234e-07 ***
Task         152.04  2   5.2459   0.01994 *  
X           2060.45  1 142.1828 1.015e-08 ***
Residuals    202.88 14                       
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> matches book p. 486 (Table 9.13, "Source Table for ANCOVA"):
#> Task SS = 152.04, MS = 76.02, F = 5.25, p = .020
#> X (within-cell regression) SS = 2060.45, F = 142.18, p = .001
#> Error SS = 202.88, MS = 14.49
#> As in the randomized-block table, the book shows the within-cell regression
#> p as .001 at three decimals; R prints 1.01e-08.

The three source tables also illustrate the book’s remark (p. 485) that the blocking analysis splits the one-way ANOVA’s error term into three pieces: 1,933.78+99.56+230.00=2,263.331{,}933.78 + 99.56 + 230.00 = 2{,}263.33.

Comparing the outputs above, ANCOVA provides the most powerful test of the Task effect (p=.020p = .020). As the textbook outlines, this happens for two main reasons:

  • Preservation of Data: Blocking forces you to take continuous, precise data (exact age) and degrade it into chunky categories (decades). ANCOVA uses all the quantitative information available, which adjusts the means more accurately.

  • Degrees of Freedom: The randomized block analysis costs a lot of degrees of freedom (you have to estimate parameters for the blocks and the interactions). ANCOVA only uses 1 degree of freedom for the continuous covariate, leaving more degrees of freedom for the error term, which increases statistical power.

9.5.4 — A Different Approach to Matching: Propensity Scores

When random assignment is impossible or unethical (e.g., studying the effects of smoking, or a self-selected treatment), researchers cannot guarantee that the treatment and control groups are equivalent at baseline. Propensity Score Matching (PSM) is a statistical technique that attempts to artificially equate these groups by matching participants based on their probability of receiving the treatment, given a set of observed covariates.

The text outlines the steps for applying PSM (p. 488 ff.). While the book does not provide a data set, we can illustrate the process using a simulated data set.

Let’s simulate a scenario where participants self-select into a Treatment group. Older participants with higher baseline Severity scores are more likely to seek out the treatment. This creates a severe confounding bias.

We will use the MatchIt package in R to perform the matching steps.

HideShow
# Simulate a biased dataset (N = 500)
set.seed(113)
n <- 500
Age <- rnorm(n, mean = 50, sd = 10)
Severity <- rnorm(n, mean = 20, sd = 5)

# Calculate probability of getting Treatment based on Age and Severity
logit_p <- -5 + 0.05 * Age + 0.1 * Severity
prob_assign <- exp(logit_p) / (1 + exp(logit_p))
Treatment <- rbinom(n, size = 1, prob = prob_assign) # 0 = Control, 1 = Treatment

# Create the Outcome (True Treatment effect is +5)
Outcome <- 10 + 5 * Treatment + 0.3 * Age + 0.8 * Severity + rnorm(n, 0, 2)

PSM_Data <- data.frame(Treatment, Age, Severity, Outcome)
head(PSM_Data)
HideShow
  Treatment      Age Severity  Outcome
1         0 51.33355 19.73790 42.07085
2         1 63.75222 26.46395 56.17827
3         0 57.48715 15.66237 39.38256
4         1 37.06149 22.60335 45.63094
5         1 44.41229 19.34045 44.50014
6         1 32.67551 19.53985 40.58952

We use logistic regression to calculate the propensity score, and then match each treated participant to the nearest control participant.

HideShow
# Step 1 & 2: Calculate Propensity Scores and Match

# method = "nearest" performs 1-to-1 nearest neighbor matching
match_model <- matchit(Treatment ~ Age + Severity, data = PSM_Data, method = "nearest")

Before checking the outcome, we must ensure our matching worked. We want the standardized mean differences (analogous to Cohen’s d) between the groups to be as close to 0 as possible (ideally <.10< .10).

HideShow
# Step 3: Check Covariate Balance
summary(match_model)
HideShow

Call:
matchit(formula = Treatment ~ Age + Severity, data = PSM_Data, 
    method = "nearest")

Summary of Balance for All Data:
         Means Treated Means Control Std. Mean Diff. Var. Ratio eCDF Mean
distance        0.4598        0.3632          0.6767     0.9510    0.1835
Age            52.7468       48.3333          0.5122     0.6969    0.1345
Severity       21.4926       19.3094          0.4526     0.9744    0.1324
         eCDF Max
distance   0.2803
Age        0.2580
Severity   0.2126

Summary of Balance for Matched Data:
         Means Treated Means Control Std. Mean Diff. Var. Ratio eCDF Mean
distance        0.4598        0.4296          0.2115     1.2733    0.0536
Age            52.7468       51.6218          0.1306     0.8512    0.0487
Severity       21.4926       20.8087          0.1418     1.1241    0.0487
         eCDF Max Std. Pair Dist.
distance   0.1443          0.2125
Age        0.1294          0.9556
Severity   0.1045          0.8943

Sample Sizes:
          Control Treated
All           299     201
Matched       201     201
Unmatched      98       0
Discarded       0       0

Before matching, the Std. Mean Diff. is 0.51 for Age and 0.45 for Severity: the self-selected Treatment group is substantially older and more severe at baseline, exactly the confounding we built in. After 1-to-1 nearest-neighbor matching, Age falls to 0.13 and Severity to 0.14 — a large improvement, though still above the 0.10 rule of thumb, which is one reason to keep adjusting for the covariates in the outcome model. All 201 treated participants were matched to 201 of the 299 controls, leaving 98 controls unmatched.

Once the groups are better balanced, we extract the matched participants and run our final analysis. As recommended by the text, we run an ANCOVA including the original covariates to clean up any residual imbalance and increase statistical power.

HideShow
# Extract the matched dataset (this will drop unmatched participants)
matched_data <- match.data(match_model)

# Run the final ANCOVA on the matched data
Final_ANCOVA <- lm(Outcome ~ Treatment + Age + Severity, data = matched_data)
car::Anova(Final_ANCOVA, type = "III")
HideShow
Anova Table (Type III tests)

Response: Outcome
            Sum Sq  Df F value    Pr(>F)    
(Intercept)  623.7   1  159.80 < 2.2e-16 ***
Treatment   2810.4   1  720.12 < 2.2e-16 ***
Age         2892.8   1  741.22 < 2.2e-16 ***
Severity    5305.8   1 1359.49 < 2.2e-16 ***
Residuals   1553.3 398                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The treatment effect is highly significant (unsurprising as this data was simulated). Because we performed this analysis on the matched dataset, we can be much more confident that this difference is driven by the treatment itself, rather than the severe baseline bias we started with.

9.10 — Extension: Heterogeneity of Regression

9.10.1 — Test for Heterogeneity of Regression

To test for heterogeneity of regression, we compare a Restricted Model (the standard ANCOVA assuming equal slopes) against a Full Model (which allows the slope parameter to vary by group).The Full Model (ANCOHET) is written as:Yij=μ+αj+βjXij+ϵijY_{ij} = \mu + \alpha_j + \beta_j X_{ij} + \epsilon_{ij} Notice the subscript jj on the slope parameter β\beta. This model fits a different intercept and a different slope for each group. The test for heterogeneity simply assesses whether this Full Model has significantly less error than the Restricted Model (βXij\beta X_{ij} without the subscript).

Here we show how to perform ANCOVA with heterogeneous slopes on the book’s Table 9E.1 data (p. 501), which modifies the Table 9.1 data so that the two groups keep the same means and the same pooled slope while the slope in Group 2 becomes much steeper. Note that we use Type III Sums of Squares (using Anova() from the car package).

HideShow
data(chapter_9_extension_table_1)
chapter_9_extension_table_1
HideShow
  Group X  Y
1     1 1  5
2     1 2  9
3     1 3  7
4     2 3 11
5     2 4 11
6     2 5 17
HideShow
#> X = 1, 2, 3 / 3, 4, 5 and Y = 5, 9, 7 / 11, 11, 17 — matches book p. 501
#> (Table 9E.1)

# To make the syntax a bit easier, we specify that Group is a grouping variable (i.e., a factor)
chapter_9_extension_table_1$Group <- as.factor(chapter_9_extension_table_1$Group)

# ANOVA Model (No covariate)
ANOVA_model <- lm(Y ~ Group, data=chapter_9_extension_table_1)
Anova(ANOVA_model, type="III")
HideShow
Anova Table (Type III tests)

Response: Y
            Sum Sq Df F value  Pr(>F)  
(Intercept)    147  1  18.375 0.01278 *
Group           54  1   6.750 0.06017 .
Residuals       32  4                  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
summary(ANOVA_model)
HideShow

Call:
lm(formula = Y ~ Group, data = chapter_9_extension_table_1)

Residuals:
         1          2          3          4          5          6 
-2.000e+00  2.000e+00 -1.763e-15 -2.000e+00 -2.000e+00  4.000e+00 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)  
(Intercept)    7.000      1.633   4.287   0.0128 *
Group2         6.000      2.309   2.598   0.0602 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.828 on 4 degrees of freedom
Multiple R-squared:  0.6279,    Adjusted R-squared:  0.5349 
F-statistic:  6.75 on 1 and 4 DF,  p-value: 0.06017
HideShow
# ANCOVA Model (Restricted Model: Homogeneous slopes)
ANCOVA_model <- lm(Y ~ Group + X, data=chapter_9_extension_table_1)
Anova(ANCOVA_model, type="III")
HideShow
Anova Table (Type III tests)

Response: Y
            Sum Sq Df F value Pr(>F)
(Intercept)   6.75  1  1.2656 0.3425
Group         2.40  1  0.4500 0.5504
X            16.00  1  3.0000 0.1817
Residuals    16.00  3               
HideShow
#> Group F = 0.45 and Error SS = 16 — matches book p. 509 ("the ANCOVA test
#> yields F(1,3) = 0.45") and p. 502 (Table 9E.2, E_R = 8 + 8 = 16)
summary(ANCOVA_model)
HideShow

Call:
lm(formula = Y ~ Group + X, data = chapter_9_extension_table_1)

Residuals:
         1          2          3          4          5          6 
 8.586e-16  2.000e+00 -2.000e+00 -9.661e-16 -2.000e+00  2.000e+00 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)    3.000      2.667   1.125    0.342
Group2         2.000      2.981   0.671    0.550
X              2.000      1.155   1.732    0.182

Residual standard error: 2.309 on 3 degrees of freedom
Multiple R-squared:  0.814, Adjusted R-squared:  0.6899 
F-statistic: 6.562 on 2 and 3 DF,  p-value: 0.08025
HideShow
#> b_W = 2 with intercepts a_1 = 3 and a_2 = 5 — matches book p. 502
#> (Table 9E.2)

# ANCOHET Model (Full Model: Heterogeneous slopes)
# The Group*X interaction term allows the slopes to vary
ANCOVA_Heterogeneity_model <- lm(Y ~ Group*X, data=chapter_9_extension_table_1)
Anova(ANCOVA_Heterogeneity_model, type="III")
HideShow
Anova Table (Type III tests)

Response: Y
            Sum Sq Df F value Pr(>F)
(Intercept) 10.714  1  1.7857 0.3132
Group        1.500  1  0.2500 0.6667
X            2.000  1  0.3333 0.6220
Group:X      4.000  1  0.6667 0.5000
Residuals   12.000  2               
HideShow
#> Group:X F = 0.667 on 1 and 2 df, and Error SS = 12 — matches book p. 501,
#> F = (16 - 12)/(3 - 2) / (12/2) = 4/6 = 0.667
summary(ANCOVA_Heterogeneity_model)
HideShow

Call:
lm(formula = Y ~ Group * X, data = chapter_9_extension_table_1)

Residuals:
 1  2  3  4  5  6 
-1  2 -1  1 -2  1 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)    5.000      3.742   1.336    0.313
Group2        -4.000      8.000  -0.500    0.667
X              1.000      1.732   0.577    0.622
Group2:X       2.000      2.450   0.816    0.500

Residual standard error: 2.449 on 2 degrees of freedom
Multiple R-squared:  0.8605,    Adjusted R-squared:  0.6512 
F-statistic: 4.111 on 3 and 2 DF,  p-value: 0.2018
HideShow
#> a_1 = 5 and b_1 = 1; the Group2 offsets give a_2 = 5 - 4 = 1 and
#> b_2 = 1 + 2 = 3 — matches book p. 502 (Table 9E.3)

The two error sums of squares are the book’s ER=16E_R = 16 and EF=12E_F = 12, so the test of heterogeneity of regression is F=(16−12)/1÷12/2=0.667F = (16-12)/1 \div 12/2 = 0.667 (p. 501), which is nowhere near significance. As the book stresses, that is unsurprising with six observations; the point of the example is the arithmetic, not the power.

Because the sums of squares on the covariate are equal in the two groups, the center of accuracy for these data is just the grand mean of XX, and the treatment effect there is the difference between the ANCOVA adjusted means. We can reproduce the book’s Table 9E.4 directly:

HideShow
# Adjusted means from the homogeneous-slopes ANCOVA
emmeans(ANCOVA_model, ~ Group)
HideShow
 Group emmean   SE df lower.CL upper.CL
 1          9 1.76  3     3.39     14.6
 2         11 1.76  3     5.39     16.6

Confidence level used: 0.95 
HideShow
#> 9 and 11, a difference of -2 — matches book p. 510 (Table 9E.4)

# Standard error of the treatment effect at the center of accuracy
# (Equation 9E.28), built from the ANCOHET error variance.
s2_het_9E <- sum(resid(ANCOVA_Heterogeneity_model)^2) /
             ANCOVA_Heterogeneity_model$df.residual
SS_x_within <- sum(resid(lm(X ~ Group, data = chapter_9_extension_table_1))^2)
se_Ca_9E <- sqrt(s2_het_9E * (1/3 + 1/3 + (2 - 4)^2 / SS_x_within))
c(s2_het = s2_het_9E, SS_x_within = SS_x_within, se = se_Ca_9E)
HideShow
     s2_het SS_x_within          se 
   6.000000    4.000000    3.162278 
HideShow
#> s2_het = 6, sum of within-group squares on X = 4, SE = sqrt(10) = 3.16 —
#> matches book p. 510 (Table 9E.4)

# The test itself
c(t = -2 / se_Ca_9E, df = ANCOVA_Heterogeneity_model$df.residual)
HideShow
         t         df 
-0.6324555  2.0000000 
HideShow
#> t(2) = -0.63, nonsignificant — matches book p. 510 (Table 9E.4)

So there is no evidence of heterogeneous slopes here (Group:X is not significant in the ANCOHET model), and whether we evaluate the treatment effect using the standard ANCOVA model or at the center of accuracy in the ANCOHET model, there is no significant treatment effect once the covariate is accounted for.

9.10.2 — Accommodating Heterogeneity of Regression

When slopes are heterogeneous, the distance between the regression lines changes continuously depending on the value of the covariate (XX). Thus, talking about a single “main effect” of treatment becomes complicated. Instead, we want to estimate the treatment effect at specific, meaningful values of the covariate.

Let’s illustrate this using the Pygmalion dataset (Bloomers vs. Controls), predicting the average post-test IQ (AvPost) from the pre-test IQ (IQPre).

HideShow
data(chapter_9_extension_figures_4_and_5)
Pygmalion <- chapter_9_extension_figures_4_and_5
Pygmalion$Treatment <- as.factor(Pygmalion$Treatment)
ANCOVA_Heterogeneity_IQ <- lm(AvPost ~ IQPre*Treatment, data=Pygmalion)
Anova(ANCOVA_Heterogeneity_IQ, type="III")
HideShow
Anova Table (Type III tests)

Response: AvPost
                Sum Sq  Df  F value    Pr(>F)    
(Intercept)       8984   1  68.4661 4.026e-15 ***
IQPre            43650   1 332.6688 < 2.2e-16 ***
Treatment          133   1   1.0144    0.3146    
IQPre:Treatment    277   1   2.1128    0.1471    
Residuals        40151 306                       
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> IQPre:Treatment F = 2.113 on 1 and 306 df, p = .147 — matches book p. 513

# The error variance of the ANCOHET model, s^2_het, is used throughout below.
sum(resid(ANCOVA_Heterogeneity_IQ)^2) / ANCOVA_Heterogeneity_IQ$df.residual
HideShow
[1] 131.2118
HideShow
#> 131.212 — matches book p. 513

The test for heterogeneity of regression is nonsignificant, but as the book explains (p. 513), one may still prefer the model that allows for it, exactly as one keeps an interaction term in the error model of a factorial ANOVA after a nonsignificant interaction test.

Before plotting, we can examine the group descriptives for the outcome and the covariate.

HideShow
# Descriptives for DV
group_by(Pygmalion, Treatment) %>%
summarise(mean_AvPost=mean(AvPost), var_AvPost=var(AvPost), sd_AvPost=sd(AvPost), SS=var(AvPost)*(n()-1))
HideShow
# A tibble: 2 × 5
  Treatment mean_AvPost var_AvPost sd_AvPost     SS
  <fct>           <dbl>      <dbl>     <dbl>  <dbl>
1 0                104.       300.      17.3 73422.
2 1                110.       438.      20.9 27602.
HideShow
# Descriptives for covariate
group_by(Pygmalion, Treatment) %>%
summarise(mean_IQPre=mean(IQPre), var_IQPre=var(IQPre), sd_IQPre=sd(IQPre), n=n())
HideShow
# A tibble: 2 × 5
  Treatment mean_IQPre var_IQPre sd_IQPre     n
  <fct>          <dbl>     <dbl>    <dbl> <int>
1 0               97.8      339.     18.4   246
2 1              101.       382.     19.5    64
HideShow
#> n = 246 Controls and 64 Bloomers, with covariate means 97.8 and 101.2 and
#> within-group sums of squares 83,171.4 and 24,043.8 — matches book p. 513

# The separate within-group regression lines
coef(lm(AvPost ~ IQPre, data = subset(Pygmalion, Treatment == 1)))   # Bloomers
HideShow
(Intercept)       IQPre 
 24.0543105   0.8463595 
HideShow
coef(lm(AvPost ~ IQPre, data = subset(Pygmalion, Treatment == 0)))   # Controls
HideShow
(Intercept)       IQPre 
 32.6912117   0.7244454 
HideShow
#> a_A = 24.05, b_A = .8464 (Bloomers) and a_B = 32.69, b_B = .7244
#> (Controls) — matches book p. 513

To visualize why varying slopes matter, let’s recreate Figure 9E.4 (book p. 513), plotting the distinct regression lines for both groups. When the parallel-slopes assumption is relaxed, each group gets its own slope as well as its own intercept. Using the Pygmalion data (average posttest IQ regressed on pretest IQ for Bloomers and Controls), the heterogeneous-regression model fits two lines that are no longer parallel. The vertical gap between them, which is the estimated treatment effect, now changes with the covariate, so a single “main effect” of treatment is no longer well defined.

HideShow
# A labelled copy of the same Pygmalion data, for the figures.
d9E <- chapter_9_extension_figures_4_and_5
d9E <- d9E |>
  mutate(Treatment = case_when(
    Treatment == 0 ~ "Control",
    Treatment == 1 ~ "Bloomers"
  )) |>
  mutate(Treatment = factor(Treatment, levels = c("Control", "Bloomers")))

# Heterogeneous-regression (ANCOHET) model: slopes differ by group.
het <- lm(AvPost ~ IQPre * Treatment, data = d9E)
HideShow
x_iq <- seq(30, 160, by = 0.5)
het_lines <- dplyr::bind_rows(
  data.frame(IQPre = x_iq, Treatment = factor("Control",  levels = levels(d9E$Treatment))),
  data.frame(IQPre = x_iq, Treatment = factor("Bloomers", levels = levels(d9E$Treatment)))
)
het_lines$AvPost <- predict(het, newdata = het_lines)

ggplot(d9E, aes(IQPre, AvPost, color = Treatment, shape = Treatment)) +
  geom_point(size = 2, alpha = 0.8) +
  geom_line(data = het_lines,
            aes(IQPre, AvPost, color = Treatment, linetype = Treatment),
            linewidth = 1, inherit.aes = FALSE) +
  scale_color_manual(values = c("Control" = "#F8766D",
                                "Bloomers" = "#00BFC4")) +
  scale_shape_manual(values = c("Control" = 1, "Bloomers" = 18)) +
  scale_linetype_manual(values = c("Control" = "solid", "Bloomers" = "dashed")) +
  coord_cartesian(xlim = c(30, 160), ylim = c(60, 180)) +
  labs(title = "Figure 9E.4. Distinct regression lines for both groups (heterogeneity of regression)",
       x = "IQ at start of school year",
       y = "IQ average of mid-year and end-of-year tests",
       color = NULL, shape = NULL, linetype = NULL) +
  theme(legend.position = "top")
Figure 9E.4. Distinct regression lines for the Bloomers and Control groups when slopes are allowed to vary (heterogeneity of regression).

Figure 9E.4. Distinct regression lines for the Bloomers and Control groups when slopes are allowed to vary (heterogeneity of regression).

This shows the prediction at the (grand) mean of the IQ Pretest.

HideShow
To_Predict <- data.frame(IQPre=mean(Pygmalion$IQPre), Treatment=as.factor(c(0, 1)))
predict(ANCOVA_Heterogeneity_IQ, newdata=To_Predict)
HideShow
       1        2 
104.0234 107.3907 

Summary of the covariate, group by group. These are the summary statistics the book lists on p. 513 and uses in all of the formulas that follow.

HideShow
Summary_IV <- group_by(Pygmalion, Treatment) %>%
  summarise(mean_IV=mean(IQPre), var_IV=var(IQPre), sd_IV=sd(IQPre), SS_IV=(n()-1)*var(IQPre), n=n())
Summary_IV
HideShow
# A tibble: 2 × 6
  Treatment mean_IV var_IV sd_IV  SS_IV     n
  <fct>       <dbl>  <dbl> <dbl>  <dbl> <int>
1 0            97.8   339.  18.4 83171.   246
2 1           101.    382.  19.5 24044.    64
HideShow
#> n = 246 / 64, mean_IV = 97.8 / 101.2, SS_IV = 83,171.4 / 24,043.8 —
#> matches book p. 513
The Standard Error of the Treatment Effect at a Given Covariate Value

To test if the predicted difference between groups is significant at a specific value of XX (denote XpX_p), we need to calculate the standard error of the vertical distance between the two lines at that point. The variance of this estimated difference is (Equation 9E.26) :σŶp1−Ŷp22=σ2[1n1+1n2+(Xp−X‾1)2∑(Xi1−X‾1)2+(Xp−X‾2)2∑(Xi2−X‾2)2]\sigma^2_{\hat{Y}_{p1}-\hat{Y}_{p2}} = \sigma^2 \left[ \frac{1}{n_1} + \frac{1}{n_2} + \frac{(X_p-\bar{X}_1)^2}{\sum (X_{i1}-\bar{X}_1)^2} + \frac{(X_p-\bar{X}_2)^2}{\sum (X_{i2}-\bar{X}_2)^2} \right]

Notice that as XpX_p moves further away from the group means, the standard error increases. Our estimate of the treatment effect is most precise near the center of the data.

We can build a custom function in R to calculate this variance for any given point XpX_p:

HideShow
# One way of obtaining summary statistics of interest.
IV_1 <- Summary_IV[Summary_IV$Treatment==0, ]
n_1 <- IV_1$n
SS_IV_1 <- IV_1$SS_IV

IV_2 <- Summary_IV[Summary_IV$Treatment==1, ]
n_2 <- IV_2$n
SS_IV_2 <- IV_2$SS_IV

SS_Residual <- last(Anova(ANCOVA_Heterogeneity_IQ, type="III")$Sum)
df_Residual <- last(Anova(ANCOVA_Heterogeneity_IQ, type="III")$Df)
s_squared <- SS_Residual/df_Residual
HideShow
# Function to calculate the variance of the predicted difference at Xp
s_squared_Y1p_minus_Y2p <- function(Xp, X1, X2, model) {
  n1 <- length(X1)
  n2 <- length(X2)
  Xbar_1 <- mean(X1)
  Xbar_2 <- mean(X2)
  SS1 <- sum((X1-Xbar_1)^2)
  SS2 <- sum((X2-Xbar_2)^2)
  Sq_Diff_Xp_Xbar_1 <- (Xp-Xbar_1)^2
  Sq_Diff_Xp_Xbar_2 <- (Xp-Xbar_2)^2

  SS_Residual <- last(Anova(model, type="III")$Sum)
  df_Residual <- last(Anova(model, type="III")$Df)
  s_squared <- SS_Residual/df_Residual

  return(s_squared*(1/n1 + 1/n2 + Sq_Diff_Xp_Xbar_1/SS1 + Sq_Diff_Xp_Xbar_2/SS2))
}

# Extract the raw IQPre vectors for each group to pass into the function
IV_1_raw <- Pygmalion$IQPre[Pygmalion$Treatment == 0]
IV_2_raw <- Pygmalion$IQPre[Pygmalion$Treatment == 1]

# Example: Standard deviation (standard error) of the difference at Xp = 100
sqrt(s_squared_Y1p_minus_Y2p(Xp=100, X1=IV_1_raw, X2=IV_2_raw, model=ANCOVA_Heterogeneity_IQ))
HideShow
[1] 1.612205
HideShow
# Example: Standard error at the Grand Mean of the covariate
sqrt(s_squared_Y1p_minus_Y2p(Xp=mean(Pygmalion$IQPre), X1=IV_1_raw, X2=IV_2_raw, model=ANCOVA_Heterogeneity_IQ))
HideShow
[1] 1.62013
Center of Accuracy

When dealing with heterogeneous slopes, the precision of our estimated treatment effect changes depending on where we look along the covariate (XX). However, there is a specific point on the XX axis where our estimation is most accurate (i.e., the standard error of the difference is at its absolute minimum).

This point is called the Center of Accuracy (CaC_a, Equation 9E.27). It is calculated as a weighted average of the group means on the covariate, where the weights are the sums of squares of the opposite group.

The book works this test out by hand for the small Table 9E.1 data set in Table 9E.4, which we reproduced in Section 9.10.1 above. Here we apply the same machinery to the much larger Pygmalion data; the book does not print these particular values, so the output below is a companion computation rather than a reproduction.

HideShow
# Isolate the raw covariate vectors to ensure proper mathematical operations
IV_1_raw <- Pygmalion$IQPre[Pygmalion$Treatment == 0]
IV_2_raw <- Pygmalion$IQPre[Pygmalion$Treatment == 1]

# Calculate the Center of Accuracy (C_a)
SS_IV_1 <- sum((IV_1_raw - mean(IV_1_raw))^2)
SS_IV_2 <- sum((IV_2_raw - mean(IV_2_raw))^2)

C_a <- (SS_IV_1 * mean(IV_2_raw) + SS_IV_2 * mean(IV_1_raw)) / (SS_IV_1 + SS_IV_2)
print(paste("Center of Accuracy (C_a) on the Pre-test IQ scale:", round(C_a, 2)))
HideShow
[1] "Center of Accuracy (C_a) on the Pre-test IQ scale: 100.42"
HideShow
# Calculate the Standard Error at C_a
# (Using the custom s_squared_Y1p_minus_Y2p function we built previously)
SE_C_a <- sqrt(s_squared_Y1p_minus_Y2p(Xp = C_a, X1 = IV_1_raw, X2 = IV_2_raw, model = ANCOVA_Heterogeneity_IQ))
print(paste("Standard Error of the difference at C_a:", round(SE_C_a, 3)))
HideShow
[1] "Standard Error of the difference at C_a: 1.612"
HideShow
# Predict the actual Y difference (Treatment Effect) at C_a
# We feed C_a back into our model to get the predicted Post-test IQ for both groups
To_Predict_Ca <- data.frame(IQPre = C_a, Treatment = as.factor(c(0, 1)))
Predicted_Y_at_Ca <- predict(ANCOVA_Heterogeneity_IQ, newdata = To_Predict_Ca)

# Difference = Treatment (1) - Control (0)
Predicted_Diff_Ca <- Predicted_Y_at_Ca[2] - Predicted_Y_at_Ca[1]
print(paste("Predicted Treatment Difference at C_a:", round(Predicted_Diff_Ca, 3)))
HideShow
[1] "Predicted Treatment Difference at C_a: 3.605"
HideShow
# Conduct the t-test (Difference / Standard Error)
t_stat <- Predicted_Diff_Ca / SE_C_a
print(paste("t-statistic:", round(t_stat, 3)))
HideShow
[1] "t-statistic: 2.237"
HideShow
# Calculate the p-value (Degrees of freedom = N - 4 for the ANCOHET model)
df_C_a <- nrow(Pygmalion) - 4
p_val <- 2 * pt(-abs(t_stat), df = df_C_a)
print(paste("p-value:", round(p_val, 4)))
HideShow
[1] "p-value: 0.026"

There is a statistically significant treatment effect at the center of accuracy. Specifically, for students with a Pre-test IQ of approximately 100.42 (the point where our model’s estimation is most precise), being in the treatment group results in a predicted Post-test IQ that is significantly higher—by about 3.6 points—than the control group (t=2.237t = 2.237, p=0.026p = 0.026).

9.10.2.1 — Simultaneous Tests

If we want to test the treatment effect across the entire continuum of the covariate (rather than just at a single point like the Center of Accuracy), we must adjust our critical value to control for the inflated Type I error rate. Potthoff’s (1964) extension of the Johnson-Neyman technique accomplishes this using a simultaneous critical value, W2=2F(2,N−4)W^2 = 2F(2, N-4) (Equation 9E.29).

The critical value itself is a one-liner:

HideShow
# Obtain W^2 for simultaneous regions of significance
N <- nrow(Pygmalion)
W2 <- 2 * qf(.95, df1 = 2, df2 = N - 4)
W2
HideShow
[1] 6.050506
HideShow
#> 6.051 — matches book p. 513, where 2F(2, 306) = 6.051 is the critical value
#> for the simultaneous region. The non-simultaneous value is F(1, 306) = 3.872.
9.10.2.2 — Carrying Out Tests and Determining Regions of Significance

The vertical distance between the two regression lines at a covariate value XX is D(X)=β̂1+β̂3XD(X) = \hat{\beta}_1 + \hat{\beta}_3 X (Equation 9E.34), where β̂1\hat{\beta}_1 is the difference in intercepts and β̂3\hat{\beta}_3 the difference in slopes. It is the estimated treatment effect at that value of the covariate.

HideShow
# Function for the vertical distance D(X) between the regression lines
D_X <- function(ancova_model, Xp) {
  Reg_Coefs <- coef(ancova_model)
  # Calculates difference: Intercept difference + (Slope difference * Xp)
  # Note: The exact names depend on your factor level names in R
  Result <- Reg_Coefs["Treatment1"] + (Reg_Coefs["IQPre:Treatment1"]) * Xp
  return(unname(Result))
}

# Example: Estimated treatment effect at an arbitrary point (X = 100)
D_X(ancova_model = ANCOVA_Heterogeneity_IQ, Xp = 100)
HideShow
[1] 3.554513
HideShow
# Example: Estimated treatment effect at the mean of the covariate
D_X(ancova_model = ANCOVA_Heterogeneity_IQ, Xp = mean(Pygmalion$IQPre))
HideShow
[1] 3.367316

We can verify this vertical distance by using the predict() function, just as we did when plotting the regression lines earlier:

HideShow
# Predict outcomes for both groups at the mean of the covariate
To_Predict_at_Mean <- data.frame(IQPre = mean(Pygmalion$IQPre),
                                 Treatment = as.factor(c(0, 1)))

predictions <- predict(ANCOVA_Heterogeneity_IQ, newdata = To_Predict_at_Mean)
predictions
HideShow
       1        2 
104.0234 107.3907 
HideShow
# The difference between these predictions matches the D(X) output
predictions[2] - predictions[1]
HideShow
       2 
3.367316 

To find the exact bounds where the treatment effect becomes statistically significant (the points where the confidence bands cross zero), we must solve a quadratic equation of the form AX2+2BX+C=0AX^2 + 2BX + C = 0. The roots of this equation (XLLX_{LL} and XULX_{UL}) define our regions of significance.

Here is how we calculate the coefficients (A, B, C) and the boundary limits for the Pygmalion dataset, for both non-simultaneous and simultaneous tests:

HideShow
# 1. Extract necessary summary statistics
n_A <- Summary_IV$n[2] # Bloomers (Treatment = 1)
n_B <- Summary_IV$n[1] # Controls (Treatment = 0)

mean_A <- Summary_IV$mean_IV[2]
mean_B <- Summary_IV$mean_IV[1]

SS_A <- Summary_IV$SS_IV[2]
SS_B <- Summary_IV$SS_IV[1]

# Extract coefficients from the ANCOHET model
# beta_1 = difference in intercepts; beta_3 = difference in slopes
beta_1 <- coef(ANCOVA_Heterogeneity_IQ)["Treatment1"]
beta_3 <- coef(ANCOVA_Heterogeneity_IQ)["IQPre:Treatment1"]

# Extract MSE (s^2_het)
SS_Residual <- last(Anova(ANCOVA_Heterogeneity_IQ, type="III")$Sum)
df_Residual <- last(Anova(ANCOVA_Heterogeneity_IQ, type="III")$Df)
s2_het <- SS_Residual / df_Residual

# Define critical F values for both region types (book p. 513):
# F(1, 306) = 3.872 for the non-simultaneous region,
# W^2 = 2F(2, 306) = 6.051 for the simultaneous region.
F_crit_non_sim <- qf(.95, df1 = 1, df2 = df_Residual)
F_crit_sim <- 2 * qf(.95, df1 = 2, df2 = df_Residual)   # this is W^2

# Function to calculate A, B, C and the limits
JN_Limits <- function(F_crit) {
  A <- beta_3^2 - F_crit * s2_het * (1/SS_A + 1/SS_B)

  B <- beta_1 * beta_3 + F_crit * s2_het * (mean_A/SS_A + mean_B/SS_B)

  C <- beta_1^2 - F_crit * s2_het * (1/n_A + 1/n_B + (mean_A^2)/SS_A + (mean_B^2)/SS_B)

  # Quadratic formula roots
  X_LL <- (-B + sqrt(B^2 - A*C)) / A
  X_UL <- (-B - sqrt(B^2 - A*C)) / A

  # Ensure LL is the smaller value
  limits <- sort(c(X_LL, X_UL))

  return(list(A=A, B=B, C=C, X_LL=limits[1], X_UL=limits[2]))
}

# Calculate Non-Simultaneous Limits
Non_Sim_Results <- JN_Limits(F_crit = F_crit_non_sim)

# Display Non-Simultaneous Limits
cat("--- Non-Simultaneous Region ---\n",
    "A:", round(Non_Sim_Results$A, 6), "\n",
    "B:", round(Non_Sim_Results$B, 6), "\n",
    "C:", round(Non_Sim_Results$C, 6), "\n",
    "Lower Limit (X_LL):", round(Non_Sim_Results$X_LL, 2), "\n",
    "Upper Limit (X_UL):", round(Non_Sim_Results$X_UL, 2), "\n\n")
HideShow
--- Non-Simultaneous Region ---
 A: -0.012376 
 B: 1.682327 
 C: -210.1354 
 Lower Limit (X_LL): 97.22 
 Upper Limit (X_UL): 174.65 
HideShow
# Calculate Simultaneous Limits
Sim_Results <- JN_Limits(F_crit = F_crit_sim)

# Display Simultaneous Limits
cat("--- Simultaneous Region ---\n",
    "A:", round(Sim_Results$A, 6), "\n",
    "B:", round(Sim_Results$B, 6), "\n",
    "C:", round(Sim_Results$C, 6), "\n",
    "Lower Limit (X_LL):", round(Sim_Results$X_LL, 2), "\n",
    "Upper Limit (X_UL):", round(Sim_Results$X_UL, 2), "\n")
HideShow
--- Simultaneous Region ---
 A: -0.027701 
 B: 3.221253 
 C: -370.3309 
 Lower Limit (X_LL): 103.89 
 Upper Limit (X_UL): 128.68 
HideShow
#> Simultaneous region: A = -0.027701, B = 3.221253, C = -370.330863, with
#> limits 103.89 and 128.68 — matches book p. 514, which highlights exactly
#> those two values (103.890812 and 128.682083).
#> Non-simultaneous region: A = -0.012376, B = 1.682327, C = -210.135379,
#> with limits 97.22 and 174.65; the book reports 97.217332 and 174.656206
#> (p. 514). The small differences past the second decimal come from the book
#> computing A, B, and C from the rounded summary statistics printed on
#> p. 513 (97.8, 101.2, 83,171.4, 24,043.8), whereas R carries full precision.

In Figure 9E.5 (book p. 514), the simultaneous confidence band for the predicted posttest IQ difference (Bloomers minus Controls) excludes zero for pretest IQs between 103.89 and 128.68. The dashed curves show the narrower pointwise confidence limits.

HideShow
# Group summaries on the covariate.
iv <- d9E |>
  group_by(Treatment) |>
  summarise(mean_iv = mean(IQPre), ss_iv = (n() - 1) * var(IQPre), n = n(),
            .groups = "drop")
n_A <- iv$n[iv$Treatment == "Bloomers"]; n_B <- iv$n[iv$Treatment == "Control"]
mean_A <- iv$mean_iv[iv$Treatment == "Bloomers"]; mean_B <- iv$mean_iv[iv$Treatment == "Control"]
ss_A <- iv$ss_iv[iv$Treatment == "Bloomers"];   ss_B <- iv$ss_iv[iv$Treatment == "Control"]

# Intercept- and slope-difference coefficients, and the error mean square.
beta_1 <- coef(het)[["TreatmentBloomers"]]        # difference in intercepts
beta_3 <- coef(het)[["IQPre:TreatmentBloomers"]]  # difference in slopes
het_t3 <- car::Anova(het, type = "III")
ss_res <- het_t3["Residuals", "Sum Sq"]
df_res <- het_t3["Residuals", "Df"]
s2_het <- ss_res / df_res

# Critical values: non-simultaneous F and the simultaneous Johnson-Neyman W^2.
Fc_non_sim <- qf(.95, df1 = 1, df2 = df_res)
Fc_sim     <- 2 * qf(.95, df1 = 2, df2 = df_res)

# Solve A X^2 + 2B X + C = 0 for the simultaneous region-of-significance limits.
jn_limits <- function(Fc) {
  A <- beta_3^2 - Fc * s2_het * (1 / ss_A + 1 / ss_B)
  B <- beta_1 * beta_3 + Fc * s2_het * (mean_A / ss_A + mean_B / ss_B)
  C <- beta_1^2 - Fc * s2_het *
       (1 / n_A + 1 / n_B + mean_A^2 / ss_A + mean_B^2 / ss_B)
  sort(c((-B + sqrt(B^2 - A * C)) / A, (-B - sqrt(B^2 - A * C)) / A))
}
sim_limits <- jn_limits(Fc_sim)

# Difference line D(X) and its confidence bands across the covariate range.
x_vals <- seq(50, 190, length.out = 300)
D_x <- beta_1 + beta_3 * x_vals
se_D <- sqrt(s2_het * (1 / n_A + 1 / n_B +
                       (x_vals - mean_A)^2 / ss_A + (x_vals - mean_B)^2 / ss_B))
bands <- data.frame(
  x_vals, D_x,
  non_sim_upper = D_x + sqrt(Fc_non_sim) * se_D,
  non_sim_lower = D_x - sqrt(Fc_non_sim) * se_D,
  sim_upper     = D_x + sqrt(Fc_sim)     * se_D,
  sim_lower     = D_x - sqrt(Fc_sim)     * se_D)

ggplot(bands, aes(x_vals)) +
  geom_ribbon(aes(ymin = sim_lower, ymax = sim_upper),
              fill = "#F8766D", alpha = 0.12) +
  geom_hline(yintercept = 0, color = "gray45", linewidth = 0.6) +
  geom_vline(xintercept = sim_limits, color = "#00BFC4",
             linetype = "dotted", linewidth = 0.9) +
  geom_line(aes(y = sim_upper),     color = "#F8766D", linewidth = 0.7) +
  geom_line(aes(y = sim_lower),     color = "#F8766D", linewidth = 0.7) +
  geom_line(aes(y = non_sim_upper), color = "#F8766D",
            linetype = "dashed", linewidth = 0.7) +
  geom_line(aes(y = non_sim_lower), color = "#F8766D",
            linetype = "dashed", linewidth = 0.7) +
  geom_line(aes(y = D_x), color = "black", linewidth = 1.1) +
  annotate("text", x = sim_limits[1], y = 36,
           label = sprintf("italic(X)[plain(LL)] == %.1f", sim_limits[1]),
           parse = TRUE,
           color = "#00BFC4", hjust = 1.1, size = 3.3) +
  annotate("text", x = sim_limits[2], y = 36,
           label = sprintf("italic(X)[plain(UL)] == %.1f", sim_limits[2]),
           parse = TRUE,
           color = "#00BFC4", hjust = -0.1, size = 3.3) +
  coord_cartesian(xlim = c(50, 190), ylim = c(-20, 40)) +
  labs(title = "Figure 9E.5. Regions of significance (Johnson-Neyman) for the treatment difference",
       x = "IQ at start of school year",
       y = "Predicted treatment difference (Bloomers - Control)")
Figure 9E.5. Regions of significance (Johnson-Neyman) for the treatment difference as a function of pretest IQ. The dotted vertical lines mark where the simultaneous confidence band crosses zero.

Figure 9E.5. Regions of significance (Johnson-Neyman) for the treatment difference as a function of pretest IQ. The dotted vertical lines mark where the simultaneous confidence band crosses zero.

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 9: Designs with Covariates: ANCOVA and Blocking (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

Chapter 10: Designs with Random or Nested Factors

Open the separate reading

Code
Results
On this page

Chapter 10 works out what changes when a factor’s levels are a random sample from a population of levels rather than the particular levels of interest. The chapter’s organizing device is the expected mean square: once the expected value of each mean square is known, the correct denominator for each FF test follows, and the familiar habit of dividing everything by MSWMS_W is revealed as a source of positive bias for the fixed factor in a mixed design. Section 10.3 develops this for completely crossed designs, where the fixed factor is tested against the fixed-by-random interaction. Section 10.4 develops the parallel case for nested designs, where no interaction with the nested factor exists and the fixed effect is instead tested against the pooled variability among the clusters. Both sections close with measures of association strength: ω̂2\widehat\omega^2 for the fixed factor and the intraclass correlation ρI\rho_I for the random ones, each built from variance components recovered from the mean squares.

These notes build on the prior chapters’ R Code and Instructions, where operational aspects of R and the use of many functions are discussed; here we skip what has already been covered there, including how the AMCP data sets are named (see Chapter 1). This chapter uses two of them: chapter_10_table_5 (the ACT training example, a crossed mixed design) and chapter_10_table_9 (the clinical trainee example, a nested design).

HideShow
# Load all of the packages used.
library(dplyr)          # data manipulation
library(ggplot2)        # figures
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(emmeans)        # estimated marginal means and simultaneous confidence intervals
library(lme4)           # fit mixed-effects models
library(lmerTest)       # p-values for lmer fixed effects
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables
library(sjPlot)         # tab_model(): mixed-model tables, including the ICC

10.3 — Designs with Random Factors

10.3.3 — Two-Factor Case

10.3.3.1 — Expected Mean Squares

Table 10.1 makes the problem concrete before any test statistic is computed. Part I of the table gives the population mean ratings of 18 clinical trainees under three therapy modes, arranged so that in the population there is no main effect of either factor: every trainee has an average effectiveness of 4 and every therapy mode has a mean of 4. Part II then takes the three trainees g, k, and r as the sampled “levels” of the random factor. No error component is involved at all; these are population cell means.

HideShow
# Table 10.1, part II: population mean ratings for three therapy modes with
# trainees g, k, and r as the sampled levels of the random factor. The labels
# are written out level by level, so the correspondence is visible rather than
# order-dependent, and factor() is used only to fix the display order.
table_10_1 <- data.frame(
  Therapy = rep(c("Psychodynamic", "Behavioral", "Rogerian"), each = 3),
  Trainee = rep(c("g", "k", "r"), times = 3),
  Mean    = c(4, 2, 3,
              7, 6, 4,
              1, 4, 5)
)
table_10_1$Therapy <- factor(table_10_1$Therapy,
  levels = c("Psychodynamic", "Behavioral", "Rogerian"))

# Marginal means for the fixed factor (therapy mode).
round(tapply(table_10_1$Mean, table_10_1$Therapy, mean), 2)
HideShow
Psychodynamic    Behavioral      Rogerian 
         3.00          5.67          3.33 
HideShow
#> 3.00, 5.67, 3.33 — matches Table 10.1, part II, book p. 536

# Marginal means for the three sampled trainees, and the grand mean.
tapply(table_10_1$Mean, table_10_1$Trainee, mean)
HideShow
g k r 
4 4 4 
HideShow
#> all 4 — matches book p. 536
mean(table_10_1$Mean)
HideShow
[1] 4
HideShow
#> 4 — matches book p. 536

The trainee marginal means are still identical, but the therapy-mode means are not: this particular sample of three trainees makes the behavioral approach look most effective and the psychodynamic approach worst, when in the full population of 18 trainees there is no therapy-mode effect whatsoever. The apparent effect is entirely an artifact of the interaction between the random and the fixed factor, and it is why Table 10.3 shows the expected mean square for the fixed factor AA in a mixed design as σε2+nσαβ2+bnθα2\sigma^2_\varepsilon + n\sigma^2_{\alpha\beta} + bn\theta^2_\alpha rather than σε2+bnθα2\sigma^2_\varepsilon + bn\theta^2_\alpha.

To see what that extra component does to a test statistic, we can add client-level error to the Part II population means and run both candidate FF tests. This simulation is a companion illustration rather than a book computation: the book deliberately bypasses the error component in Table 10.1.

HideShow
# A companion illustration: client ratings around the Table 10.1 population
# means, five clients per trainee-by-mode cell.
set.seed(113)

n_per_cell <- 5
sim_data <- data.frame(
  Therapy    = rep(table_10_1$Therapy, each = n_per_cell),
  Trainee    = rep(table_10_1$Trainee, each = n_per_cell),
  TargetMean = rep(table_10_1$Mean,    each = n_per_cell)
)
sim_data$Rating <- sim_data$TargetMean +
  rnorm(nrow(sim_data), mean = 0, sd = 1.2)

# The crossed model supplies every mean square we need.
sim_model <- aov(Rating ~ Therapy * Trainee, data = sim_data)
sim_table <- as.data.frame(summary(sim_model)[[1]])
sim_table
HideShow
                Df     Sum Sq   Mean Sq    F value       Pr(>F)
Therapy          2  91.937226 45.968613 27.7933266 5.017248e-08
Trainee          2   0.659002  0.329501  0.1992213 8.202657e-01
Therapy:Trainee  4 109.923542 27.480886 16.6153639 8.439692e-08
Residuals       36  59.541993  1.653944         NA           NA
HideShow
ms_therapy_sim     <- sim_table[1, "Mean Sq"]
ms_trainee_sim     <- sim_table[2, "Mean Sq"]
ms_interaction_sim <- sim_table[3, "Mean Sq"]
ms_within_sim      <- sim_table[4, "Mean Sq"]

df_therapy_sim     <- sim_table[1, "Df"]
df_trainee_sim     <- sim_table[2, "Df"]
df_interaction_sim <- sim_table[3, "Df"]
df_within_sim      <- sim_table[4, "Df"]

# The habitual test: MS_A / MS_W, which ignores that the trainees are a sample.
f_incorrect <- ms_therapy_sim / ms_within_sim
p_incorrect <- pf(f_incorrect, df_therapy_sim, df_within_sim, lower.tail = FALSE)

# The mixed-model test: MS_A / MS_AB.
f_correct <- ms_therapy_sim / ms_interaction_sim
p_correct <- pf(f_correct, df_therapy_sim, df_interaction_sim, lower.tail = FALSE)

cat(sprintf("Therapy tested against MS_W  : F(%d, %d) = %.3f, p = %.5f\n",
            df_therapy_sim, df_within_sim, f_incorrect, p_incorrect),
    sprintf("Therapy tested against MS_AB : F(%d, %d) = %.3f, p = %.5f\n",
            df_therapy_sim, df_interaction_sim, f_correct, p_correct),
    sep = "")
HideShow
Therapy tested against MS_W  : F(2, 36) = 27.793, p = 0.00000
Therapy tested against MS_AB : F(2, 4) = 1.673, p = 0.29654

Tested against MSWMS_W, the therapy effect comes out at F=27.79F = 27.79 with p<.0001p < .0001 — a confident conclusion that one therapy is better than another, drawn from a population in which no therapy-mode effect exists. Tested against MSABMS_{AB}, the same data give F=1.67F = 1.67, p=0.297p = 0.297, and the null hypothesis is retained. That is the positive bias of the preceding paragraphs: the within-cell error term is too small because it carries no interaction component, so the ratio is inflated by variability that belongs to these three particular trainees rather than to the therapies.

10.3.3.3 — Selection of Error Terms

Table 10.4 states the choice of denominator for every effect in the three two-factor crossed designs. For the mixed design (factor AA fixed, factor BB random), the error term for AA is MSABMS_{AB}, while BB and ABAB are both tested against MSWMS_W. Applying that table to the simulated trainee data is a matter of pairing each numerator with the right denominator and the right degrees of freedom.

HideShow
# Table 10.4, mixed design: A against MS_AB; B and AB against MS_W.
f_trainee_sim   <- ms_trainee_sim / ms_within_sim
p_trainee_sim   <- pf(f_trainee_sim, df_trainee_sim, df_within_sim,
                      lower.tail = FALSE)

f_interact_sim  <- ms_interaction_sim / ms_within_sim
p_interact_sim  <- pf(f_interact_sim, df_interaction_sim, df_within_sim,
                      lower.tail = FALSE)

data.frame(
  Effect      = c("Therapy (A, fixed)", "Trainee (B, random)", "Interaction (AB)"),
  Denominator = c("MS_AB", "MS_within", "MS_within"),
  df_num      = c(df_therapy_sim, df_trainee_sim, df_interaction_sim),
  df_denom    = c(df_interaction_sim, df_within_sim, df_within_sim),
  F_value     = round(c(f_correct, f_trainee_sim, f_interact_sim), 3),
  p_value     = round(c(p_correct, p_trainee_sim, p_interact_sim), 4)
)
HideShow
               Effect Denominator df_num df_denom F_value p_value
1  Therapy (A, fixed)       MS_AB      2        4   1.673  0.2965
2 Trainee (B, random)   MS_within      2       36   0.199  0.8203
3    Interaction (AB)   MS_within      4       36  16.615  0.0000

The three rows tell a story a fixed-effects analysis would have missed. The therapy effect is not significant once it must exceed the inconsistency among trainees. There is no main effect of trainee: on average the three were equally effective. The interaction is large, which is the whole point — effectiveness depends on the pairing of therapist with method, and that is exactly the component inflating the naive test of therapy mode.

10.3.4 — Numerical Example

An educational products firm compares a computer-based ACT study program with a packet of printed materials. Four high schools are sampled at random, ten junior volunteers at each school are split evenly between the two programs, and the posttest is a simulated ACT. Study program is factor AA (fixed; a1a_1 is the computer-based program, a2a_2 the paper-and-pencil program) and school is factor BB (random). The data are Table 10.5.

HideShow
data(chapter_10_table_5)
str(chapter_10_table_5)
HideShow
'data.frame':   40 obs. of  3 variables:
 $ A  : int  1 1 1 1 1 1 1 1 1 1 ...
 $ B  : int  1 1 1 1 1 2 2 2 2 2 ...
 $ ACT: int  28 26 26 23 17 26 26 25 21 17 ...
HideShow
# Spell out the correspondence between the numeric codes and the program names,
# then use factor() only to fix the level order (a1 first, as in the book).
chapter_10_table_5 <- chapter_10_table_5 |>
  mutate(Program = case_when(
    A == 1 ~ "Computer",
    A == 2 ~ "Paper-and-Pencil"
  )) |>
  mutate(Program = factor(Program,
                          levels = c("Computer", "Paper-and-Pencil")),
         School  = factor(B))

# Cell means and within-cell variances, part I of Table 10.5.
chapter_10_table_5 |>
  group_by(Program, School) |>
  summarise(mean = mean(ACT), variance = var(ACT), n = n(), .groups = "drop")
HideShow
# A tibble: 8 × 5
  Program          School  mean variance     n
  <fct>            <fct>  <dbl>    <dbl> <int>
1 Computer         1         24     18.5     5
2 Computer         2         23     15.5     5
3 Computer         3         19     25       5
4 Computer         4         18     12       5
5 Paper-and-Pencil 1         26     18.5     5
6 Paper-and-Pencil 2         29     14.5     5
7 Paper-and-Pencil 3         25     26       5
8 Paper-and-Pencil 4         28     14.5     5
HideShow
#> cell means 24, 23, 19, 18 and 26, 29, 25, 28 — matches Table 10.5, book p. 543
#> cell variances 18.5, 15.5, 25.0, 12.0 and 18.5, 14.5, 26.0, 14.5 — book p. 543

# Marginal means.
tapply(chapter_10_table_5$ACT, chapter_10_table_5$Program, mean)
HideShow
        Computer Paper-and-Pencil 
              21               27 
HideShow
#> 21 and 27 — matches book p. 543
tapply(chapter_10_table_5$ACT, chapter_10_table_5$School, mean)
HideShow
 1  2  3  4 
25 26 22 23 
HideShow
#> 25, 26, 22, 23 — matches book p. 543
mean(chapter_10_table_5$ACT)
HideShow
[1] 24
HideShow
#> 24 — matches book p. 543

The sums of squares, degrees of freedom, and mean squares are computed exactly as in a fixed-effects two-way design; only the denominators of the FF tests change. The crossed aov() fit supplies all of them.

HideShow
model_act <- aov(ACT ~ Program * School, data = chapter_10_table_5)
res_act   <- as.data.frame(summary(model_act)[[1]])
res_act
HideShow
               Df Sum Sq   Mean Sq   F value       Pr(>F)
Program         1    360 360.00000 19.930796 9.352074e-05
School          3    100  33.33333  1.845444 1.588054e-01
Program:School  3     80  26.66667  1.476355 2.395151e-01
Residuals      32    578  18.06250        NA           NA
HideShow
#> SS 360, 100, 80, 578 and MS 360.000, 33.333, 26.667, 18.063 — matches
#> Table 10.5, part III, book p. 543

ms_program     <- res_act[1, "Mean Sq"]
ms_school      <- res_act[2, "Mean Sq"]
ms_interaction <- res_act[3, "Mean Sq"]
ms_within      <- res_act[4, "Mean Sq"]

df_program     <- res_act[1, "Df"]
df_school      <- res_act[2, "Df"]
df_interaction <- res_act[3, "Df"]
df_within      <- res_act[4, "Df"]

The novel feature of the source table is the test of the fixed factor, whose denominator is MSABMS_{AB} rather than MSWMS_W.

HideShow
f_mixed <- ms_program / ms_interaction
p_mixed <- pf(f_mixed, df_program, df_interaction, lower.tail = FALSE)
c(F = f_mixed, p = p_mixed)
HideShow
          F           p 
13.50000000  0.03489698 
HideShow
#> F_A = 360 / 26.667 = 13.500 on (1, 3) df, p = .035 — matches book p. 542

# The critical value the observed F is compared against.
qf(0.95, df_program, df_interaction)
HideShow
[1] 10.12796
HideShow
#> 10.128, which book p. 542 quotes to one decimal as 10.1

For contrast, the same numerator divided by MSWMS_W gives the liberal test the book reports in Section 10.3.5.

HideShow
f_fixed <- ms_program / ms_within
p_fixed <- pf(f_fixed, df_program, df_within, lower.tail = FALSE)
c(F = f_fixed, p = p_fixed)
HideShow
           F            p 
1.993080e+01 9.352074e-05 
HideShow
#> F_obs(1, 32) = 19.931, p = .00009 — matches book p. 542

The full source table of Table 10.5, in APA style with gt. The FF and pp columns use the Table 10.4 denominators: MSABMS_{AB} for the fixed program effect, MSWMS_W for the random school factor and for the interaction. Partial η2\eta^2 for each effect is its share of effect-plus-within variance, which is the book’s Rpartial2R^2_{partial} of Equation 10.14.

HideShow
ss_within_act <- res_act[4, "Sum Sq"]

act_source <- data.frame(
  Source = c("A (Program, fixed)", "B (School, random)", "AB", "Within"),
  SS     = res_act[, "Sum Sq"],
  df     = res_act[, "Df"],
  MS     = res_act[, "Mean Sq"],
  Fstat  = c(f_mixed,
             ms_school / ms_within,
             ms_interaction / ms_within,
             NA_real_),
  p      = c(p_mixed,
             pf(ms_school / ms_within, df_school, df_within, lower.tail = FALSE),
             pf(ms_interaction / ms_within, df_interaction, df_within,
                lower.tail = FALSE),
             NA_real_),
  Denom  = c("AB", "Within", "Within", ""),
  row.names = NULL
)
act_source$peta <- ifelse(act_source$Source == "Within", NA_real_,
                          act_source$SS / (act_source$SS + ss_within_act))

act_source |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 3) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("**Table 10.5**. Analysis of Variance for ACT Score")) |>
  cols_align(align = "center", columns = -Source)
Table 10.5. Analysis of Variance for ACT Score
Source SS df MS F p Denom Partial η2
A (Program, fixed) 360.000 1 360.000 13.500 0.0349 AB 0.384
B (School, random) 100.000 3 33.333 1.845 0.1588 Within 0.147
AB 80.000 3 26.667 1.476 0.2395 Within 0.122
Within 578.000 32 18.063


HideShow
#> F = 13.500, 1.845, 1.476 with p = .035, .159, .240 — matches Table 10.5,
#> part III, book p. 543

The two analyses of the same data differ in what they license. The fixed-effects test is restricted to these 40 students at these four schools; the mixed-model test speaks to the population of American high schools, and pays for that reach with denominator degrees of freedom that fall from 32 to 3. The school, not the student, becomes the unit of analysis for the fixed effect, and pp moves from .00009 to .035.

The Program-by-School cell means

Why the price is worth paying is easiest to see in the cell means. The two programs do not differ by a constant across schools — the gap is 2 points at School 1 and 10 at School 4 — and that non-parallelism is the MSABMS_{AB} that the mixed-model test must overcome. The dashed navy lines are the two program marginal means, 21 and 27.

HideShow
act_cell_means <- chapter_10_table_5 |>
  group_by(Program, School) |>
  summarise(Mean = mean(ACT), .groups = "drop")

act_program_means <- chapter_10_table_5 |>
  group_by(Program) |>
  summarise(Mean = mean(ACT), .groups = "drop")

ggplot(act_cell_means, aes(x = School, y = Mean,
                           group = Program, colour = Program)) +
  geom_hline(data = act_program_means, aes(yintercept = Mean),
             inherit.aes = FALSE,
             linetype = "dashed", colour = "#0C2340") +
  geom_line() +
  geom_point(size = 2.5) +
  labs(x = "School (random factor)",
       y = "Mean simulated ACT score",
       colour = "Study program")
Mean simulated ACT score for each study program at each of the four randomly sampled schools, with the two program marginal means as dashed reference lines.

Mean simulated ACT score for each study program at each of the four randomly sampled schools, with the two program marginal means as dashed reference lines.

The same source table in DMAR

The bookkeeping above — build the crossed ANOVA table, then divide MSAMS_A by MSABMS_{AB} by hand and look up the right degrees of freedom — is what DMAR’s mixed_anova() packages. What the function adds is that the fixed-versus-random decision becomes an explicit argument rather than an unwritten convention, and the denominator actually used is reported in a column of the output, so the table carries its own audit trail.

HideShow
mixed_anova(
  data     = chapter_10_table_5,
  outcome  = "ACT",
  factor_A = "Program", A_type = "fixed",
  factor_B = "School",  B_type = "random"
)
effect ss df ms denominator F_value p_value
A 360 1 360.000 MS_AB 13.500 0.0349
B 100 3 33.333 MS_within 1.845 0.1588
A:B 80 3 26.667 MS_within 1.476 0.2395
HideShow
#> A: F = 13.500 on (1, 3) df, p = .0349 against MS_AB — matches book p. 542
#> B: F = 1.845, p = .1588 and A:B: F = 1.476, p = .2395 against MS_within —
#>    matches Table 10.5, book p. 543

Every number agrees with the hand computation and with the book’s source table, which is the point of showing both: the base-R route makes the choice of denominator visible, and the DMAR call records it.

10.3.5 — Alternative Tests and Design Considerations with Random Factors

If one is willing to treat the interaction as absent — the book’s example is a preliminary test of ABAB returning p>.2p > .2, which is the case here — the αβ\alpha\beta term can be dropped and the interaction and within-cell sources pooled into a single residual.

HideShow
ss_interaction <- res_act[3, "Sum Sq"]
ss_within      <- res_act[4, "Sum Sq"]

df_pooled <- df_interaction + df_within
ms_pooled <- (ss_interaction + ss_within) / df_pooled
ms_pooled
HideShow
[1] 18.8
HideShow
#> MS_residual = (578 + 80) / (32 + 3) = 658 / 35 = 18.80 — matches book p. 544

f_pooled <- ms_program / ms_pooled
p_pooled <- pf(f_pooled, df_program, df_pooled, lower.tail = FALSE)
c(F = f_pooled, p = p_pooled)
HideShow
           F            p 
1.914894e+01 1.038738e-04 
HideShow
#> F(1, 35) = 19.149, p = .0001 — matches book p. 544

If instead one concluded there was no evidence for either a BB effect or an ABAB interaction, the analysis could be rerun as a one-factor design, pooling BB, ABAB, and within.

HideShow
ss_school  <- res_act[2, "Sum Sq"]
df_pooled2 <- df_school + df_interaction + df_within
ms_pooled2 <- (ss_school + ss_interaction + ss_within) / df_pooled2

f_pooled2 <- ms_program / ms_pooled2
p_pooled2 <- pf(f_pooled2, df_program, df_pooled2, lower.tail = FALSE)
c(F = f_pooled2, p = p_pooled2)
HideShow
           F            p 
18.047493404  0.000134292 
HideShow
#> F(1, 38) = 18.047, p = .0001 — matches book p. 544

The four tests of the same fixed effect, side by side.

HideShow
data.frame(
  Test_logic  = c("Mixed model", "Pooled AB and within",
                  "Pooled B, AB and within", "Fixed effects"),
  Denominator = c("MS_AB", "MS_residual", "MS_residual (one-factor)", "MS_within"),
  MS_denom    = round(c(ms_interaction, ms_pooled, ms_pooled2, ms_within), 3),
  df_denom    = c(df_interaction, df_pooled, df_pooled2, df_within),
  F_value     = round(c(f_mixed, f_pooled, f_pooled2, f_fixed), 3),
  p_value     = signif(c(p_mixed, p_pooled, p_pooled2, p_fixed), 4)
)
HideShow
               Test_logic              Denominator MS_denom df_denom F_value
1             Mixed model                    MS_AB   26.667        3  13.500
2    Pooled AB and within              MS_residual   18.800       35  19.149
3 Pooled B, AB and within MS_residual (one-factor)   19.947       38  18.047
4           Fixed effects                MS_within   18.063       32  19.931
    p_value
1 3.490e-02
2 1.039e-04
3 1.343e-04
4 9.352e-05

The legitimacy of the last three rows hinges on the preliminary test having reached the right conclusion. As the book argues, an ABAB interaction that went undetected is still an ABAB interaction, so continuing to use MSABMS_{AB} regardless of how the interaction test turns out is the more conservative course.

10.3.6 — Follow-Up Tests and Confidence Intervals

Confidence intervals follow the same rule as the omnibus tests: whatever mean square served as the denominator of the test of an effect replaces MSWMS_W in the interval. For the two-level fixed factor that means MSABMS_{AB} and its 3 degrees of freedom.

HideShow
program_means <- tapply(chapter_10_table_5$ACT, chapter_10_table_5$Program, mean)
mean_diff <- program_means[["Computer"]] - program_means[["Paper-and-Pencil"]]
mean_diff
HideShow
[1] -6
HideShow
#> -6 = 21 - 27 — matches book p. 545

n_program <- as.vector(table(chapter_10_table_5$Program))   # 20 students each
f_crit    <- qf(0.95, df_program, df_interaction)
se_diff   <- sqrt(ms_interaction * sum(1 / n_program))
moe       <- sqrt(f_crit) * se_diff

c(lower = mean_diff - moe, upper = mean_diff + moe)
HideShow
      lower       upper 
-11.1969131  -0.8030869 
HideShow
#> -11.197, -0.803 — matches book p. 545, where rounding the critical value to
#> F(.05; 1, 3) = 10.1 rather than 10.128 gives -11.190 and -0.810

The interval excludes zero, consistent with the mixed-model test, but it is wide: the deficit from the computer-based program could be just over 11 points or less than a single point.

When a factor has more than two levels, simultaneous intervals are appropriate. The school effect was not significant, but the book illustrates a Tukey interval on the difference between Schools 2 and 3 using MSWMS_W, since MSWMS_W is the denominator for the random factor.

HideShow
school_means <- tapply(chapter_10_table_5$ACT, chapter_10_table_5$School, mean)
diff_23 <- school_means[["2"]] - school_means[["3"]]

n_school <- as.vector(table(chapter_10_table_5$School))     # 10 students each
q_crit   <- qtukey(0.95, nmeans = nlevels(chapter_10_table_5$School),
                   df = df_within)
q_crit
HideShow
[1] 3.831616
HideShow
#> 3.8316, which book p. 545 quotes as 3.832
moe_23   <- (q_crit / sqrt(2)) * sqrt(ms_within * (1 / n_school[2] + 1 / n_school[3]))

c(estimate = diff_23, lower = diff_23 - moe_23, upper = diff_23 + moe_23)
HideShow
 estimate     lower     upper 
 4.000000 -1.149569  9.149569 
HideShow
#> 4, with limits -1.150 and 9.150 — matches book p. 545

The mainstream route to the same interval is emmeans, which forms the estimated marginal means from the fitted model and applies the Tukey adjustment for the family of four school means.

HideShow
emm_school <- emmeans(model_act, specs = ~ School)
confint(contrast(emm_school, method = "pairwise", adjust = "tukey"),
        level = 0.95)
HideShow
 contrast          estimate  SE df lower.CL upper.CL
 School1 - School2       -1 1.9 32    -6.15     4.15
 School1 - School3        3 1.9 32    -2.15     8.15
 School1 - School4        2 1.9 32    -3.15     7.15
 School2 - School3        4 1.9 32    -1.15     9.15
 School2 - School4        3 1.9 32    -2.15     8.15
 School3 - School4       -1 1.9 32    -6.15     4.15

Results are averaged over the levels of: Program 
Confidence level used: 0.95 
Conf-level adjustment: tukey method for comparing a family of 4 estimates 
HideShow
#> School2 - School3: estimate 4, limits -1.150 and 9.150 — matches book p. 545

The School2 - School3 row reproduces the hand computation to three decimals, which is the useful thing to know: emmeans is doing the arithmetic of the preceding chunk, not something different, and it supplies the remaining five pairwise intervals at the same simultaneous confidence level.

10.3.7 — Measures of Association Strength

10.3.7.2 — Numerical Example

The sample measures are ratios of sums of squares, exactly as in earlier chapters: R2=SSeffect/SSTotalR^2 = SS_{effect}/SS_{Total} (Equation 10.13) and Rpartial2=SSeffect/(SSW+SSeffect)R^2_{partial} = SS_{effect}/(SS_W + SS_{effect}) (Equation 10.14).

HideShow
ss_total_act <- sum(res_act[, "Sum Sq"])
ss_total_act
HideShow
[1] 1118
HideShow
#> 360 + 100 + 80 + 578 = 1118 — matches book p. 548

ss_effects <- setNames(res_act[1:3, "Sum Sq"], c("A", "B", "AB"))
round(ss_effects / ss_total_act, 3)
HideShow
    A     B    AB 
0.322 0.089 0.072 
HideShow
#> R^2 = .322, .089, .072 — matches Table 10.6, book p. 548
round(ss_effects / (ss_effects + ss_within_act), 3)
HideShow
    A     B    AB 
0.384 0.147 0.122 
HideShow
#> R^2_partial = .384, .147, .122 — matches Table 10.6, book p. 548

The population estimates need variance components, which Equation 10.21 recovers from the mean squares. Because the program factor is fixed, its component is a sum of squared effect parameters, ∑α̂j2/a\sum\hat\alpha_j^2/a, rather than a variance.

HideShow
a <- nlevels(chapter_10_table_5$Program)   # 2 programs
b <- nlevels(chapter_10_table_5$School)    # 4 schools
n <- 5                                     # 5 students per cell

# Equation 10.21.
theta_program <- ((a - 1) / (a * b * n)) * (ms_program - ms_interaction)
var_school    <- (ms_school - ms_within) / (a * n)
var_interact  <- (ms_interaction - ms_within) / n
var_error     <- ms_within

round(c(sum_alpha_sq_over_a = theta_program, sigma2_beta = var_school,
        sigma2_alphabeta = var_interact, sigma2_epsilon = var_error), 4)
HideShow
sum_alpha_sq_over_a         sigma2_beta    sigma2_alphabeta      sigma2_epsilon 
             8.3333              1.5271              1.7208             18.0625 
HideShow
#> 8.333, 1.527, 1.721, and 18.0625 (which the book prints as 18.063) —
#> matches book p. 548

Equation 10.20 then gives the overall measures and Equation 10.22 the partial ones. The fixed factor’s measure is written ω̂2\widehat\omega^2; the random factors’ are intraclass correlations ρ̂I\widehat\rho_I.

HideShow
total_pop_var <- theta_program + var_school + var_interact + var_error
total_pop_var
HideShow
[1] 29.64375
HideShow
#> 29.644 — matches book p. 548

omega_sq_A <- theta_program / total_pop_var
rho_I_B    <- var_school    / total_pop_var
rho_I_AB   <- var_interact  / total_pop_var

# Equation 10.22: each component relative to itself plus error alone.
omega_sq_A_partial <- theta_program / (theta_program + var_error)
rho_I_B_partial    <- var_school    / (var_school    + var_error)
rho_I_AB_partial   <- var_interact  / (var_interact  + var_error)

round(c(omega_sq_A = omega_sq_A, rho_I_B = rho_I_B, rho_I_AB = rho_I_AB), 3)
HideShow
omega_sq_A    rho_I_B   rho_I_AB 
     0.281      0.052      0.058 
HideShow
#> .281, .052, .058 — matches book p. 548
round(c(omega_sq_A_partial = omega_sq_A_partial,
        rho_I_B_partial = rho_I_B_partial,
        rho_I_AB_partial = rho_I_AB_partial), 3)
HideShow
omega_sq_A_partial    rho_I_B_partial   rho_I_AB_partial 
             0.316              0.078              0.087 
HideShow
#> .316, .078, .087 — matches Table 10.6, book p. 548

All twelve entries of Table 10.6 in one table.

HideShow
data.frame(
  Effect     = c("A (Program, fixed)", "B (School, random)", "AB"),
  R2         = ss_effects / ss_total_act,
  R2_partial = ss_effects / (ss_effects + ss_within_act),
  Overall    = c(omega_sq_A, rho_I_B, rho_I_AB),
  Partial    = c(omega_sq_A_partial, rho_I_B_partial, rho_I_AB_partial),
  row.names  = NULL
) |>
  gt() |>
  fmt_number(columns = c(R2, R2_partial, Overall, Partial), decimals = 3) |>
  cols_label(R2 = md("*R*<sup>2</sup>"),
             R2_partial = md("*R*<sup>2</sup><sub>partial</sub>"),
             Overall = "Overall", Partial = "Partial") |>
  tab_spanner(label = "Sample values", columns = c(R2, R2_partial)) |>
  tab_spanner(label = "Population estimates", columns = c(Overall, Partial)) |>
  tab_header(title = md(paste("**Table 10.6**. Estimates of Association Strength",
                              "Measures for ACT Training Program Example"))) |>
  cols_align(align = "center", columns = -Effect)
Table 10.6. Estimates of Association Strength Measures for ACT Training Program Example
Effect
Sample values
Population estimates
R2 R2partial Overall Partial
A (Program, fixed) 0.322 0.384 0.281 0.316
B (School, random) 0.089 0.147 0.052 0.078
AB 0.072 0.122 0.058 0.087
HideShow
#> every entry matches Table 10.6, book p. 548

The overall ω̂2=.281\widehat\omega^2 = .281 counts school-to-school variability and the program-by-school interaction as part of the variance the program has to explain. The partial ω̂partial2=.316\widehat\omega^2_{partial} = .316 treats the school factor as extrinsic — appropriate if the question concerns students within one particular school, or a population for whom the school effect is not relevant — and so divides only by the program component plus within-cell error.

The same variance components from a fitted mixed model

The components above came from the method of moments: set each observed mean square equal to its expectation and solve. A random-effects model estimates them directly by restricted maximum likelihood, and VarCorr() reports them. The comparison is instructive precisely because the two routes do not agree everywhere.

HideShow
fit_mixed <- lmer(ACT ~ Program + (1 | School) + (1 | Program:School),
                  data = chapter_10_table_5)
print(VarCorr(fit_mixed), comp = "Variance")
HideShow
 Groups         Name        Variance
 Program:School (Intercept)  1.72082
 School         (Intercept)  0.66668
 Residual                   18.06250

The interaction component, 1.721, and the residual, 18.063, reproduce the moment-method values exactly. The school component does not: REML returns 0.667 where Equation 10.21 gives 1.527. The difference is not an error in either computation but a difference in the model being fitted. Table 10.3 gives the mixed-design expectation of MSBMS_B as σε2+anσβ2\sigma^2_\varepsilon + an\sigma^2_\beta, which is what Equation 10.21 inverts. Fitting (1 | School) and (1 | Program:School) as two separate random terms implies instead that MSBMS_B also carries an interaction component, σε2+nσαβ2+anσβ2\sigma^2_\varepsilon + n\sigma^2_{\alpha\beta} + an\sigma^2_\beta, and subtracting that extra term accounts for the whole discrepancy:

HideShow
(ms_school - ms_within - n * var_interact) / (a * n)
HideShow
[1] 0.6666667
HideShow
#> 0.667 — the REML estimate of the School variance, recovered by hand

So the two answers differ by nσ̂αβ2/(an)=1.721/2=0.861n\widehat\sigma^2_{\alpha\beta}/(an) = 1.721/2 = 0.861, and the choice between them is the choice between the restricted and unrestricted formulations of the mixed model. The book’s Equation 10.21 and the intraclass correlations above use the restricted form, and those are the values Table 10.6 reports.

10.3.8 — Using Statistical Computer Programs to Analyze Designs with Random Factors

The chapter shows how SPSS and SAS are told which error term to use for which effect: VS on a MANOVA DESIGN statement, a /TEST method vs method*school line added to UNIANOVA syntax, or test H = method E = method*school; in SAS’s PROC GLM. R’s counterpart in base R is the Error() term inside aov(), which splits the analysis into error strata and tests each effect within its own stratum.

HideShow
mixed_model_auto <- aov(ACT ~ Program + Error(School / Program),
                        data = chapter_10_table_5)
summary(mixed_model_auto)
HideShow

Error: School
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  3    100   33.33               

Error: School:Program
          Df Sum Sq Mean Sq F value Pr(>F)  
Program    1    360   360.0    13.5 0.0349 *
Residuals  3     80    26.7                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: Within
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals 32    578   18.06               
HideShow
#> Program: F = 13.5, p = .0349 in the School:Program stratum — matches book
#> p. 542; the strata carry MS_B = 33.33, MS_AB = 26.7, MS_W = 18.06 of
#> Table 10.5, book p. 543

The Error: School:Program stratum holds the test of the fixed factor, with the interaction mean square as its residual, so the reported FF and pp are the mixed-model values rather than the naive ones. The Error: Within stratum holds the within-cell variance.

The contemporary route is a linear mixed-effects model. lmer() estimates the variance components by REML, which does not require the balance that the method of moments assumes, and lmerTest supplies the FF test for the fixed effect with Satterthwaite degrees of freedom. The term (1 | School) makes the baseline ACT score vary randomly across schools, and (1 | Program:School) lets the program’s effect vary by school.

HideShow
lmm_model <- lmer(ACT ~ Program + (1 | School) + (1 | Program:School),
                  data = chapter_10_table_5)
anova(lmm_model)
HideShow
Type III Analysis of Variance Table with Satterthwaite's method
        Sum Sq Mean Sq NumDF DenDF F value Pr(>F)  
Program 243.84  243.84     1     3    13.5 0.0349 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 13.5 on (1, 3) df, p = .0349 — matches book p. 542

The Satterthwaite denominator degrees of freedom come out at exactly 3 here because the design is balanced; with unequal cell sizes or missing observations the same approximation returns a non-integer value, which is where it earns its keep. Note that lmer() reports a SumSqSum\ Sq for the fixed effect that is not the book’s SSA=360SS_A = 360: the likelihood- based fit works on a different scale, and it is the FF ratio and its degrees of freedom that are comparable to Table 10.5.

sjPlot::tab_model() collects the fitted model in one place: the fixed-effect estimate for program, the random-effect variances, the intraclass correlation, and the sample sizes. These random-effect variances are the REML ones, so the school variance is the 0.667 discussed above rather than the 1.527 of Table 10.6, and the reported ICC is computed from the REML partition rather than from Equation 10.20.

HideShow
tab_model(lmm_model,
          show.icc    = TRUE,    # intraclass correlation(s)
          show.re.var = TRUE,    # random-effect variances
          dv.labels   = "ACT score")
  ACT score
Predictors Estimates CI p
(Intercept) 21.00 18.51 – 23.49 <0.001
Program
[Paper-and-Pencil]
6.00 2.68 – 9.32 0.001
Random Effects
σ2 18.06
τ00 Program:School 1.72
τ00 School 0.67
ICC 0.12
N School 4
N Program 2
Observations 40
Marginal R2 / Conditional R2 0.311 / 0.391

To make the generalizability penalty concrete, the mixed model can be placed side by side with the fixed-effects OLS fit that ignores the random schools. With modelsummary, each model is a column and the fit statistics sit at the foot.

HideShow
fit_ols_act <- lm(ACT ~ Program, data = chapter_10_table_5)

modelsummary(
  list("Fixed-effects (OLS)" = fit_ols_act, "Mixed (random School)" = lmm_model),
  estimate  = "{estimate}",
  statistic = "({std.error})",   # standard errors in parentheses, APA style
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  output    = "gt"
)
Fixed-effects (OLS) Mixed (random School)
(Intercept) 21.000 21.000
(0.999) (1.225)
ProgramPaper-and-Pencil 6.000 6.000
(1.412) (1.633)
SD (Intercept ProgramSchool) 1.312
SD (Intercept School) 0.817
SD (Observations) 4.250
Num.Obs. 40 40
AIC 237.2 236.8
BIC 242.3 245.2
Log.Lik. -115.594

The same two fits as a gtsummary table, each under its own spanning header. The program coefficient is identical in the two models, because the design is balanced; what differs is the standard error and the reference distribution the fixed effect is judged against.

HideShow
t_ols <- tbl_regression(fit_ols_act, intercept = TRUE)
t_mix <- tbl_regression(lmm_model,   intercept = TRUE)
tbl_merge(list(t_ols, t_mix),
          tab_spanner = c("**Fixed-effects (OLS)**", "**Mixed (random School)**"))
Characteristic
Fixed-effects (OLS)
Mixed (random School)
Beta 95% CI p-value Beta 95% CI p-value
(Intercept) 21 19, 23 <0.001 21 18, 24 <0.001
Program





    Computer — —
— —
    Paper-and-Pencil 6.0 3.1, 8.9 <0.001 6.0 0.80, 11 0.035
Abbreviation: CI = Confidence Interval

10.3.9 — Determining Power in Designs with Random Factors

Power for a random effect is based on a central FF distribution rather than a noncentral one, which is why software written for fixed-effects power analysis does not apply. Under the alternative, the test statistic is distributed as a multiple of a central FF, and the multiplier is the ratio of expected mean squares (Equation 10.23). For a one-way random-effects design that ratio is 1+nfrand21 + nf^2_{rand} (Equation 10.24), with frand=σα/σεf_{rand} = \sigma_\alpha/\sigma_\varepsilon, so Equation 10.25 gives

power=Pr⁡[F≥Fcrit1+nfrand2].\text{power} = \Pr\left[F \geq \frac{F_{crit}}{1 + n f^2_{rand}}\right].

The book computes this with SPSS syntax over a table of scenarios: three levels of a random factor, α=.05\alpha = .05, frand=.40f_{rand} = .40, and nn running from 20 to 80. The same table in R is three vectorized lines.

HideShow
power_random <- function(a, n, f_rand, alpha = 0.05) {
  ems_ratio <- 1 + n * f_rand^2
  f_crit    <- qf(1 - alpha, a - 1, a * n - a)
  power     <- 1 - pf(f_crit / ems_ratio, a - 1, a * n - a)
  data.frame(a = a, n = n, f_rand = f_rand, alpha = alpha,
             EMSratio = round(ems_ratio, 2),
             F_crit = round(f_crit, 2),
             power = round(power, 2))
}

power_random(a = 3, n = c(20, 40, 60, 80), f_rand = 0.40)
HideShow
  a  n f_rand alpha EMSratio F_crit power
1 3 20    0.4  0.05      4.2   3.16  0.48
2 3 40    0.4  0.05      7.4   3.07  0.66
3 3 60    0.4  0.05     10.6   3.05  0.75
4 3 80    0.4  0.05     13.8   3.03  0.80
HideShow
#> EMSratio 4.20, 7.40, 10.60, 13.80; F_crit 3.16, 3.07, 3.05, 3.03;
#> power .48, .66, .75, .80 — matches book p. 551

Reaching power of .80 takes 240 subjects in total even though frand=.40f_{rand} = .40 is a large effect, for the two reasons the text gives: with only three levels sampled, the variance among the selected population means is usually smaller than the population variance, and power depends on how many levels of the random factor are used and not only on the total NN. Redistributing the same 240 subjects over more levels shows the second point directly.

HideShow
power_random(a = c(3, 8), n = c(80, 30), f_rand = 0.40)
HideShow
  a  n f_rand alpha EMSratio F_crit power
1 3 80    0.4  0.05     13.8   3.03  0.80
2 8 30    0.4  0.05      5.8   2.05  0.93
HideShow
#> 3 groups of 80 gives power .80; 8 groups of 30 gives .93 — matches book p. 551

# And the same power of .80 from far fewer subjects, by using 7 groups of 20.
power_random(a = 7, n = 20, f_rand = 0.40)
HideShow
  a  n f_rand alpha EMSratio F_crit power
1 7 20    0.4  0.05      4.2   2.17   0.8
HideShow
#> power .80 with 140 subjects in total — matches book p. 551

The effect size itself can be estimated from pilot data. Equation 10.26 estimates frand2f^2_{rand} as (MSA−MSW)/(n⋅MSW)(MS_A - MS_W)/(n \cdot MS_W). The book’s illustration is a three-group pilot study with means of 40, 45, and 50, 20 subjects per group, and MSW=100MS_W = 100.

HideShow
pilot_means <- c(40, 45, 50)
n_pilot     <- 20
ms_w_pilot  <- 100

# MS_A = sum(n * alpha_hat^2) / (a - 1), with alpha_hat the deviations from the
# grand mean.
alpha_hat  <- pilot_means - mean(pilot_means)
ms_a_pilot <- sum(n_pilot * alpha_hat^2) / (length(pilot_means) - 1)
ms_a_pilot
HideShow
[1] 500
HideShow
#> MS_A = 20(25 + 0 + 25) / 2 = 500 — matches book p. 551

f2_rand <- (ms_a_pilot - ms_w_pilot) / (n_pilot * ms_w_pilot)
c(f2_rand = f2_rand, f_rand = sqrt(f2_rand))
HideShow
  f2_rand    f_rand 
0.2000000 0.4472136 
HideShow
#> f^2_rand = 400 / 2000 = .2, so f_rand = .4472 — matches book p. 551

# How many per group a three-group study would then need for power of .80.
power_random(a = 3, n = 64, f_rand = sqrt(f2_rand))
HideShow
  a  n    f_rand alpha EMSratio F_crit power
1 3 64 0.4472136  0.05     13.8   3.04   0.8
HideShow
#> power .80 at 64 subjects per group — matches book p. 551
Planning the number of levels in DMAR

The computations above answer a power question: given a number of levels and a number of observations per level, how often will the test reject? A planning question the chapter’s emphasis on the intraclass correlation raises but does not take up is the precision question: how many levels are needed to estimate ρI\rho_I itself to a stated confidence- interval width? DMAR’s accuracy-in-parameter-estimation planner inverts the asymptotic variance of the ICC to answer it. This is a companion addition, not a reproduction of a printed value.

HideShow
ss_aipe_icc(true_icc = 0.5, n_raters = 5, width = 0.20,
            conf_level = 0.95, type = "ICC(1,1)")
term value
necessary_N 88
expected_width 0.199
true_icc 0.500
n_raters 5
width 0.200
conf_level 0.950

Confidence level: 95%

The necessary_N row is the number of levels of the random factor — schools, trainees, clusters — needed so that with 5 observations per level and an anticipated ICC of .5 the 95% confidence interval for the ICC is no wider than .20, and expected_width reports the width that number actually delivers. The lesson is the same one the power table teaches: with random factors it is the number of levels sampled, not the number of observations inside each one, that governs the quality of the inference.

10.4 — Designs with Nested Factors

10.4.3 — Models and Tests

The clinic director tests for a difference across genders in the severity ratings that graduate students assign to clients. Three male and three female clinical students are sampled, and each is assigned four clients for an intake interview. Gender is the fixed factor AA; trainee is the random factor BB, nested within gender, because a given trainee is either male or female and cannot be crossed with gender. The structural model is Equation 10.32:

Yijk=μ+αj+βk/j+εijkY_{ijk} = \mu + \alpha_j + \beta_{k/j} + \varepsilon_{ijk}

where αj\alpha_j is the fixed effect of the jjth gender, βk/j\beta_{k/j} the simple effect of the kkth trainee within that gender, and εijk\varepsilon_{ijk} the within-cell error. No interaction term exists, so SSB/ASS_{B/A} is the pooled sum of squares from one-way analyses within each gender. The data are Table 10.9.

HideShow
data(chapter_10_table_9)
str(chapter_10_table_9)
HideShow
'data.frame':   24 obs. of  3 variables:
 $ Gender  : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Trainee : int  1 1 1 1 2 2 2 2 3 3 ...
 $ Severity: int  49 40 31 40 42 48 52 58 42 46 ...
HideShow
chapter_10_table_9$Gender  <- factor(chapter_10_table_9$Gender)
chapter_10_table_9$Trainee <- factor(chapter_10_table_9$Trainee)

# Cell means, gender marginal means, and the grand mean of Table 10.9, part I.
tapply(chapter_10_table_9$Severity,
       list(chapter_10_table_9$Gender, chapter_10_table_9$Trainee), mean)
HideShow
   1  2  3
1 40 50 48
2 61 54 65
HideShow
#> 40, 50, 48 for the male trainees and 61, 54, 65 for the female trainees —
#> matches Table 10.9, book p. 559
tapply(chapter_10_table_9$Severity, chapter_10_table_9$Gender, mean)
HideShow
 1  2 
46 60 
HideShow
#> 46 and 60 — matches book p. 559
mean(chapter_10_table_9$Severity)
HideShow
[1] 53
HideShow
#> 53 — matches book p. 559

In base R the nesting is written into the error structure. Error(Gender/Trainee) tells aov() that trainee is nested within gender, which puts the gender effect in the Gender:Trainee stratum and so tests it against MSB/AMS_{B/A} rather than MSWMS_W.

HideShow
nested_aov <- aov(Severity ~ Gender + Error(Gender / Trainee),
                  data = chapter_10_table_9)
summary(nested_aov)
HideShow

Error: Gender
       Df Sum Sq Mean Sq
Gender  1   1176    1176

Error: Gender:Trainee
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  4    472     118               

Error: Within
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals 18    820   45.56               
HideShow
#> SS_A = 1176, SS_B/A = 472, SS_W = 820 with MS 1176, 118, 45.556 — matches
#> Table 10.9, parts II to IV, book p. 559

aov_summary <- summary(nested_aov)
MS_A  <- aov_summary[["Error: Gender"]][[1]]["Gender", "Mean Sq"]
MS_BA <- aov_summary[["Error: Gender:Trainee"]][[1]]["Residuals", "Mean Sq"]
MS_W  <- aov_summary[["Error: Within"]][[1]]["Residuals", "Mean Sq"]
df_BA <- aov_summary[["Error: Gender:Trainee"]][[1]]["Residuals", "Df"]
df_W  <- aov_summary[["Error: Within"]][[1]]["Residuals", "Df"]

aov() leaves the FF column blank for gender, because the test spans two strata. The two ratios are a line of arithmetic each.

HideShow
f_gender <- MS_A / MS_BA
p_gender <- pf(f_gender, 1, df_BA, lower.tail = FALSE)
c(F = f_gender, p = p_gender)
HideShow
         F          p 
9.96610169 0.03428551 
HideShow
#> F = 1176 / 118 = 9.966 on (1, 4) df, p = .034 — matches Table 10.9, book
#> p. 559

f_trainee <- MS_BA / MS_W
p_trainee <- pf(f_trainee, df_BA, df_W, lower.tail = FALSE)
c(F = f_trainee, p = p_trainee)
HideShow
         F          p 
2.59024390 0.07164886 
HideShow
#> F = 118 / 45.556 = 2.590 on (4, 18) df, p = .072 — matches Table 10.9, book
#> p. 559

The book notes that the test of the nonnested factor is equivalent to a one-way ANOVA carried out on the cluster means themselves. That claim is worth checking, because it explains where the 4 denominator degrees of freedom come from.

HideShow
cluster_means <- aggregate(Severity ~ Gender + Trainee,
                           data = chapter_10_table_9, FUN = mean)
cluster_means
HideShow
  Gender Trainee Severity
1      1       1       40
2      2       1       61
3      1       2       50
4      2       2       54
5      1       3       48
6      2       3       65
HideShow
summary(aov(Severity ~ Gender, data = cluster_means))
HideShow
            Df Sum Sq Mean Sq F value Pr(>F)  
Gender       1    294   294.0   9.966 0.0343 *
Residuals    4    118    29.5                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 294 / 29.5 = 9.966 on (1, 4) df — the same F as the full hierarchical
#> analysis, as stated on book p. 562

Six numbers, one per trainee, and the resulting FF is the FF of Table 10.9. The 24 client ratings contribute to the precision of each cluster mean but not to the degrees of freedom of the gender test, which is why adding clients per trainee cannot buy power for the fixed effect and adding trainees can.

The modern equivalent is a mixed-effects model with the nested factor as a random intercept. (1 | Gender:Trainee) forms one grouping level per trainee-within-gender, and lmerTest supplies the FF test.

HideShow
nested_lmm <- lmer(Severity ~ Gender + (1 | Gender:Trainee),
                   data = chapter_10_table_9)
anova(nested_lmm)
HideShow
Type III Analysis of Variance Table with Satterthwaite's method
       Sum Sq Mean Sq NumDF DenDF F value  Pr(>F)  
Gender 454.01  454.01     1     4  9.9661 0.03429 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 9.966 on (1, 4) df, p = .034 — matches Table 10.9, book p. 559

The nested source table of Table 10.9, in APA style. Gender is tested against MSB/AMS_{B/A}, the nested trainee effect against MSWMS_W; partial η2\eta^2 is each effect’s share of effect-plus-within variance.

HideShow
ss_a_nest  <- aov_summary[["Error: Gender"]][[1]]["Gender", "Sum Sq"]
ss_ba_nest <- aov_summary[["Error: Gender:Trainee"]][[1]]["Residuals", "Sum Sq"]
ss_w_nest  <- aov_summary[["Error: Within"]][[1]]["Residuals", "Sum Sq"]

nested_source <- data.frame(
  Source = c("A (Gender)", "B/A (Trainee within Gender)", "Within"),
  SS     = c(ss_a_nest, ss_ba_nest, ss_w_nest),
  df     = c(1, df_BA, df_W),
  MS     = c(MS_A, MS_BA, MS_W),
  Fstat  = c(f_gender, f_trainee, NA_real_),
  p      = c(p_gender, p_trainee, NA_real_),
  Denom  = c("B/A", "Within", ""),
  row.names = NULL
)
nested_source$peta <- ifelse(nested_source$Source == "Within", NA_real_,
                             nested_source$SS / (nested_source$SS + ss_w_nest))

nested_source |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 3) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md(paste("**Table 10.9**. Analysis of Variance for",
                              "General Severity Ratings (Nested Design)"))) |>
  cols_align(align = "center", columns = -Source)
Table 10.9. Analysis of Variance for General Severity Ratings (Nested Design)
Source SS df MS F p Denom Partial η2
A (Gender) 1,176.000 1 1,176.000 9.966 0.0343 B/A 0.589
B/A (Trainee within Gender) 472.000 4 118.000 2.590 0.0716 Within 0.365
Within 820.000 18 45.556


HideShow
#> F = 9.966 with p = .034 and F = 2.590 with p = .072 — matches Table 10.9,
#> part IV, book p. 559

sjPlot::tab_model() summarizes the same model, with the trainee random-effect variance and the intraclass correlation reported beside the gender fixed effect.

HideShow
tab_model(nested_lmm,
          show.icc    = TRUE,
          show.re.var = TRUE,
          dv.labels   = "Severity")
  Severity
Predictors Estimates CI p
(Intercept) 46.00 39.46 – 52.54 <0.001
Gender [2] 14.00 4.75 – 23.25 0.005
Random Effects
σ2 45.56
τ00 Gender:Trainee 18.11
ICC 0.28
N Gender 2
N Trainee 3
Observations 24
Marginal R2 / Conditional R2 0.445 / 0.603

10.4.4 — Degrees of Freedom

The nonnested factor keeps its usual a−1a - 1 degrees of freedom. The nested factor pools the simple effects: b−1b - 1 within each of the aa levels of AA, for a(b−1)a(b - 1) in total. The precaution the book flags is that bb is the number of levels per nest, not the total number of distinct levels of BB in the design.

HideShow
a_nest <- nlevels(chapter_10_table_9$Gender)    # 2 genders
b_nest <- 3   # 3 trainees per gender, not the 6 distinct trainees in the study
n_nest <- 4   # 4 clients per trainee

c(df_A = a_nest - 1,
  df_BA = a_nest * (b_nest - 1),
  df_W  = a_nest * b_nest * (n_nest - 1))
HideShow
 df_A df_BA  df_W 
    1     4    18 
HideShow
#> 1, 4, 18 — matches Table 10.9, book p. 559, and the rule on book p. 563

10.4.6 — Follow-Up Tests and Confidence Intervals

The rule from Section 10.3.6 carries over unchanged: the mean square that served as the denominator of an effect’s omnibus test is the one that appears in intervals for that effect. For gender that is MSB/A=118MS_{B/A} = 118 on 4 degrees of freedom (Equation 10.43).

HideShow
gender_means <- tapply(chapter_10_table_9$Severity,
                       chapter_10_table_9$Gender, mean)
mean_diff_gender <- gender_means[["1"]] - gender_means[["2"]]
mean_diff_gender
HideShow
[1] -14
HideShow
#> -14 = 46 - 60 — matches book p. 565

n_gender <- sum(chapter_10_table_9$Gender == 1)   # 12 clients per gender
ME_gender <- sqrt(qf(0.95, 1, df_BA)) *
  sqrt(MS_BA * (1 / n_gender + 1 / n_gender))

c(lower = mean_diff_gender - ME_gender, upper = mean_diff_gender + ME_gender)
HideShow
     lower      upper 
-26.312733  -1.687267 
HideShow
#> -26.313, -1.687 — matches book p. 565, where rounding F(.05; 1, 4) to 7.71
#> gives -26.314 and -1.686

Comparing two trainees is a test of the nested factor, so it drops back down the hierarchy to MSW=45.556MS_W = 45.556 on 18 degrees of freedom. The book defines the family as the three pairwise comparisons among male trainees plus the three among female trainees, which makes Bonferroni preferable to Tukey, and reads the critical value for 6 comparisons on 18 degrees of freedom from Appendix Table A.3.

HideShow
# Table 10.9 labels the female trainees 4, 5, and 6; within gender 2 they are
# coded k = 1, 2, 3, so female Trainee 5 is Trainee 2 and Trainee 6 is Trainee 3.
sev <- chapter_10_table_9
mean_T5 <- mean(sev$Severity[sev$Gender == 2 & sev$Trainee == 2])
mean_T6 <- mean(sev$Severity[sev$Gender == 2 & sev$Trainee == 3])
c(Trainee_5 = mean_T5, Trainee_6 = mean_T6)
HideShow
Trainee_5 Trainee_6 
       54        65 
HideShow
#> 54 and 65 — matches Table 10.9, book p. 559

alpha_bonf  <- 0.05 / 6
F_crit_bonf <- qf(1 - alpha_bonf, df1 = 1, df2 = df_W)
F_crit_bonf
HideShow
[1] 8.777796
HideShow
#> 8.78 — matches the Appendix Table A.3 value used on book p. 565

n_trainee  <- sum(sev$Gender == 2 & sev$Trainee == 2)   # 4 clients per trainee
ME_trainee <- sqrt(F_crit_bonf) * sqrt(MS_W * (1 / n_trainee + 1 / n_trainee))

c(estimate = mean_T5 - mean_T6,
  lower = (mean_T5 - mean_T6) - ME_trainee,
  upper = (mean_T5 - mean_T6) + ME_trainee)
HideShow
  estimate      lower      upper 
-11.000000 -25.139968   3.139968 
HideShow
#> -11 with a half-width of 14.140 — matches book p. 565; the interval contains
#> zero, so these two trainees do not differ significantly

10.4.7 — Standardized Effect Size Estimates

A nested design offers more than one standard deviation to standardize against, so the choice has to be made explicitly. Table 10.10 gives the variance components for the design at hand (factor AA fixed, factor BB random and nested), and the estimates follow from the mean squares.

HideShow
var_error_nest   <- MS_W                                         # sigma^2_epsilon
var_trainee_nest <- (MS_BA - MS_W) / n_nest                      # sigma^2_beta
var_gender_nest  <- ((a_nest - 1) / a_nest) *
  ((MS_A - MS_BA) / (b_nest * n_nest))                           # sum(alpha^2)/a

round(c(sigma2_epsilon = var_error_nest, sigma2_beta = var_trainee_nest,
        sum_alpha_sq_over_a = var_gender_nest), 3)
HideShow
     sigma2_epsilon         sigma2_beta sum_alpha_sq_over_a 
             45.556              18.111              44.083 
HideShow
#> 45.556, 18.111, 44.083 — matches book p. 567; sigma^2_beta = 18.111 is also
#> quoted on book p. 566

Standardizing by the between-cluster standard deviation gives dBd_B (Equation 10.44), by the within-cluster standard deviation dWd_W (Equation 10.45), and by both sources together dTd_T (Equation 10.46). The last is usually the one to report, because it anticipates a population in which both clients and therapists vary.

HideShow
d_B <- mean_diff_gender / sqrt(var_trainee_nest)
d_W <- mean_diff_gender / sqrt(var_error_nest)
d_T <- mean_diff_gender / sqrt(var_trainee_nest + var_error_nest)

round(c(d_B = d_B, d_W = d_W, d_T = d_T), 3)
HideShow
   d_B    d_W    d_T 
-3.290 -2.074 -1.755 
HideShow
#> -3.290, -2.074, -1.755 — matches book p. 566

# The standardizers themselves, for comparison with the book's arithmetic.
round(c(sigma_beta = sqrt(var_trainee_nest),
        sigma_epsilon = sqrt(var_error_nest),
        sigma_total = sqrt(var_trainee_nest + var_error_nest)), 3)
HideShow
   sigma_beta sigma_epsilon   sigma_total 
        4.256         6.749         7.979 
HideShow
#> 4.256, 6.749, 7.979 with a total variance of 63.667 — matches book p. 566

dBd_B and dWd_W are both larger in magnitude than dTd_T, and both would overstate the effect expected in a population of varying clients and varying therapists.

10.4.8 — Strength of Association in Nested Designs

The sample proportions come first. Two partial measures are defensible here, depending on whether the comparison variability is that among client ratings or that among trainees.

HideShow
ss_total_nest <- ss_a_nest + ss_ba_nest + ss_w_nest
ss_total_nest
HideShow
[1] 2468
HideShow
#> 1176 + 472 + 820 = 2468 — matches book p. 566

round(c(R2 = ss_a_nest / ss_total_nest,
        R2_partial_within = ss_a_nest / (ss_a_nest + ss_w_nest),
        R2_partial_nested = ss_a_nest / (ss_a_nest + ss_ba_nest)), 3)
HideShow
               R2 R2_partial_within R2_partial_nested 
            0.476             0.589             0.714 
HideShow
#> .476 and .589 — matches book p. 566; .714 — matches book p. 567, which is
#> the quantity SPSS labels partial eta squared for this design

The population estimates use the variance components of Section 10.4.7.

HideShow
omega_sq_overall <- var_gender_nest /
  (var_gender_nest + var_trainee_nest + var_error_nest)
omega_sq_partial <- var_gender_nest / (var_gender_nest + var_error_nest)
icc_trainee      <- var_trainee_nest / (var_trainee_nest + var_error_nest)

round(c(omega_sq_overall = omega_sq_overall,
        omega_sq_partial = omega_sq_partial,
        icc_trainee = icc_trainee), 3)
HideShow
omega_sq_overall omega_sq_partial      icc_trainee 
           0.409            0.492            0.284 
HideShow
#> omega^2 = 44.083 / 107.750 = .409 and omega^2_partial = 44.083 / 89.639
#> = .492 — matches book p. 567
#> ICC = 18.111 / (18.111 + 45.556) = .284 — matches book p. 567

An ICC of .284 says that some 28% of the variance in client severity ratings that remains after gender is accounted for belongs to the trainee doing the interviewing rather than to the client being rated. The book cites Wampold and Serlin (2000) on what ignoring a nested random factor of roughly this size costs: a threefold or greater inflation of the Type I error rate, and estimates of ω̂2\widehat\omega^2 for the nonnested factor twice as large as they should be.

The same ICC and its interval in DMAR

The ICC above was assembled from mean squares by hand. icc_lmer() reads the same quantity off a fitted mixed model, and what it adds is the interval: the point estimate alone says nothing about how well six trainees pin down a population ICC.

HideShow
icc_lmer(nested_lmm, conf_level = 0.95)
term value
icc 0.284
sigma2_between 18.111
sigma2_within 45.556
total_variance 63.667
ci_lower 0.000
ci_upper 0.747
n_clusters 6
average_cluster_size 4

Confidence level: 95%

HideShow
#> icc = 0.284 with sigma2_between = 18.111 and sigma2_within = 45.556 —
#> matches book p. 567

The icc row reproduces .284 and the sigma2_between and sigma2_within rows reproduce 18.111 and 45.556, so the REML and method-of-moments partitions coincide exactly for this balanced design. The ci_lower and ci_upper rows are the addition: the interval runs essentially from zero to .75, which is the honest summary of what six clusters support.

DMAR also supplies the analytic route to the same interval. The Burdick and Graybill modified-large-sample intervals are built from the method-of-moments mean squares rather than from a likelihood, so they can be computed from the published source table alone, without the raw data. These are companion additions; the book develops the variance components but not intervals around them.

HideShow
variance_components_mls(
  ms_between  = MS_BA,
  ms_within   = MS_W,
  df_between  = df_BA,
  df_within   = df_W,
  n_per_group = n_nest,
  conf_level  = 0.95
)
term value
sigma2_between 18.111
sigma2_between_ci_lower 0.000
sigma2_between_ci_upper 231.470
sigma2_within 45.556
sigma2_within_ci_lower 26.010
sigma2_within_ci_upper 99.626
icc 0.284
icc_ci_lower 0.000
icc_ci_upper 0.899

Confidence level: 95%

HideShow
#> sigma2_between = 18.111, sigma2_within = 45.556, icc = 0.284 — matches
#> book p. 567, now each with a confidence interval

The point estimates agree with the hand computation and with icc_lmer(), which is the check worth making; the _ci_lower and _ci_upper rows are what the call buys. The asymptotic sampling variance of the ICC estimate is available on its own, and it is the quantity the precision planner of Section 10.3.9 inverts.

HideShow
var_icc(icc = icc_trainee, N = 6, n_raters = n_nest, type = "ICC(1,1)")
term value
var_icc 0.049

With N=6N = 6 clusters of 4 observations each, the sampling variance of the ICC estimate is about .049, so a standard error near .22 — the same message the wide interval above delivers, in a different currency.

10.4.9 — Using Statistical Computer Programs to Analyze Nested Designs

As the chapter observes, the initial description of a nested design looks much like that of a crossed one in most programs: MANOVA Y BY THERAPY (1,2), TRAINEE (1,3) is the same line either way, and the nesting shows up only in which effects are requested and against what they are tested. SAS’s PROC GLM writes the nesting into the model as model y = a b(a); and then needs test H = a E = b(a); to get the right denominator.

R has the same trap. Listing both factors with * on nested data runs a crossed two-way analysis, and everything gets tested against MSWMS_W.

HideShow
wrong_aov <- aov(Severity ~ Gender * Trainee, data = chapter_10_table_9)
summary(wrong_aov)
HideShow
               Df Sum Sq Mean Sq F value  Pr(>F)    
Gender          1   1176  1176.0  25.815 7.8e-05 ***
Trainee         2    156    78.0   1.712  0.2086    
Gender:Trainee  2    316   158.0   3.468  0.0532 .  
Residuals      18    820    45.6                    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The gender effect is unchanged at SSA=1176SS_A = 1176, but dividing it by MSW=45.556MS_W = 45.556 rather than MSB/A=118MS_{B/A} = 118 sends FF from 9.966 to 25.815 and pp from .034 to below .0001. Worse, the Trainee and Gender:Trainee rows of that table are not interpretable at all: trainee 2 is a different person in each gender, so there is no trainee main effect to speak of and no interaction to estimate. The crossed analysis has silently split SSB/A=472SS_{B/A} = 472 into a fictitious 156 and 316.

HideShow
wrong_tab <- as.data.frame(summary(wrong_aov)[[1]])
c(fictitious_main = wrong_tab[2, "Sum Sq"],
  fictitious_interaction = wrong_tab[3, "Sum Sq"],
  total = wrong_tab[2, "Sum Sq"] + wrong_tab[3, "Sum Sq"])
HideShow
       fictitious_main fictitious_interaction                  total 
                   156                    316                    472 
HideShow
#> 156 + 316 = 472, which is SS_B/A of Table 10.9, book p. 559, carved up
#> between two effects that do not exist in a nested design
c(F_wrong = wrong_tab[1, "Mean Sq"] / wrong_tab[4, "Mean Sq"],
  F_right = f_gender)
HideShow
  F_wrong   F_right 
25.814634  9.966102 
HideShow
#> 25.815 against MS_W versus 9.966 against MS_B/A; the second is the value in
#> Table 10.9, book p. 559

The correct base-R syntax is the one used in Section 10.4.3, and it is worth seeing the two side by side.

HideShow
right_aov <- aov(Severity ~ Gender + Error(Gender / Trainee),
                 data = chapter_10_table_9)
summary(right_aov)
HideShow

Error: Gender
       Df Sum Sq Mean Sq
Gender  1   1176    1176

Error: Gender:Trainee
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  4    472     118               

Error: Within
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals 18    820   45.56               
HideShow
#> MS_B/A = 118 on 4 df is now the residual of the stratum holding Gender —
#> matches Table 10.9, book p. 559

The cost of the correct syntax is the blank FF column: aov() will not form a ratio across strata, so the test has to be finished by hand, as F=1176/118=9.966F = 1176/118 = 9.966. That is the practical reason to prefer a mixed-effects fit, which carries the hierarchy in the model rather than in the error strata and reports the test directly.

HideShow
anova(nested_lmm)
HideShow
Type III Analysis of Variance Table with Satterthwaite's method
       Sum Sq Mean Sq NumDF DenDF F value  Pr(>F)  
Gender 454.01  454.01     1     4  9.9661 0.03429 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 9.966 on (1, 4) df, p = .034 — matches Table 10.9, book p. 559

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 10: Designs with Random or Nested Factors (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

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

Open the separate reading

Code
Results
On this page

Chapter 11 provides a comprehensive overview of the traditional univariate approach to one-way within-subjects (repeated-measures) designs. It highlights the primary advantage of these designs, which is removing systematic individual differences to drastically increase statistical power, while carefully addressing the fundamental statistical challenge of correlated errors. To manage this challenge, the text details critical assumptions like sphericity and compound symmetry, alongside vital epsilon adjustments (such as Greenhouse–Geisser) for when these assumptions are violated. Furthermore, the chapter covers essential practical considerations for researchers, including controlling for order effects using Latin squares, computing effect sizes, and conducting accurate power analyses. Finally, the ANOVA framework is extended beyond experimental design to demonstrate how intraclass correlations (ICCs) can be calculated to assess rater and measurement reliability.

Chapter 1 explains how AMCP names the book’s data sets; these notes assume that explanation and get on with the statistics. The data used here are chapter_11_table_1 (two conditions, six subjects), chapter_11_table_4 (four conditions, ten subjects), chapter_11_table_5 (the McCarthy scores for 12 children at four ages), and chapter_11_table_19 and chapter_11_table_20 (the judges’ ratings used for the intraclass correlations).

HideShow
# Load all of the packages used.
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(tidyverse)      # data wrangling and plotting (dplyr, ggplot2, and friends)
library(MASS)           # mvrnorm() for the multivariate-normal simulations (Figure 11.2, Section 11.16)
library(car)            # Anova() for repeated-measures tests with sphericity corrections
library(broom)          # tidy model output into data frames
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables

11.5 — Analysis of Repeated-Measures Designs with Two Levels

11.5.1 — The Problem of Correlated Errors

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

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

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

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

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

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

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

11.5.2 — Reformulation of Model

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

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

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

We can replicate the step-by-step model comparison shown in Table 11.3 by calculating the full-model error (EFE_F) and restricted-model error (ERE_R) from these difference scores.

HideShow
# Replicating Table 11.3: the F test via model comparison

n <- nrow(chapter_11_table_1)

# Calculate Difference Scores (D) and the Mean Difference (D_bar)
D <- chapter_11_table_1$YCondition2 - chapter_11_table_1$YCondition1
D_bar <- mean(D)

# Restricted Error (E_R), Equation 11.12: the restricted model predicts 0.
E_R <- sum(D^2)

# Full Error (E_F), Equation 11.11: the full model predicts D_bar.
E_F <- sum((D - D_bar)^2)

df_R <- n      # 6
df_F <- n - 1  # 5

F_stat <- ((E_R - E_F) / (df_R - df_F)) / (E_F / df_F)

cat("Sum of D:", sum(D), " Sum of D^2:", E_R, "\n")
HideShow
Sum of D: 12  Sum of D^2: 32 
HideShow
cat("Restricted Error (E_R):", E_R, "\n")
HideShow
Restricted Error (E_R): 32 
HideShow
cat("Full Error (E_F):", E_F, "\n")
HideShow
Full Error (E_F): 8 
HideShow
cat("F statistic:", F_stat, "\n")
HideShow
F statistic: 15 
HideShow
#> sum(D) = 12, E_R = 32, E_F = 8, F = 15.0 — matches Table 11.3, book p. 595

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

Because this FF test has a single numerator degree of freedom, it is mathematically identical to a dependent (paired) tt test, which is Equation 11.19. We run it with t.test(), spelling out the options rather than relying on defaults. Note the argument order: putting Condition 2 first makes t.test() report the mean of Y2−Y1Y_2 - Y_1, which is the direction of DD in Table 11.3.

HideShow
# Paired samples t test, in the direction D = Y2 - Y1 used in Table 11.3
paired_t <- t.test(
  x           = chapter_11_table_1$YCondition2,
  y           = chapter_11_table_1$YCondition1,
  paired      = TRUE,
  alternative = "two.sided",
  conf.level  = 0.95
)
paired_t
HideShow

    Paired t-test

data:  chapter_11_table_1$YCondition2 and chapter_11_table_1$YCondition1
t = 3.873, df = 5, p-value = 0.01172
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
 0.6725572 3.3274428
sample estimates:
mean difference 
              2 
HideShow
# The square of the t value is exactly the F value above
cat("t =", round(paired_t$statistic, 4), " t^2 =", round(paired_t$statistic^2, 2), "\n")
HideShow
t = 3.873  t^2 = 15 
HideShow
#> t = 3.873, t^2 = 15.0 — the same F as Table 11.3, book p. 595

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

In DMAR: an exact test that does not assume normality

The paired tt test assumes the difference scores are normally distributed, which is a strong assumption with n=6n = 6. DMAR’s randomization_test_paired() returns an exact pp value obtained by enumerating all 2n2^n within-pair sign patterns, assuming only that the labeling of the two conditions within a pair is arbitrary under the null hypothesis. Note that DMAR defines the within-pair difference as y−xy - x, the reverse of the x - y convention in stats::t.test(), so the arguments are supplied in the opposite order here to keep the direction D=Y2−Y1D = Y_2 - Y_1.

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

Both routes reject at the .05 level, and the mean difference is identical. The randomization pp value is coarser than the tt test’s because with six pairs there are only 26=642^6 = 64 sign patterns, so the smallest attainable two-sided pp value is 2/64=.0312/64 = .031. That coarseness is the price of dropping the normality assumption at this sample size, and it is worth knowing before a small paired study is run.

11.7 — Traditional Univariate (Mixed-Model) Approach

When a within-subjects design has more than two levels, it can be viewed as a two-factor design, as Table 11.4 in the text (book p. 596) lays out. Specifically:

  • Factor A (treatment condition): a fixed factor.

  • Factor S (subjects): a random factor, because the subjects are viewed as a random sample from a larger population.

11.7.1 — Comparison of Full and Restricted Models

Because we are testing a fixed main effect (condition) in the presence of a random factor (subjects), the appropriate error term for the FF test is the interaction of the two, MSA×SMS_{A \times S}. This interaction measures how inconsistently the treatment effect behaves across subjects. Dropping the (πα)ij(\pi\alpha)_{ij} terms from Equations 11.20 and 11.21 gives the two models that are actually compared:

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

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

11.7.2 — Estimation of Parameters: Numerical Example

Let’s look at the data from Table 11.5, which tracks the general cognitive scores of 12 children on the McCarthy Scales of Children’s Abilities at 4 different ages (30, 36, 42, and 48 months). First, we load the data and calculate the marginal means.

HideShow
# Load the Chapter 11 Table 5 data
data(chapter_11_table_5)
str(chapter_11_table_5)
HideShow
'data.frame':   12 obs. of  4 variables:
 $ Months30: int  108 103 96 84 118 110 129 90 84 96 ...
 $ Months36: int  96 117 107 85 125 107 128 84 104 100 ...
 $ Months42: int  110 127 106 92 125 96 123 101 100 103 ...
 $ Months48: int  122 133 107 99 116 91 128 113 88 105 ...
HideShow
chapter_11_table_5
HideShow
   Months30 Months36 Months42 Months48
1       108       96      110      122
2       103      117      127      133
3        96      107      106      107
4        84       85       92       99
5       118      125      125      116
6       110      107       96       91
7       129      128      123      128
8        90       84      101      113
9        84      104      100       88
10       96      100      103      105
11      105      114      105      112
12      113      117      132      130
HideShow
# Calculate Marginal Means
# Means by row (subjects)
subject_means <- apply(chapter_11_table_5, MARGIN = 1, FUN = mean)

# Means by column (ages)
condition_means <- apply(chapter_11_table_5, MARGIN = 2, FUN = mean)

grand_mean <- mean(as.matrix(chapter_11_table_5))

cat("Subject Means:\n", round(subject_means, 2), "\n\n")
HideShow
Subject Means:
 109 120 104 90 121 101 127 97 94 101 109 123 
HideShow
cat("Condition Means:\n", round(condition_means, 2), "\n\n")
HideShow
Condition Means:
 103 107 110 112 
HideShow
cat("Grand Mean:", round(grand_mean, 2), "\n")
HideShow
Grand Mean: 108 
HideShow
#> condition means 103, 107, 110, 112 and grand mean 108 — match Table 11.5, book p. 598
#> subject means 109, 120, 104, 90, 121, 101, 127, 97, 94, 101, 109, 123 — match p. 598

To see how the ANOVA partitions variance, we can compute the full and restricted models exactly as the textbook does in Tables 11.6 through 11.9.

  • Restricted model (ERE_R, Equation 11.25): no age effect. The predicted score for a child is that child’s own mean across all ages.

  • Full model (EFE_F, Equation 11.24): age effects allowed. The predicted score is the age mean plus the child’s mean minus the grand mean.

HideShow
# Setup empty matrices to hold our predicted scores and squared errors
n_subj <- nrow(chapter_11_table_5)
a_cond <- ncol(chapter_11_table_5)

Y_hat_full <- matrix(NA, n_subj, a_cond)
Y_hat_restricted <- matrix(NA, n_subj, a_cond)
sq_error_full <- matrix(NA, n_subj, a_cond)
sq_error_restricted <- matrix(NA, n_subj, a_cond)

# Calculate Predictions and Squared Errors cell-by-cell
for (i in 1:n_subj) {
  for (j in 1:a_cond) {
    actual_Y <- chapter_11_table_5[i, j]

    # Restricted Model: Predicted score is just the Subject's mean
    Y_hat_restricted[i, j] <- subject_means[i]
    sq_error_restricted[i, j] <- (actual_Y - Y_hat_restricted[i, j])^2

    # Full Model: Predicted score accounts for both Subject and Condition effects
    Y_hat_full[i, j] <- condition_means[j] + subject_means[i] - grand_mean
    sq_error_full[i, j] <- (actual_Y - Y_hat_full[i, j])^2
  }
}

# Column sums of squared discrepancies, as the book's tables report them
cat("Full model, column sums (Table 11.8):     ", colSums(sq_error_full), "\n")
HideShow
Full model, column sums (Table 11.8):      474 584 220 728 
HideShow
cat("Restricted model, column sums (Table 11.9):", colSums(sq_error_restricted), "\n")
HideShow
Restricted model, column sums (Table 11.9): 774 596 268 920 
HideShow
#> 474, 584, 220, 728 — matches Table 11.8, book p. 600
#> 774, 596, 268, 920 — matches Table 11.9, book p. 601

# Calculate Total Error for both models
E_R <- sum(sq_error_restricted)
E_F <- sum(sq_error_full)

# Calculate F statistic
df_R <- n_subj * (a_cond - 1)          # 12 * 3 = 36
df_F <- (n_subj - 1) * (a_cond - 1)    # 11 * 3 = 33

F_stat <- ((E_R - E_F) / (df_R - df_F)) / (E_F / df_F)

cat("\nRestricted Error (E_R):", E_R, "\n")
HideShow

Restricted Error (E_R): 2558 
HideShow
cat("Full Error (E_F):", E_F, "\n")
HideShow
Full Error (E_F): 2006 
HideShow
cat("SS_A = E_R - E_F:", E_R - E_F, "\n")
HideShow
SS_A = E_R - E_F: 552 
HideShow
cat("F statistic:", round(F_stat, 2), "\n")
HideShow
F statistic: 3.03 
HideShow
#> E_F = SS_AxS = 2006 — matches book p. 600; E_R = 2558 — matches book p. 601
#> SS_A = 552 and F(3, 33) = 3.03 — match book p. 602

While hand calculation builds intuition, aov() is the practical route. Standard ANOVA functions in R require data in “long” (person-period) format rather than the “wide” (multivariate) format we currently have, so we reshape with tidyr and dplyr first.

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

# Reshape the data from Wide to Long
# The "sep=-3" partitions between the 3rd and 2nd value from the end of the column name.
C11_T5_PP <- C11_T5_PP %>%
  pivot_longer(
    cols = -ID,
    names_to = c("Unit", "Month"),
    names_sep = -3,
    values_to = "Values"
  ) %>%
  arrange(ID, Month)

# We do not need the "Unit" variable, so we drop it.
C11_T5_PP$Unit <- NULL

# Both ID and the Repeated Measure (Month) must be factors
# If not, the model will be incorrectly fitted
C11_T5_PP$Month <- as.factor(C11_T5_PP$Month)

head(C11_T5_PP, 10)
HideShow
# A tibble: 10 × 3
   ID    Month Values
   <fct> <fct>  <int>
 1 1     s30      108
 2 1     s36       96
 3 1     s42      110
 4 1     s48      122
 5 2     s30      103
 6 2     s36      117
 7 2     s42      127
 8 2     s48      133
 9 3     s30       96
10 3     s36      107
HideShow
str(C11_T5_PP)
HideShow
tibble [48 × 3] (S3: tbl_df/tbl/data.frame)
 $ ID    : Factor w/ 12 levels "1","2","3","4",..: 1 1 1 1 2 2 2 2 3 3 ...
 $ Month : Factor w/ 4 levels "s30","s36","s42",..: 1 2 3 4 1 2 3 4 1 2 ...
 $ Values: int [1:48] 108 96 110 122 103 117 127 133 96 107 ...

With the data in the correct format, we can run the model. To tell R that Month is a within-subjects factor, we define the error strata with + Error(ID/Month). This builds the same MSA×SMS_{A \times S} error term we computed by hand.

HideShow
# Run the repeated-measures ANOVA
Repeated_Measures_ANOVA <- aov(Values ~ Month + Error(ID/Month), data = C11_T5_PP)
summary(Repeated_Measures_ANOVA)
HideShow

Error: ID
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals 11   6624   602.2               

Error: ID:Month
          Df Sum Sq Mean Sq F value Pr(>F)  
Month      3    552  184.00   3.027 0.0432 *
Residuals 33   2006   60.79                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Month: SS = 552, MS = 184.0, F = 3.027, p = .0432 — matches book p. 602
#> Residuals (A x S): SS = 2006, MS = 60.79 — matches book p. 602

The same source table laid out APA-style, with sums of squares, df, mean squares, the omnibus F, its p value, and partial η2\eta^2. The error term for the age effect is the Age ×\times Subjects interaction, so partial η2\eta^2 is SSA/(SSA+SSA×S)SS_A / (SS_A + SS_{A \times S}). The table is built with gt because the plain-text ANOVA summary above does not format well in HTML.

HideShow
# Pull the error-stratum ANOVA into a tidy data frame, then format as APA.
aov_tbl <- broom::tidy(Repeated_Measures_ANOVA)

# Locate the three pieces we report: the Subjects stratum (S), the Age main
# effect (A), and the Age x Subjects residual that serves as its error term.
ss_S    <- aov_tbl$sumsq[aov_tbl$stratum == "ID"       & aov_tbl$term == "Residuals"]
ss_A    <- aov_tbl$sumsq[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Month"]
ss_AxS  <- aov_tbl$sumsq[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Residuals"]

tibble(
  Source = c("Subjects (S)", "Age (A)", "A × S (error)"),
  SS     = c(ss_S, ss_A, ss_AxS),
  df     = c(aov_tbl$df[aov_tbl$stratum == "ID"       & aov_tbl$term == "Residuals"],
             aov_tbl$df[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Month"],
             aov_tbl$df[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Residuals"]),
  MS     = c(ss_S / 11, ss_A / 3, ss_AxS / 33),
  Fstat  = c(NA, aov_tbl$statistic[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Month"], NA),
  p      = c(NA, aov_tbl$p.value[aov_tbl$stratum == "ID:Month" & aov_tbl$term == "Month"], NA),
  # Partial eta-squared for the Age effect: its share of effect-plus-error SS.
  peta   = c(NA, ss_A / (ss_A + ss_AxS), NA)
) |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("**Table 11.5 ANOVA**. Repeated-Measures Analysis of Variance for McCarthy Scores")) |>
  cols_align(align = "center", columns = -Source)
Table 11.5 ANOVA. Repeated-Measures Analysis of Variance for McCarthy Scores
Source SS df MS F p Partial η2
Subjects (S) 6,624.00 11 602.18


Age (A) 552.00 3 184.00 3.03 0.0432 0.216
A × S (error) 2,006.00 33 60.79


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

This is the basic, unadjusted repeated-measures ANOVA. It assumes sphericity holds exactly. Section 11.8 examines that assumption for these data, and Section 11.9 shows what happens to the test once it is relaxed.

The two models side by side

The full and restricted models of Equations 11.22 and 11.23 are ordinary least-squares fits once the data are in long format: the full model regresses Values on subjects (ID) and age (Month), and the restricted model drops age, keeping only the subject effects. Their residual sums of squares are exactly the EFE_F and ERE_R we computed by hand, and comparing them with anova() returns the same FF as the repeated-measures table above.

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

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

# The model comparison reproduces the omnibus F(3, 33) = 3.03 from the ANOVA.
anova(fit_restricted, fit_full)
HideShow
Analysis of Variance Table

Model 1: Values ~ ID
Model 2: Values ~ ID + Month
  Res.Df  RSS Df Sum of Sq      F  Pr(>F)  
1     36 2558                              
2     33 2006  3       552 3.0269 0.04322 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Sum of Sq = 552, F = 3.027, p = .0432 — matches book p. 602

A modelsummary table places the two models next to each other with their fit statistics at the foot; the 11 subject dummy coefficients are omitted so the age effect stands out. Each age coefficient is that month’s mean minus the 30-month mean, which from the Table 11.5 marginal means is 4, 7, and 9 points.

HideShow
modelsummary(
  list("Subjects only (restricted)" = fit_restricted,
       "Subjects + Age (full)"      = fit_full),
  estimate  = "{estimate}",
  statistic = "({std.error})",                 # standard errors in parentheses
  coef_omit = "ID",                            # hide the 11 subject dummies
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  output    = "gt"
)
Subjects only (restricted) Subjects + Age (full)
(Intercept) 109.000 104.000
(4.215) (4.358)
Months36 4.000
(3.183)
Months42 7.000
(3.183)
Months48 9.000
(3.183)
Num.Obs. 48 48
AIC 353.1 347.4
BIC 377.4 377.3
Log.Lik. -163.528 -157.694
HideShow
#> Month36 = 4, Month42 = 7, Month48 = 9 — the Table 11.5 age means minus 103, book p. 598

A gtsummary tbl_regression() table reports the age effect from the full model with confidence intervals and p values. The restricted model has no age term by construction (that is the whole point of the restriction), so the regression table belongs to the full model; the subject dummies are dropped with include so only the Month terms appear.

HideShow
tbl_regression(fit_full, include = "Month") |>
  modify_caption("**Age effect (full model), relative to 30 months**")
Age effect (full model), relative to 30 months
Characteristic Beta 95% CI p-value
Month


    s30 — —
    s36 4.0 -2.5, 10 0.2
    s42 7.0 0.52, 13 0.035
    s48 9.0 2.5, 15 0.008
Abbreviation: CI = Confidence Interval

11.8 — Assumptions in the Traditional Univariate (Mixed-Model) Approach

In addition to the standard ANOVA assumptions of normality, independence of subjects, and random sampling, the traditional univariate repeated-measures ANOVA requires a strict assumption about variances: homogeneity of treatment-difference variances.

This means that if you calculate the difference between any two treatment levels (Yl−YmY_l - Y_m), the population variance of those differences must be identical for every possible pair of levels. By Equation 11.30, the variance of a difference isσYl−Ym2=σYl2+σYm2−2ρlmσYlσYm\sigma^2_{Y_l-Y_m} = \sigma^2_{Y_l} + \sigma^2_{Y_m} - 2\rho_{lm}\sigma_{Y_l}\sigma_{Y_m}

11.8.1 — Homogeneity, Sphericity, and Compound Symmetry

The homogeneity assumption is satisfied when the population covariance matrix meets the condition of sphericity. A related but stricter condition is compound symmetry.

  • Sphericity: the variances of the differences are equal, even if the underlying variances and correlations differ.

  • Compound symmetry: all treatment variances are equal to each other (σ2\sigma^2) and all correlations between treatments are equal to each other (ρ\rho), as in Equations 11.31 and 11.32. Then the variance of a difference reduces to 2σ2(1−ρ)2\sigma^2(1-\rho), a constant, so compound symmetry guarantees sphericity.

As the text notes, compound symmetry is sufficient but technically not necessary. However, in a one-way design with more than two levels it would be highly unusual to find a matrix with sphericity but not compound symmetry, so for practical purposes compound symmetry is the requirement here.

11.8.2 — Numerical Example

We can use the McCarthy scores (Table 11.5) to check the sample variances, correlations, and variances of the differences to see whether they are consistent with sphericity.

HideShow
# Sample variances for each Month
sample_vars <- apply(chapter_11_table_5, MARGIN = 2, FUN = var)
cat("Sample Variances:\n")
HideShow
Sample Variances:
HideShow
round(sample_vars, 2)
HideShow
Months30 Months36 Months42 Months48 
  188.00   200.55   178.00   218.00 
HideShow
#> 188.00, 200.55, 178.00, 218.00 — match book p. 603

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

The correlation between adjacent time points (42 and 48 months: .853.853) is much higher than between distant time points (36 and 48 months: .466.466). Because the variances are roughly equal but the correlations are clearly unequal, compound symmetry is violated. The variances of the differences (Table 11.11) show the consequence.

HideShow
# Replicate Table 11.11: Variances of the Differences
# Extract columns for readability
Y1 <- chapter_11_table_5[, 1] # 30 months
Y2 <- chapter_11_table_5[, 2] # 36 months
Y3 <- chapter_11_table_5[, 3] # 42 months
Y4 <- chapter_11_table_5[, 4] # 48 months

var_diffs <- c(
  "Var(Y2 - Y1)" = var(Y2 - Y1),
  "Var(Y3 - Y2)" = var(Y3 - Y2),
  "Var(Y4 - Y3)" = var(Y4 - Y3),
  "Var(Y3 - Y1)" = var(Y3 - Y1),
  "Var(Y4 - Y2)" = var(Y4 - Y2),
  "Var(Y4 - Y1)" = var(Y4 - Y1)
)

data.frame(Variance = round(var_diffs, 2))
HideShow
             Variance
Var(Y2 - Y1)    79.82
Var(Y3 - Y2)    91.27
Var(Y4 - Y3)    59.82
Var(Y3 - Y1)   111.27
Var(Y4 - Y2)   223.64
Var(Y4 - Y1)   163.64
HideShow
#> 79.82, 91.27, 59.82, 111.27, 223.64, 163.64 — match Table 11.11, book p. 604

Because these variances range from 59.8259.82 to 223.64223.64, the sample data are far from homogeneous treatment-difference variances. The book reports that when the assumption is false, the actual probability of a Type I error may be as high as .10 or .15 against a nominal .05 (p. 605).

In DMAR: Mauchly’s test from the wide data

DMAR’s mauchly_test() runs Mauchly’s test of sphericity directly on the wide (multivariate) data, so no multivariate model or idata frame has to be assembled first.

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

The test is significant here, agreeing with the unequal variances of the differences above. The book is careful about how much weight this deserves: it cites Keselman, Rogan, Mendoza, and Breen (1980) to the effect that Mauchly’s test has little value as a preliminary test before the test of mean differences (p. 605), and recommends the epsilon adjustments of Section 11.9 regardless of its outcome.

11.9 — Adjusted Univariate Tests

To correct for violations of sphericity, we adjust the degrees of freedom used for the critical FF value. The adjustment is based on Box’s measure of departure from sphericity, ε\varepsilon (epsilon).

  • Perfect sphericity: ε=1.0\varepsilon = 1.0

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

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

11.9.1 — Lower-Bound Adjustment

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

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

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

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

11.9.2 — ε̂\hat{\varepsilon} Adjustment

Greenhouse and Geisser’s ε̂\hat{\varepsilon} estimates the population ε\varepsilon from the sample covariance matrix. Its computational formula is tedious, but car::Anova() reports it (along with ε̃\tilde{\varepsilon}) once the within-subjects design is specified. The two orderings of the same two surnames in this section are deliberate and follow the book: the lower-bound correction is due to Geisser and Greenhouse (1958), whereas ε̂\hat{\varepsilon} derives from Greenhouse and Geisser (1959).

HideShow
# Bind the columns of the wide dataset into a single matrix
Y_matrix <- as.matrix(chapter_11_table_5)

# Fit a multivariate linear model with just an intercept
rm_model <- lm(Y_matrix ~ 1)

# Create a data frame defining the within-subjects design
idata <- data.frame(Month = factor(c("30", "36", "42", "48")))

# Run the Anova with the within-subjects design specified
rm_anova <- Anova(rm_model, idata = idata, idesign = ~Month)

# Display the univariate summary (which includes the sphericity corrections)
rm_summary <- summary(rm_anova, multivariate = FALSE)
rm_summary
HideShow

Univariate Type III Repeated-Measures ANOVA Assuming Sphericity

            Sum Sq num Df Error SS den Df  F value    Pr(>F)    
(Intercept) 559872      1     6624     11 929.7391 5.586e-12 ***
Month          552      3     2006     33   3.0269   0.04322 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


Mauchly Tests for Sphericity

      Test statistic  p-value
Month        0.24265 0.017718


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

       GG eps Pr(>F[GG])  
Month 0.60954    0.07479 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

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

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

The observed FF of 3.03 is still below 3.59, so the null hypothesis is not rejected with the ε̂\hat{\varepsilon} approach either. (R’s exact ε̂\hat{\varepsilon} is 0.60954; the book’s degrees of freedom on p. 606 come from the rounded value .61, which is why 20.13 appears there rather than 20.115.)

11.9.3 — ε̃\tilde{\varepsilon} Adjustment

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

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

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

Again the observed FF of 3.03 falls short of the critical value, so all three adjustments agree with each other, and disagree with the unadjusted test.

11.9.4 — Summary of Four Mixed-Model Approaches

Table 11.12 in the text collects the four approaches. Every one of them uses the same observed F=MSA/MSA×S=3.03F = MS_A / MS_{A \times S} = 3.03; only the degrees of freedom for the critical value differ.

HideShow
tibble(
  Approach   = c("Unadjusted",
                 "Huynh-Feldt (epsilon-tilde)",
                 "Greenhouse-Geisser (epsilon-hat)",
                 "Geisser-Greenhouse lower bound"),
  `Observed F` = rm_summary$univariate.tests["Month", "F value"],
  `df num`   = c(a - 1, eps_HF * (a - 1), 0.61 * (a - 1), 1),
  `df den`   = c((a - 1) * (n - 1), eps_HF * (a - 1) * (n - 1), 0.61 * (a - 1) * (n - 1), n - 1)
) |>
  mutate(`Critical F` = qf(0.95, df1 = `df num`, df2 = `df den`)) |>
  gt() |>
  fmt_number(columns = c(`Observed F`, `Critical F`), decimals = 2) |>
  fmt_number(columns = c(`df num`, `df den`), decimals = 2) |>
  tab_header(title = md("**Table 11.12**. Summary of Four Mixed-Model Approaches, Table 11.5 Data")) |>
  cols_align(align = "center", columns = -Approach)
Table 11.12. Summary of Four Mixed-Model Approaches, Table 11.5 Data
Approach Observed F df num df den Critical F
Unadjusted 3.03 3.00 33.00 2.89
Huynh-Feldt (epsilon-tilde) 3.03 2.17 23.92 3.32
Greenhouse-Geisser (epsilon-hat) 3.03 1.83 20.13 3.59
Geisser-Greenhouse lower bound 3.03 1.00 11.00 4.84
HideShow
#> critical F values 2.89, 3.32, 3.59, 4.84 — match Table 11.12, book p. 608

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

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

The unadjusted test is significant at .05, but the book recommends against ever using it (p. 607), and recommends ε̂\hat{\varepsilon} among the remaining three (p. 609). Once the degrees of freedom are shrunk, the age effect no longer meets the .05 criterion.

In DMAR: all four approaches in one table

DMAR’s anova_within() returns the omnibus within-subjects FF with the unadjusted, Greenhouse–Geisser, Huynh–Feldt, and lower-bound results in a single tidy table, directly from the wide data. The whole of Table 11.12 comes back from one call, with the epsilons, adjusted degrees of freedom, and pp values together.

HideShow
# Omnibus F with no adjustment plus GG, HF, and lower-bound corrections
anova_within(chapter_11_table_5[, c("Months30", "Months36", "Months42", "Months48")])
adjustment F_value df_1 df_2 p_value epsilon
none 3.027 3 33 0.0432 NA
Greenhouse-Geisser 3.027 1.829 20.115 0.0748 0.610
Huynh-Feldt 3.027 2.175 23.920 0.0635 0.725
lower_bound 3.027 1 11 0.1098 0.333
HideShow
#> F = 3.027 throughout; GG eps = .610 with df 1.829 / 20.115; HF eps = .725 with
#> df 2.175 / 23.920; lower-bound eps = .333 with df 1 / 11 — the same quantities
#> car::Anova produced above, and the book's Table 11.12 structure (p. 608)

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

11.10 — Measures of Effect

A statistically significant pp value tells us only that an effect exists, not how large it is. For magnitude we use measures of association strength (omega squared) and standardized mean differences (Cohen’s dd).

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

Omega squared estimates the proportion of total population variance accounted for by the treatment effect. For a one-way within-subjects design, Equation 11.35 isω̂2=(a−1)(MSA−MSA×S)SSTotal+MSS\hat{\omega}^2 = \frac{(a-1)(MS_A - MS_{A \times S})}{SS_{Total} + MS_S}

The denominator requires SSTotalSS_{Total} and MSSMS_S (the mean square for subjects). Rather than hardcoding them, we extract them from the univariate summary of the car::Anova model fitted above.

HideShow
# Save the univariate summary table from our rm_anova model
uni_table <- rm_summary$univariate.tests

# 1. Extract Sum of Squares
SS_A <- uni_table["Month", "Sum Sq"]
SS_AxS <- uni_table["Month", "Error SS"]
SS_S <- uni_table["(Intercept)", "Error SS"] # Subject variance is the intercept's error term

# 2. Extract Degrees of Freedom
df_A <- uni_table["Month", "num Df"]
df_AxS <- uni_table["Month", "den Df"]
df_S <- uni_table["(Intercept)", "den Df"]

# 3. Calculate Mean Squares
MS_A <- SS_A / df_A
MS_AxS <- SS_AxS / df_AxS
MS_S <- SS_S / df_S

# 4. Calculate SS_Total (Equation 11.37)
SS_Total <- SS_A + SS_S + SS_AxS

cat("Mean Squares: MS_A =", round(MS_A, 2), " MS_AxS =", round(MS_AxS, 4), "\n")
HideShow
Mean Squares: MS_A = 184  MS_AxS = 60.7879 
HideShow
cat("Sum of Squares Subjects (SS_S):", round(SS_S, 2), "\n")
HideShow
Sum of Squares Subjects (SS_S): 6624 
HideShow
cat("Total Sum of Squares (SS_Total):", round(SS_Total, 2), "\n\n")
HideShow
Total Sum of Squares (SS_Total): 9182 
HideShow
#> MS_A = 184.00 and MS_AxS = 60.7879 — match book p. 602
#> SS_S = 6624 and SS_Total = 9182 — match book p. 609

# 5. Calculate Omega Squared (Equation 11.35)
# Note: (a - 1) is exactly equal to df_A
omega_sq <- (df_A * (MS_A - MS_AxS)) / (SS_Total + MS_S)
cat("Omega Squared:", round(omega_sq, 4), "\n")
HideShow
Omega Squared: 0.0378 
HideShow
#> .04 — matches book p. 609

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

Standardized mean differences (dd)

For a standardized effect size we must divide a mean difference by a standard deviation, and the choice of standard deviation matters a great deal.

  • It is tempting to use MSA×S\sqrt{MS_{A \times S}}, because that is the error term for the FF test. But subject variance has been partialed out of it, so the denominator is artificially small and the resulting dd is not comparable to a dd from a between-subjects study.

  • Instead we reconstruct the standard deviation as if the data had come from a between-subjects design, by pooling the subject variance (SSSSS_S) and the error variance (SSA×SSS_{A \times S}) back together. That is Equation 11.38:

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

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

# The book notes this equals the square root of the MSW we would compute if the
# data were treated as between-subjects: the mean of the four level variances.
cat("sqrt(mean of the four level variances):", round(sqrt(mean(sample_vars)), 2), "\n")
HideShow
sqrt(mean of the four level variances): 14 
HideShow
#> 14.00 — matches book p. 611 ("averaging these four values and taking the square root")

# Extract specific condition means (from Table 11.5)
mean_30 <- mean(chapter_11_table_5[, 1]) # 103
mean_36 <- mean(chapter_11_table_5[, 2]) # 107
mean_48 <- mean(chapter_11_table_5[, 4]) # 112

# Calculate Cohen's d for specific comparisons
d_36_vs_30 <- (mean_36 - mean_30) / sd_pooled
d_48_vs_30 <- (mean_48 - mean_30) / sd_pooled

cat("\nEffect Size (d) - 36 vs 30 months:", round(d_36_vs_30, 2), "\n")
HideShow

Effect Size (d) - 36 vs 30 months: 0.29 
HideShow
cat("Effect Size (d) - 48 vs 30 months:", round(d_48_vs_30, 2), "\n")
HideShow
Effect Size (d) - 48 vs 30 months: 0.64 
HideShow
#> 0.29 and 0.64 — match book p. 611

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

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

The book reads these as follows (p. 611): the 30-to-36-month difference is on the “small” side, and the 30-to-48-month difference is about halfway between “medium” and “large.” Had we used MSA×S=7.80\sqrt{MS_{A \times S}} = 7.80 instead, the same 9-point difference would have been reported as d=1.15d = 1.15, nearly twice as large, purely because systematic individual differences were excluded from the yardstick.

11.11 — Comparisons among Individual Means

The traditional way to test an individual comparison in a repeated-measures design divides the contrast sum of squares by the interaction mean square (Equation 11.40):

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

with critical values from Equation 11.41 (Tukey) and Equation 11.42 (Scheffé) when other comparisons are to be taken into account. We can compute all of this for the 48-versus-30-month comparison, whose estimate ψ̂=9\hat{\psi} = 9 we have already verified against the Table 11.5 marginal means.

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

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

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

Per-comparison F(.05; 1, 33):    4.139 
HideShow
cat("Bonferroni, C = 6 comparisons:  ", round(qf(1 - 0.05 / 6, 1, (a - 1) * (n - 1)), 3), "\n")
HideShow
Bonferroni, C = 6 comparisons:   7.878 
HideShow
cat("Tukey, q^2 / 2 (Eq. 11.41):     ",
    round(qtukey(0.95, a, (a - 1) * (n - 1))^2 / 2, 3), "\n")
HideShow
Tukey, q^2 / 2 (Eq. 11.41):      7.317 
HideShow
cat("Scheffe, (a - 1)F (Eq. 11.42):  ",
    round((a - 1) * qf(0.95, a - 1, (a - 1) * (n - 1)), 3), "\n")
HideShow
Scheffe, (a - 1)F (Eq. 11.42):   8.675 

These values are not printed in the book; they follow from Equations 11.40 through 11.42 using the mean square MSA×S=60.79MS_{A \times S} = 60.79 and the means already confirmed against Table 11.5 (pp. 598, 602).

The book’s recommendation, however, is that these formulas not be used (p. 612). They lean entirely on sphericity, and Boik (1981) showed that tests of comparisons are far more sensitive to departures from sphericity than the omnibus test is: when MSA×SMS_{A \times S} is too small for a particular contrast the actual error rate can reach .70 for a nominal .05, and when it is too large the power can collapse to near .05. Nor do the ε̂\hat{\varepsilon} and ε̃\tilde{\varepsilon} adjustments fix the power problem. The remedy, a separate error term for each contrast, is what the next two sections preview.

11.12 — Confidence Intervals for Comparisons

Confidence intervals face the same sphericity trap as the FF tests. With a pooled error term, some 95% intervals are too narrow and others too wide.

Let’s reproduce Table 11.13 and see exactly how the pooled-error approach differs from the separate-error approach for McCarthy scores at 48 versus 42 months and at 48 versus 30 months.

1. Pooled error interval. Equation 11.43 assumes every pairwise difference is estimated with the same precision:ψ̂±wMSA×S∑j=1a(cj2/nj)\hat{\psi} \pm w \sqrt{ MS_{A \times S} \sum_{j=1}^{a} (c_j^2 / n_j) }

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

HideShow
df_pooled <- (a - 1) * (n - 1) # 33 degrees of freedom

# Critical t (w) for a per-comparison alpha of .05, two-tailed
w_pooled <- qt(0.975, df_pooled)

# Contrast coefficients for a pairwise comparison (1 and -1)
# sum(c_j^2 / n_j) = (1^2 / 12) + ((-1)^2 / 12) = 2/12
contrast_sum <- 2 / n

margin_pooled <- w_pooled * sqrt(MS_AxS * contrast_sum)
cat("Pooled Margin of Error: +/-", round(margin_pooled, 2), "\n")
HideShow
Pooled Margin of Error: +/- 6.48 
HideShow
#> 6.48 — matches Table 11.13, book p. 614

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

HideShow
df_sep <- n - 1 # 11
w_sep <- qt(0.975, df_sep)

# Comparison 1: 48 Months vs 42 Months
diff_48_42 <- chapter_11_table_5[, 4] - chapter_11_table_5[, 3]
var_diff_48_42 <- var(diff_48_42)
se_48_42 <- sqrt((var_diff_48_42 / 2) * contrast_sum)
margin_sep_48_42 <- w_sep * se_48_42

# Comparison 2: 48 Months vs 30 Months
diff_48_30 <- chapter_11_table_5[, 4] - chapter_11_table_5[, 1]
var_diff_48_30 <- var(diff_48_30)
se_48_30 <- sqrt((var_diff_48_30 / 2) * contrast_sum)
margin_sep_48_30 <- w_sep * se_48_30

ci_comparison <- data.frame(
  Comparison      = c("48 vs 42 months", "48 vs 30 months"),
  Mean_Diff       = c(mean(diff_48_42), mean(diff_48_30)),
  Pooled_Margin   = c(margin_pooled, margin_pooled),
  Separate_Margin = c(margin_sep_48_42, margin_sep_48_30)
)

print(ci_comparison, digits = 3)
HideShow
       Comparison Mean_Diff Pooled_Margin Separate_Margin
1 48 vs 42 months         2          6.48            4.91
2 48 vs 30 months         9          6.48            8.13
HideShow
#> mu4 - mu3: 2.00 +/- 6.48 pooled, 2.00 +/- 4.91 separate
#> mu4 - mu1: 9.00 +/- 6.48 pooled, 9.00 +/- 8.13 separate
#> all four margins and both estimates match Table 11.13, book p. 614

The choice of error term does not move the center of the interval, only its width. Scores spaced close together in time (48 versus 42 months) are estimated much more precisely (margin 4.91) than scores spaced further apart (48 versus 30 months, margin 8.13). The pooled term assigns 6.48 to both.

In DMAR: every pairwise comparison with its own error term

The separate-variances logic generalizes to the whole set of pairwise comparisons. The mainstream route is stats::pairwise.t.test() with paired = TRUE, which uses each pair’s own difference scores. To exercise a full four-condition set we use the Table 11.4 data (book p. 596).

HideShow
# Load the four-condition within-subjects data (Table 11.4)
data(chapter_11_table_4)
four <- chapter_11_table_4
colnames(four) <- c("C1", "C2", "C3", "C4")
four
HideShow
   C1 C2 C3 C4
1   8 10  7  5
2   9  9  8  6
3   7  5  8  4
4   9  6  5  7
5   8  7  7  6
6   5  4  4  3
7   7  6  5  4
8   8  8  6  6
9   9  8  6  5
10  7  7  4  5
HideShow
# Base/mainstream route: all six paired comparisons, Bonferroni-adjusted
four_long <- data.frame(
  Value     = unlist(four),
  Condition = factor(rep(colnames(four), each = nrow(four))),
  Subject   = factor(rep(seq_len(nrow(four)), times = ncol(four)))
)

pairwise.t.test(x = four_long$Value, g = four_long$Condition,
                paired = TRUE, p.adjust.method = "bonferroni")
HideShow

    Pairwise comparisons using paired t tests 

data:  four_long$Value and four_long$Condition 

   C1      C2    C3   
C2 0.794   -     -    
C3 0.026   0.640 -    
C4 5.5e-06 0.027 0.727

P value adjustment method: bonferroni 

pairwise.t.test() reports the adjusted significance levels alone. DMAR’s pairwise_within() reports the mean difference, its standard deviation, the per-pair tt statistic, and a confidence interval for every comparison, all in one tidy table, taken straight from the wide data.

HideShow
# All pairwise within-subjects comparisons, separate variances, Bonferroni-adjusted
pairwise_within(four[, c("C1", "C2", "C3", "C4")], adjust = "bonferroni")
contrast mean_difference sd_difference t_value df p_value p_adjusted ci_lower ci_upper n_pairs
C2 - C1 -0.700 1.337 -1.655 9 0.1323 0.7938 -1.657 0.257 10
C3 - C1 -1.700 1.418 -3.791 9 0.0043 0.0257 -2.714 -0.686 10
C4 - C1 -2.600 0.699 -11.759 9 < 0.0001 < 0.0001 -3.100 -2.100 10
C3 - C2 -1.000 1.764 -1.793 9 0.1066 0.6395 -2.262 0.262 10
C4 - C2 -1.900 1.595 -3.767 9 0.0044 0.0266 -3.041 -0.759 10
C4 - C3 -0.900 1.663 -1.711 9 0.1212 0.7274 -2.090 0.290 10

Confidence level: 95%

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

The two routes agree on every adjusted pp value. Each row uses its own difference-score variance, so the confidence intervals widen or narrow with the correlation between the two conditions being compared, exactly as the pooled-versus-separate comparison on Table 11.5 showed by hand.

11.13 — Confidence Intervals with Pooled and Separate Variances

The book marks this section “Optional.” It answers the question left open by Section 11.12: why is the separate-variance approach actually preferable, rather than merely different?

It comes down to the correlations between the repeated measures. By Equation 11.30,σYl−Ym2=σYl2+σYm2−2ρlmσYlσYm\sigma^2_{Y_l - Y_m} = \sigma^2_{Y_l} + \sigma^2_{Y_m} - 2\rho_{lm}\sigma_{Y_l}\sigma_{Y_m}

We can show in R how ρ\rho drives the variance of the difference, using the population values of the simulation the book runs in this section: every level has variance 225, levels 1 and 2 correlate .8, and levels 1 and 4 correlate .2.

HideShow
# Both conditions have a variance of 225 (SD = 15)
var_Y1 <- 225
var_Y2 <- 225
sd_Y1 <- sqrt(var_Y1)
sd_Y2 <- sqrt(var_Y2)

# Scenario A: Highly correlated conditions (levels 1 and 2, rho = 0.8)
r_high <- 0.8
var_diff_high <- var_Y1 + var_Y2 - (2 * r_high * sd_Y1 * sd_Y2)

# Scenario B: Weakly correlated conditions (levels 1 and 4, rho = 0.2)
r_low <- 0.2
var_diff_low <- var_Y1 + var_Y2 - (2 * r_low * sd_Y1 * sd_Y2)

cat("Variance of Y2 - Y1 (rho = .8):", var_diff_high, "\n")
HideShow
Variance of Y2 - Y1 (rho = .8): 90 
HideShow
cat("Variance of Y4 - Y1 (rho = .2):", var_diff_low, "\n")
HideShow
Variance of Y4 - Y1 (rho = .2): 360 
HideShow
#> 90 and 360 — match book p. 617; the first comparison is one-fourth as variable

When two conditions are highly correlated, the true variance of their difference shrinks, and a pooled error term makes the interval systematically too wide, costing precision and power. When two conditions are weakly correlated, the true variance of their difference is large, and the pooled term makes the interval systematically too narrow, so coverage falls below the stated 95%. Unless sphericity holds, the separate-variance approach is the one to use.

Reproducing Figure 11.2

Figure 11.2 (book p. 616) displays a simulation described on pp. 615–617. Data are generated for a four-level within-subjects design with n=50n = 50 subjects. Every level has population mean 50 except level 2, whose mean is 54, so the true value of μ2−μ1\mu_2 - \mu_1 is 4 and the true value of μ4−μ1\mu_4 - \mu_1 is 0. Each level has a standard deviation of 15, but sphericity is deliberately broken: the population correlation matrix (Table 11.14, book p. 615) has levels 1 and 2 correlating .8 while levels 1 and 4 correlate only .2. Across 10 replications, each contrast gets two confidence intervals centered at the same estimate: a pooled interval (Equation 11.43, using MSA×SMS_{A \times S}) and a separate interval (Equation 11.44, using that pair’s own difference-score variance). Because the simulation is random, we fix set.seed(113) so the figure is reproducible; the book’s own figure comes from a different draw, so the individual intervals differ while the pattern does not.

HideShow
# Population from Table 11.14 (book p. 615): 4 levels, sd = 15, sphericity violated.
a_sim  <- 4
n_sim  <- 50
mu     <- c(50, 54, 50, 50)     # mu2 - mu1 = 4 (true); mu4 - mu1 = 0 (true)
sd_    <- 15
R      <- matrix(c(1.0, 0.8, 0.5, 0.2,
                   0.8, 1.0, 0.8, 0.5,
                   0.5, 0.8, 1.0, 0.8,
                   0.2, 0.5, 0.8, 1.0), nrow = 4, byrow = TRUE)
Sigma  <- (sd_^2) * R           # variance 225 on the diagonal

# Critical t for a per-comparison interval at alpha = .05 (two-tailed). Pooled
# intervals use df = (a - 1)(n - 1) (Eq. 11.43); separate intervals use df = n - 1
# (Eq. 11.44), because each pair contributes a single difference score per subject.
reps   <- 10
w_pool <- qt(0.975, (a_sim - 1) * (n_sim - 1))
w_sep  <- qt(0.975, n_sim - 1)

set.seed(113)
sim <- lapply(seq_len(reps), function(r) {
  Y <- MASS::mvrnorm(n_sim, mu, Sigma)

  # Pooled error term: MS_{A x S} from the additive (subject + level) model.
  level_means <- colMeans(Y)
  subj_means  <- rowMeans(Y)
  grand       <- mean(Y)
  resid_AxS   <- Y - outer(subj_means, level_means, "+") + grand
  MS_AxS_sim  <- sum(resid_AxS^2) / ((a_sim - 1) * (n_sim - 1))

  one_contrast <- function(cj, contrast_label) {
    psi  <- sum(cj * level_means)                         # point estimate
    me_p <- w_pool * sqrt(MS_AxS_sim * sum(cj^2) / n_sim)  # pooled half-width
    idx  <- which(cj != 0)                                 # the two active levels
    Dij  <- Y[, idx[1]] * cj[idx[1]] + Y[, idx[2]] * cj[idx[2]]
    me_s <- w_sep * sqrt(stats::var(Dij) / n_sim)          # separate half-width
    data.frame(
      Contrast = contrast_label, Replication = r, Estimate = psi,
      Pooled_lo = psi - me_p, Pooled_hi = psi + me_p,
      Separate_lo = psi - me_s, Separate_hi = psi + me_s
    )
  }

  rbind(
    one_contrast(c(-1, 0, 0, 1), "mu[4] - mu[1]"),       # true value 0
    one_contrast(c(-1, 1, 0, 0), "mu[2] - mu[1]")        # true value 4
  )
})
sim <- do.call(rbind, sim)

# Long form for plotting: one row per (replication, contrast, error-term method),
# offset slightly so the pooled and separate lines do not overprint.
ci_long <- rbind(
  transform(sim, Method = "Pooled variance",   lo = Pooled_lo,   hi = Pooled_hi,
            yoff = Replication - 0.16),
  transform(sim, Method = "Separate variance", lo = Separate_lo, hi = Separate_hi,
            yoff = Replication + 0.16)
)
ci_long$Method <- factor(ci_long$Method,
                         levels = c("Pooled variance", "Separate variance"))

# Panel order: the weakly correlated pair (mu4 - mu1) on top, which is the order
# the text discusses the two contrasts in. Without this the facets would fall in
# alphabetical order and put mu2 - mu1 first.
contrast_levels <- c("mu[4] - mu[1]", "mu[2] - mu[1]")
ci_long$Contrast <- factor(ci_long$Contrast, levels = contrast_levels)

# Reference lines: the true population value of each contrast.
truth <- data.frame(Contrast = factor(contrast_levels, levels = contrast_levels),
                    true_value = c(0, 4))
HideShow
ggplot(ci_long, aes(y = yoff, color = Method, linetype = Method)) +
  geom_vline(data = truth, aes(xintercept = true_value),
             color = "#0C2340", linewidth = 0.7) +
  geom_segment(aes(x = lo, xend = hi, yend = yoff), linewidth = 0.7) +
  geom_point(aes(x = Estimate), size = 1.3) +
  facet_wrap(~ Contrast, ncol = 1, labeller = label_parsed) +
  scale_y_reverse(breaks = 1:10) +
  scale_x_continuous(breaks = seq(-12, 12, 2), limits = c(-12, 12)) +
  scale_linetype_manual(values = c("Pooled variance"   = "solid",
                                   "Separate variance" = "dashed")) +
  labs(title = "Figure 11.2. Confidence intervals over 10 replications",
       subtitle = "Reference line marks the true population difference in each panel",
       x = "Estimated mean difference", y = "Replication",
       color = NULL, linetype = NULL) +
  theme(legend.position = "top")
Figure 11.2. Confidence intervals over 10 replications for two population mean differences, using pooled versus separate error terms. Solid lines are pooled; dashed lines are separate.

Figure 11.2. Confidence intervals over 10 replications for two population mean differences, using pooled versus separate error terms. Solid lines are pooled; dashed lines are separate.

The top panel (μ4−μ1\mu_4 - \mu_1, where levels 1 and 4 correlate only .2) shows the separate-variance intervals (dashed) running wider than the pooled intervals (solid): the pooled term understates how variable this far-apart comparison really is. The bottom panel (μ2−μ1\mu_2 - \mu_1, where levels 1 and 2 correlate .8) shows the reverse, with the separate intervals narrower, so the pooled term wastes precision and power. The point estimate is identical for the two methods within a replication; only the width differs. We can count the coverage directly rather than reading it off the figure.

HideShow
coverage <- function(df, true_value) {
  c(Pooled   = sum(df$Pooled_lo   <= true_value & df$Pooled_hi   >= true_value),
    Separate = sum(df$Separate_lo <= true_value & df$Separate_hi >= true_value))
}
s41 <- subset(sim, Contrast == "mu[4] - mu[1]")
s21 <- subset(sim, Contrast == "mu[2] - mu[1]")

cat("Intervals containing the true value of mu4 - mu1 (0):\n"); print(coverage(s41, 0))
HideShow
Intervals containing the true value of mu4 - mu1 (0):
HideShow
  Pooled Separate 
       7        9 
HideShow
cat("\nIntervals containing the true value of mu2 - mu1 (4):\n"); print(coverage(s21, 4))
HideShow

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

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

With this seed, the separate-variance intervals contain the true value of μ4−μ1\mu_4 - \mu_1 in 9 of 10 replications against 7 of 10 for the pooled intervals. The book’s own 10 replications (p. 615) come out 9 and 8. The individual counts differ because the two sets of replications are different random draws, and 10 replications is far too few to pin down a coverage rate; what both show is the same qualitative pattern. The half-widths make the mechanism explicit: the pooled half-width is the same number in both panels, while the separate half-width is larger than it for the weakly correlated pair and smaller for the strongly correlated pair. As the book puts it, the pooled approach has the right average width across all pairwise comparisons while none of the individual intervals need have the right width (p. 614).

11.14 — Considerations in Designing Within-Subjects Experiments

11.14.1 — Order Effects

Within-subjects designs must protect internal validity against confounds with time. The standard solution with two levels is a crossover design, in which half the subjects receive Treatment A first and the other half receive Treatment B first, so that the main effect of order is controlled.

11.14.2 — Differential Carryover Effects

A crossover design controls the main effect of order but is vulnerable to differential carryover: the lingering effect of Treatment 1 onto Treatment 2 differs from the lingering effect of Treatment 2 onto Treatment 1.

Table 11.15 gives a set of plausible means for a free-recall study in which half the children receive a chunking strategy first and half receive the control condition first. Computing the marginal means shows how differential carryover masks the true treatment effect.

HideShow
# Create the data matrix from Table 11.15
carryover_matrix <- matrix(
  c(10, 20,  # Control first, then Strategy
    20, 20), # Strategy first, then Control
  nrow = 2,
  byrow = TRUE,
  dimnames = list(
    Group = c("Control -> Strategy", "Strategy -> Control"),
    Time = c("Phase 1", "Phase 2")
  )
)

print(carryover_matrix)
HideShow
                     Time
Group                 Phase 1 Phase 2
  Control -> Strategy      10      20
  Strategy -> Control      20      20
HideShow
#> 10, 20 / 20, 20 — matches Table 11.15, book p. 618

# Marginal means for the "Treatment"
# Control scores are at [1,1] and [2,2]; Strategy scores are at [1,2] and [2,1]
mean_control <- mean(c(carryover_matrix[1, 1], carryover_matrix[2, 2]))
mean_strategy <- mean(c(carryover_matrix[1, 2], carryover_matrix[2, 1]))

cat(
  "\nMarginal Mean for Control:", mean_control,
  "\nMarginal Mean for Strategy:", mean_strategy,
  "\nApparent Effect:", mean_strategy - mean_control,
  "\nEffect in the control-first group only:",
  carryover_matrix[1, 2] - carryover_matrix[1, 1],
  "\n"
)
HideShow

Marginal Mean for Control: 15 
Marginal Mean for Strategy: 20 
Apparent Effect: 5 
Effect in the control-first group only: 10 
HideShow
#> control mean 15, strategy mean 20, apparent 5-point effect — matches book p. 618
#> the control-first group improves by 10 points, which the book reads as the
#> more plausible estimate of the true effect (p. 618)

The marginal means suggest the strategy improves scores by 5 points (20 versus 15). But the children who received the control condition first improved by 10 points, while those who received the strategy first showed no change at all, because strategy training produced a persistent change they carried into the control phase. When effects are intended to persist, the book’s advice is to abandon the within-subjects design and use a between-subjects design (p. 619).

11.14.3 — Controlling for Order Effects with More Than Two Levels: Latin Square Designs

With more than two levels, testing every possible order quickly becomes impractical: a=4a = 4 conditions have 4!=244! = 24 orders, and a=5a = 5 have 120 (book p. 619).

A more efficient deterministic control is a Latin square, in which each treatment appears exactly once in each sequential position. The text warns against the cyclic square of Table 11.16, because there treatment B always follows A, C always follows B, and so on, which is exactly the arrangement most vulnerable to carryover. Instead, randomly select one of the standard squares of Table 11.17 and randomly permute its rows and columns.

The book works this through with Standard Square 3 and the random orders 3, 1, 4, 2 for rows and 3, 4, 1, 2 for columns (p. 620), which we can reproduce exactly.

HideShow
# Standard Square 3 from Table 11.17 (book p. 621)
sq3 <- matrix(
  c("A", "B", "C", "D",
    "B", "A", "D", "C",
    "C", "D", "B", "A",
    "D", "C", "A", "B"),
  nrow = 4, byrow = TRUE
)
cat("Standard Square 3:\n")
HideShow
Standard Square 3:
HideShow
print(sq3)
HideShow
     [,1] [,2] [,3] [,4]
[1,] "A"  "B"  "C"  "D" 
[2,] "B"  "A"  "D"  "C" 
[3,] "C"  "D"  "B"  "A" 
[4,] "D"  "C"  "A"  "B" 
HideShow
#> matches Square 3 of Table 11.17, book p. 621

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

After the book's row permutation (3, 1, 4, 2):
HideShow
print(sq3[c(3, 1, 4, 2), ])
HideShow
     [,1] [,2] [,3] [,4]
[1,] "C"  "D"  "B"  "A" 
[2,] "A"  "B"  "C"  "D" 
[3,] "D"  "C"  "A"  "B" 
[4,] "B"  "A"  "D"  "C" 
HideShow
#> C D B A / A B C D / D C A B / B A D C — matches book p. 620

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

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

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

HideShow
set.seed(113)

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

randomized_square <- sq3[row_perm, col_perm]

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

Randomized Latin Square:
HideShow
print(randomized_square)
HideShow
     [,1] [,2] [,3] [,4]
[1,] "C"  "A"  "B"  "D" 
[2,] "D"  "B"  "A"  "C" 
[3,] "A"  "D"  "C"  "B" 
[4,] "B"  "C"  "D"  "A" 
HideShow
# Each treatment still appears exactly once in each position.
apply(randomized_square, MARGIN = 2, FUN = function(x) sort(x))
HideShow
     [,1] [,2] [,3] [,4]
[1,] "A"  "A"  "A"  "A" 
[2,] "B"  "B"  "B"  "B" 
[3,] "C"  "C"  "C"  "C" 
[4,] "D"  "D"  "D"  "D" 

Permuting the rows and columns of the four standard squares is what gives the 576 possible Latin squares for a=4a = 4 reported on book p. 620, and it breaks the systematic treatment sequences that make the cyclic square a poor choice.

11.15 — Relative Advantages of Between-Subjects and Within-Subjects Designs

The main advantage of a within-subjects design is efficiency and power: using subjects as their own controls removes systematic individual differences from the error term.

Venter and Maxwell (1999) give formulas relating the total number of subjects needed in a within-subjects design (NWN_W) to that in a between-subjects posttest-only design (NBN_B), assuming any position effects have been modeled (Equation 11.45), and to a pretest-posttest design analyzed with ANCOVA (Equation 11.46):

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

Where ρ\rho is the population correlation between scores at the two levels. We can reproduce all four columns of Table 11.18, which gives the total sample size needed for power of .80 to detect a medium difference between two means.

HideShow
# Base sample size for the between-subjects posttest-only design
N_B <- 128

# Correlation values used in Table 11.18
rho_values <- c(0.0, 0.3, 0.5, 0.7)

# Within-subjects, from Equation 11.45
N_W_exact <- (N_B * (1 - rho_values)) / 2

# Pretest-posttest with ANCOVA, by rearranging Equation 11.46
N_PP_exact <- N_W_exact * 2 * (1 + rho_values)

# Pretest-posttest analyzed with change scores: the variance of a change score
# is 2 sigma^2 (1 - rho), so the design needs 2(1 - rho) times the posttest-only N
N_change_exact <- N_B * 2 * (1 - rho_values)

power_comparison <- data.frame(
  Correlation_Rho  = rho_values,
  Between_Posttest = N_B,
  Between_ANCOVA   = ceiling(N_PP_exact),
  Between_Change   = ceiling(N_change_exact),
  Within_Subjects  = ceiling(N_W_exact)
)

print(power_comparison)
HideShow
  Correlation_Rho Between_Posttest Between_ANCOVA Between_Change
1             0.0              128            128            256
2             0.3              128            117            180
3             0.5              128             96            128
4             0.7              128             66             77
  Within_Subjects
1              64
2              45
3              32
4              20
HideShow
#> 128 / 128 / 256 / 64, 128 / 117 / 180 / 45, 128 / 96 / 128 / 32, 128 / 66 / 77 / 20
#> all sixteen cells match Table 11.18, book p. 623

The sample sizes are rounded up, since a design cannot use a fraction of a subject; at ρ=0.3\rho = 0.3 and ρ=0.7\rho = 0.7 the unrounded within-subjects values are 44.8 and 19.2.

The table makes three points, following the book (p. 624):

  • Even with zero correlation between conditions, the within-subjects design needs only half the subjects (64 versus 128), because each subject contributes two data points.

  • As the correlation grows, the requirement falls further still: at ρ=0.7\rho = 0.7, 20 subjects give the power that 128 would give in a between-subjects posttest-only design.

  • Including a pretest and analyzing change scores can be far worse than ignoring the pretest altogether (256 versus 128 at ρ=0\rho = 0), which is why ANCOVA is almost always the better analysis of a randomized pretest-posttest design.

11.16 — Power Analysis and Sample Size Planning

In a within-subjects design, power depends heavily on the correlation (ρ\rho) between the repeated measures. When scores are positively correlated, the error variance shrinks, so the noncentrality parameter (λ\lambda) and power both rise.

The text compares the noncentrality parameter of a one-way between-subjects design with that of a one-way within-subjects design (Equations 4.49 and 11.50):

Between-subjects:λ=Nf2\lambda = N f^2

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

For power of .80 to detect a medium effect (f=0.25f = 0.25) across a=3a = 3 conditions, the book reports that a between-subjects design requires N=159N = 159 in total, or 53 per group (p. 626). Let’s confirm the noncentrality parameter and the power that follows from it, then see how the within-subjects requirement changes with ρ\rho.

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

# Scenario 1: Between-subjects
N_between <- 159
lambda_between <- N_between * f^2
cat("Between-subjects lambda:", lambda_between, "\n")
HideShow
Between-subjects lambda: 9.9375 
HideShow
cat("Critical F(.05; 2, 156):", round(qf(0.95, df1 = 2, df2 = N_between - a_power), 3), "\n")
HideShow
Critical F(.05; 2, 156): 3.054 
HideShow
cat("Power:", round(pf(qf(0.95, 2, N_between - a_power), df1 = 2, df2 = N_between - a_power,
                       ncp = lambda_between, lower.tail = FALSE), 3), "\n")
HideShow
Power: 0.805 
HideShow
#> lambda = 9.9375 and critical F = 3.054, giving power of about .80 — match book p. 626

# Scenario 2: Within-subjects, solving Equation 11.50 for n
# lambda = (a * n * f^2) / (1 - rho)  =>  n = lambda * (1 - rho) / (a * f^2)
n_for_rho <- function(rho) (lambda_between * (1 - rho)) / (a_power * f^2)
cat("\nRequired n for the within-subjects design (rho = 0):  ", n_for_rho(0), "\n")
HideShow

Required n for the within-subjects design (rho = 0):   53 
HideShow
cat("Required n for the within-subjects design (rho = 0.5):",
    n_for_rho(0.5), "-> round up to", ceiling(n_for_rho(0.5)), "\n")
HideShow
Required n for the within-subjects design (rho = 0.5): 26.5 -> round up to 27 

When ρ=0\rho = 0, the within-subjects design needs 53 subjects in total to reach the same λ\lambda as the between-subjects design, which needed 53 per group, or 159 in all (book p. 626). When the correlation rises to a more realistic ρ=0.5\rho = 0.5, the closed form halves that to 26.5, or 27 subjects. The book reports 28 for this case (p. 627), from software that solves for the sample size directly instead of matching noncentrality parameters as the closed form does, and it is explicit that 28 is the requirement whether the unadjusted or the ε̂\hat{\varepsilon}-adjusted test is used. The closed form lands slightly lower because equating λ\lambda to the between-subjects value ignores the degrees of freedom the within-subjects test actually has. The book also notes that at ρ=0\rho = 0 the adjusted test needs 54 rather than 53, so the adjustment costs very little here.

Unequal correlations

Compound symmetry, in which every condition correlates equally with every other, is rarely met in practice. The book works through a case where it fails: population means of 10, 13, and 16, population variance 96 (which implies f=0.25f = 0.25), and a correlation matrix whose entries differ (book p. 627).

GLIMMPSE and SAS GLMPOWER, which require a value for each individual correlation, both give a required sample size of 33 for power of .80 with the recommended ε̂\hat{\varepsilon}-adjusted test (book p. 627). The book then names the package an R user is likeliest to reach for: as of its writing Superpower computes power from a given sample size rather than solving for the sample size, so the book uses it the other way round, to confirm that at N=33N = 33 “the power is indeed .80 (within sampling variability and rounding error)” (p. 627). Reproducing that confirmation is what this subsection does, by hand, in base R.

It is worth going slowly, because this is the one place in the chapter where naming a test is not enough to name a number. Once sphericity fails, the FF statistic no longer follows a noncentral FF distribution exactly — the book makes precisely this point on p. 627 — so for each candidate test the distribution the statistic is referred to and the distribution it actually follows come apart. The subsections below take the candidates in turn: the unadjusted test, for which Equation 11.50’s average correlation implies .8776 while the matrix the book prints delivers about .827; the Greenhouse–Geisser test with ε\varepsilon treated as known, .8384; and the Greenhouse–Geisser test a researcher can actually run, .8045, which is the book’s .80 and the figure its 33 rests on. These are not competing attempts at one number; they answer different questions. This is the part of the book’s power discussion that is hardest to follow along with in R, because software reports one of them and the output label rarely says which.

The design, and Equation 11.50 by hand
HideShow
# The correlation matrix R from the textbook (book p. 627)
R_power <- matrix(
  c(1.0, 0.6, 0.3,
    0.6, 1.0, 0.6,
    0.3, 0.6, 1.0),
  nrow = 3, byrow = TRUE
)

# The population means, the population variance, and the covariance matrix
# they imply. The book sets the variance to 96.
mu_power    <- c(10, 13, 16)
var_power   <- 96
Sigma_power <- var_power * R_power
n_power     <- 33                 # the book's required sample size

# Equation 3.91: the ratio of the variance of the population means to the
# error variance is f^2, so f is the square root of that ratio. Here the
# design is given by the means and the variance, so f follows from them
# rather than being assumed, and the rest of the subsection uses that f.
sigma_m_sq <- mean((mu_power - mean(mu_power))^2)
f_implied  <- sqrt(sigma_m_sq / var_power)
cat("f implied by the means and the variance:", f_implied, "\n")
HideShow
f implied by the means and the variance: 0.25 
HideShow
#> 0.25 — matches book p. 627, and the f of the two scenarios above

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

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

Notice what that calculation did with the correlation matrix: it replaced all three correlations by their average. That is the reduction the book describes on p. 627 as the older approach, taken by programs that “rely on specifying a mean value for the population correlations.” It is worth knowing exactly what the reduction costs, and the answer is: nothing at all, for the noncentrality parameter. The error term of the within-subjects FF has expectation tr(Σ*)/(a−1)\mathrm{tr}(\Sigma^{*}) / (a - 1), where Σ*\Sigma^{*} is the covariance matrix of a set of orthonormal contrasts among the conditions, and that quantity equals σ2(1−ρ‾)\sigma^2 (1 - \bar{\rho}) for any correlation matrix. Building Σ*\Sigma^{*} also gives us ε\varepsilon, which the book (p. 628) rightly calls tedious to compute from the individual correlations by hand — but which is three lines of R:

HideShow
# A set of orthonormal contrasts among the a condition means: Helmert
# contrasts, each scaled to unit length, so that U %*% t(U) is the identity
U_power    <- t(apply(t(contr.helmert(a_power)), 1,
                      function(r) r / sqrt(sum(r^2))))
Sigma_star <- U_power %*% Sigma_power %*% t(U_power)
b_df       <- a_power - 1   # number of contrasts, and the numerator df

# The expected error term, two ways
cat("tr(Sigma*) / (a - 1):      ", sum(diag(Sigma_star)) / b_df, "\n")
HideShow
tr(Sigma*) / (a - 1):       48 
HideShow
cat("sigma^2 * (1 - rho-bar):   ", var_power * (1 - rho_bar), "\n")
HideShow
sigma^2 * (1 - rho-bar):    48 
HideShow
#> both 48 — the average correlation reproduces the error term exactly

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

So λ=12.375\lambda = 12.375 is not an approximation: it is the exact noncentrality parameter of this design, unequal correlations and all. What the average correlation cannot capture is the shape of the distribution. When sphericity fails, 𝑀𝑆A×S\mathit{MS}_{A \times S} is a weighted sum of chi-square variables rather than a single scaled one, and ε\varepsilon is exactly the summary of Σ*\Sigma^{*} that measures how far from a single scaled chi-square it falls. Every disagreement in the rest of this subsection comes from how a method handles ε\varepsilon, never from λ\lambda.

Quantity 1 — the power Equation 11.50 implies

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

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

power_un <- pf(crit_un, df1 = df1_un, df2 = df2_un,
               ncp = lambda_power, lower.tail = FALSE)
cat("Critical F(.05; 2, 64):", round(crit_un, 3), "\n")
HideShow
Critical F(.05; 2, 64): 3.14 
HideShow
cat("Power implied by Equation 11.50 at n = 33:", round(power_un, 4), "\n")
HideShow
Power implied by Equation 11.50 at n = 33: 0.8776 
HideShow
#> critical F = 3.14 and power = .8776, the figure for the compound-symmetric
#> design that the average correlation describes

# What the positive correlations buy, on the effect-size scale power software
# usually prints: the design's own partial eta-squared and the f it implies
eta_p_sq_power <- lambda_power / (lambda_power + df2_un)
cat("Effective partial eta-squared:", round(eta_p_sq_power, 4),
    "-> effective f:", round(sqrt(eta_p_sq_power / (1 - eta_p_sq_power)), 4), "\n")
HideShow
Effective partial eta-squared: 0.162 -> effective f: 0.4397 

That is 87.76%, and the last two lines make concrete how much the repeated measurements are worth: a raw medium effect (f=0.25f = 0.25) behaves like an effective f≈0.44f \approx 0.44, with ηp2≈0.16\eta_p^2 \approx 0.16, because each subject serves as their own control. The same 87.76355% is what Superpower’s ANOVA_exact() reports for this design with no correction applied.

What 87.76% is not is the power of the unadjusted test under the matrix the book prints. Being referred to a distribution does not make a statistic follow it, which is the point made just before this subsection: when sphericity fails, 𝑀𝑆A×S\mathit{MS}_{A \times S} is a weighted sum of chi-square variables, so the ratio is not a noncentral FF and its .05 critical value is not really a .05 critical value. What the unadjusted test does here can be found out by running it on data from this Σ\Sigma and counting.

HideShow
# One replicate of the one-way within-subjects omnibus test, on a sample drawn
# from the population (mu, Sigma). correction = "none" is the unadjusted test;
# correction = "GG" estimates epsilon-hat from the replicate's own data, which
# is what a researcher does. Returns TRUE if the test rejects.
omnibus_reject <- function(n, mu, Sigma, U, correction = c("none", "GG"),
                           alpha = 0.05) {
  correction <- match.arg(correction)
  b <- nrow(U)
  D <- MASS::mvrnorm(n = n, mu = mu, Sigma = Sigma) %*% t(U)  # contrast scores
  S <- cov(D)

  F_obs <- n * sum(colMeans(D)^2) / sum(diag(S))
  eps   <- switch(correction,
                  none = 1,                                  # no correction
                  GG   = sum(diag(S))^2 / (b * sum(S^2)))    # from THIS sample
  F_obs > qf(1 - alpha, df1 = b * eps, df2 = b * (n - 1) * eps)
}

set.seed(113)
reps_power <- 50000
hits_un <- replicate(reps_power,
                     omnibus_reject(n_power, mu_power, Sigma_power, U_power,
                                    correction = "none"))

cat("Simulated power of the unadjusted test at n = 33:", round(mean(hits_un), 4),
    "  Monte Carlo SE:",
    round(sqrt(mean(hits_un) * (1 - mean(hits_un)) / reps_power), 4), "\n")
HideShow
Simulated power of the unadjusted test at n = 33: 0.8288   Monte Carlo SE: 0.0017 
HideShow
#> .8288 (SE .0017) — about .827, five points below the .8776 above

So under the book’s own correlation matrix the unadjusted test has power of about .827 at n=33n = 33, not .8776. The closed form in Quantity 3 puts it at .8268, and this simulation lands about one Monte Carlo standard error above that. The .8776 is what Equation 11.50’s average correlation implies, and it is the right answer for the design that average describes — the compound-symmetric ρ‾=.5\bar{\rho} = .5 design of the previous subsection, where sphericity does hold and the reference distribution is the right one. It is not a property of the unequal-correlation design this subsection is about.

That distinction is not local to this example. The book states it directly when it turns to the two-factor case: “if sphericity does not hold, we cannot simply rely on the mean correlation, and must instead specify each element of the covariance (or correlation) matrix” (p. 685). Chapter 12 of these notes works through what that costs, reproducing the table of required sample sizes on book p. 686 from the full matrix rather than from its average. The book sets an exercise on the Type I error side of the same point (p. 641, Exercise 27), where the reader computes the rejection rate of the unadjusted test under a non-spherical matrix with the null hypothesis true. Either way, .8776 and .827 are both reference points rather than planning figures, because the book is explicit (p. 627) that it does not recommend the unadjusted test at all.

Quantity 2 — the Greenhouse–Geisser test with ε\varepsilon treated as known

The textbook correction multiplies both degrees of freedom by ε\varepsilon. If we pretend ε\varepsilon is known and equal to its population value, the noncentrality is rescaled along with the degrees of freedom, and the power is again one pf() call:

HideShow
df1_known <- b_df * eps_pop
df2_known <- b_df * (n_power - 1) * eps_pop

power_gg_known <- pf(qf(0.95, df1 = df1_known, df2 = df2_known),
                     df1 = df1_known, df2 = df2_known,
                     ncp = lambda_power * eps_pop, lower.tail = FALSE)
cat("GG power with epsilon treated as known:", round(power_gg_known, 4), "\n")
HideShow
GG power with epsilon treated as known: 0.8384 

This is the quantity that ANOVA_exact(correction = "GG") reports, and the three lines above reproduce its 83.84% for this design to four decimals. It is a clearly defined and clearly documented quantity: the power of a Greenhouse–Geisser test whose correction factor is the population ε\varepsilon. It is the right thing to report if the question is how much the non-sphericity costs with the correction held fixed. It is not the quantity the book’s 33 rests on, for a reason that has nothing to do with the arithmetic: no researcher can run that test. The population ε\varepsilon is unknown, and the test that actually gets run substitutes ε̂\hat{\varepsilon} computed from the very same data that produce FF.

Quantity 3 — the Greenhouse–Geisser test a researcher actually runs

This is the book’s quantity, and the one SAS GLMPOWER reports under mtest=gg. Because ε̂\hat{\varepsilon} and FF are computed from the same sample, they are not independent, and the power is not a single noncentral FF tail. SAS uses the UNIREP approximation of Muller and Barton (1989), as refined by Muller, Edwards, Simpson, and Taylor (2007): the numerator and denominator degrees of freedom and the noncentrality are all rescaled from the eigenvalues of Σ*\Sigma^{*}, and the critical value is taken at an approximation to E[ε̂]\mathrm{E}[\hat{\varepsilon}] rather than at ε\varepsilon. Those are documented closed-form expressions, so they can be written out directly:

HideShow
# The UNIREP approximation for the one-way within-subjects omnibus test.
# mu and Sigma are the population means and covariance matrix; n is the
# number of subjects; test says which critical value the statistic is judged
# against, the epsilon-hat-corrected one ("GG") or the nominal one
# ("uncorrected"). Returns the power, and the pieces it is built from.
power_unirep <- function(mu, Sigma, n, alpha = 0.05,
                         test = c("GG", "uncorrected")) {
  test <- match.arg(test)
  a <- length(mu); rM <- a - 1; nu <- n - 1

  # orthonormal contrasts, and the contrast covariance matrix and means
  U     <- t(apply(t(contr.helmert(a)), 1, function(r) r / sqrt(sum(r^2))))
  Estar <- U %*% Sigma %*% t(U)
  ev    <- eigen(Estar, symmetric = TRUE)
  phi   <- ev$values                       # eigenvalues of Sigma*
  theta <- as.numeric(U %*% mu)

  # per-eigenvector noncentrality contributions
  om <- n * as.numeric(diag(t(ev$vectors) %*% outer(theta, theta) %*%
                              ev$vectors)) / phi

  # the four trace-like sums the approximation is built from
  S1 <- sum(phi);    S2 <- sum(phi * om)
  S3 <- sum(phi^2);  S4 <- sum(phi^2 * om)

  # rescaled df and noncentrality (Muller & Barton 1989, Muller et al. 2007)
  Rs1      <- (S3 + 2 * S4) / (S1 + 2 * S2)
  Rs2      <- S3 / S1
  nu1_star <- S1 / Rs1
  nu2_star <- nu * S1 / Rs2
  lambda   <- S2 / Rs1

  # the Muller-Barton closed-form approximation to E[epsilon-hat], which is
  # what sets the critical value for the GG test
  Et1       <- 2 * nu * S3 + nu^2 * S1^2
  Et2       <- nu * (nu + 2) * S3 +
               2 * nu * sum(outer(phi, phi)[lower.tri(diag(rM))])
  E_eps_hat <- Et1 / (rM * Et2)

  e    <- switch(test, uncorrected = 1, GG = E_eps_hat)
  crit <- qf(1 - alpha, df1 = rM * e, df2 = rM * nu * e)
  list(power = pf(crit, df1 = nu1_star, df2 = nu2_star,
                  ncp = lambda, lower.tail = FALSE),
       E_eps_hat = E_eps_hat, nu1_star = nu1_star,
       nu2_star = nu2_star, lambda = lambda)
}

gg_33 <- power_unirep(mu_power, Sigma_power, n = n_power, test = "GG")
cat("Muller-Barton E[epsilon-hat]:", round(gg_33$E_eps_hat, 4),
    "  (population epsilon:", round(eps_pop, 4), ")\n")
HideShow
Muller-Barton E[epsilon-hat]: 0.8232   (population epsilon: 0.8621 )
HideShow
cat("Rescaled df1, df2, lambda:", round(gg_33$nu1_star, 3),
    round(gg_33$nu2_star, 3), round(gg_33$lambda, 3), "\n")
HideShow
Rescaled df1, df2, lambda: 1.447 55.172 8.954 
HideShow
cat("GG power of the test actually run, at n = 33:", round(gg_33$power, 4), "\n")
HideShow
GG power of the test actually run, at n = 33: 0.8045 
HideShow
#> .8045 — confirms the book's power of .80 at N = 33, book p. 627

# The same rescaled statistic judged against the nominal critical value, which
# is the unadjusted test of Quantity 1 evaluated under this Sigma
cat("Unadjusted test under this Sigma, same closed form:",
    round(power_unirep(mu_power, Sigma_power, n_power,
                       test = "uncorrected")$power, 4), "\n")
HideShow
Unadjusted test under this Sigma, same closed form: 0.8268 
HideShow
#> .8268 — the closed-form counterpart of the simulated .8288 in Quantity 1,
#> and five points below the .8776 that Equation 11.50 implies

That reproduces the book’s claim on p. 627 directly, and it also puts a closed form behind Quantity 1: the .8268 on the last line is the unadjusted test evaluated under the actual Σ\Sigma rather than under its average correlation, which is the .827 the simulation there estimated.

Two things in that output deserve care. First, the 0.8232 is not E[ε̂]\mathrm{E}[\hat{\varepsilon}] itself; it is the Muller–Barton closed-form approximation to it, and the approximation is not sharp here. Second, it is tempting to read the drop from Quantity 2’s .8384 to .8045 as a consequence of ε̂\hat{\varepsilon} being biased downward, since a smaller correction factor means a larger critical value. Both points can be checked directly.

HideShow
# E[epsilon-hat] by simulation: draw a sample, compute its epsilon-hat, repeat
set.seed(113)
eps_hats <- replicate(20000, {
  D <- MASS::mvrnorm(n = n_power, mu = mu_power, Sigma = Sigma_power) %*% t(U_power)
  S <- cov(D)
  sum(diag(S))^2 / (b_df * sum(S^2))
})
cat("Simulated E[epsilon-hat]:", round(mean(eps_hats), 4),
    " Muller-Barton approximation:", round(gg_33$E_eps_hat, 4), "\n")
HideShow
Simulated E[epsilon-hat]: 0.8414  Muller-Barton approximation: 0.8232 
HideShow
#> .8414 against .8232: epsilon-hat is biased downward from the population
#> .8621, but by about .021, not the .039 the closed form implies

# How much of the .8384 -> .8045 drop is the critical value alone? Hold the
# rescaled df and noncentrality fixed and move only the critical value.
crit_at_eps_pop <- qf(0.95, df1 = b_df * eps_pop,
                      df2 = b_df * (n_power - 1) * eps_pop)
cat("Same rescaled test, critical value taken at the population epsilon:",
    round(pf(crit_at_eps_pop, df1 = gg_33$nu1_star, df2 = gg_33$nu2_star,
             ncp = gg_33$lambda, lower.tail = FALSE), 4), "\n")
HideShow
Same rescaled test, critical value taken at the population epsilon: 0.81 
HideShow
#> 0.81 — moving the critical value recovers .0056 of the .0339 drop, a sixth

So the bias in ε̂\hat{\varepsilon} is real but mild, and it is not where the conservatism mostly comes from. The larger part is in the rescaling: λ*=8.954\lambda^{*} = 8.954 against Quantity 2’s λε=10.668\lambda \varepsilon = 10.668, and 𝑑𝑓1*=1.447\mathit{df}_1^{*} = 1.447 against 1.724. That rescaling is the approximation’s way of carrying the dependence between ε̂\hat{\varepsilon} and FF — the two are built from the same sums of squares, so a sample that happens to inflate FF also sets its own critical value. Moving the critical value across the whole distance from the closed form’s 0.8232 to the population 0.8621 accounts for at most a sixth of the gap, and for less than that in truth, since the simulated E[ε̂]\mathrm{E}[\hat{\varepsilon}] of 0.8414 is nearer the population value than the closed form’s 0.8232 is. The dependence accounts for the rest.

An approximation deserves a check, and here the check is easy: run the test itself, with omnibus_reject() from Quantity 1 and the correction switched on. Each replicate draws nn subjects, computes its own ε̂\hat{\varepsilon}, and is judged against its own critical value — which is what a researcher does. No approximation is involved at all. Because the seed and the replication count are the ones Quantity 1 used, these are the same 50,000 samples, now judged the way the book recommends judging them.

HideShow
set.seed(113)
hits <- replicate(reps_power,
                  omnibus_reject(n_power, mu_power, Sigma_power, U_power,
                                 correction = "GG"))

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

The simulation and the closed form agree to within one Monte Carlo standard error, so for this design the UNIREP approximation and brute force are telling the same story, and both put the power of the realized Greenhouse–Geisser test at N=33N = 33 essentially at .80. The simulation is also the honest adjudicator among the quantities above, since it makes no distributional approximation: it simply runs the test 50,000 times. Report the Monte Carlo standard error whenever you plan this way, and raise the replications if the third decimal matters.

Superpower, the package the book names, has two engines, and they answer two of the questions separated above. ANOVA_exact() refers one exact data set to its nominal distribution, returning Quantity 1’s 87.76% with no correction and Quantity 2’s 83.84% with correction = "GG"; ANOVA_power() re-estimates ε̂\hat{\varepsilon} in each simulated replicate, so it estimates the realized test of Quantity 3, and it is that engine that lands near the book’s .80 at N=33N = 33, within its own Monte Carlo error.

Solving for the sample size

Nothing above solves for nn, but a one-line search over the closed forms does, and it is worth seeing what each definition of power asks for.

HideShow
# Smallest n at which a power function reaches the target
smallest_n <- function(power_fn, target = 0.80, n_max = 200) {
  for (n in 2:n_max) if (power_fn(n) >= target) return(n)
  NA_integer_
}

# Route 1: Equation 11.50's average correlation, referred to a noncentral F.
# This is the spherical calculation, so it describes the rho-bar = .5 design.
n_eq_11_50 <- smallest_n(function(n) {
  lam <- a_power * n * f_implied^2 / (1 - rho_bar)
  pf(qf(0.95, df1 = a_power - 1, df2 = (a_power - 1) * (n - 1)),
     df1 = a_power - 1, df2 = (a_power - 1) * (n - 1),
     ncp = lam, lower.tail = FALSE)
})

# Routes 2 and 3: the two tests, both evaluated under the printed matrix
n_unadjusted <- smallest_n(function(n)
  power_unirep(mu_power, Sigma_power, n, test = "uncorrected")$power)
n_adjusted   <- smallest_n(function(n)
  power_unirep(mu_power, Sigma_power, n, test = "GG")$power)

cat("Equation 11.50 with rho-bar = .5, noncentral F:     ", n_eq_11_50, "\n")
HideShow
Equation 11.50 with rho-bar = .5, noncentral F:      28 
HideShow
#> 28 — matches the compound-symmetric rho = .50 requirement, book p. 627
cat("Unadjusted test under the printed matrix:           ", n_unadjusted, "\n")
HideShow
Unadjusted test under the printed matrix:            31 
HideShow
#> 31 — the unequal-correlation requirement for the same unadjusted test
cat("Epsilon-hat-adjusted test, printed matrix:          ", n_adjusted, "\n")
HideShow
Epsilon-hat-adjusted test, printed matrix:           33 
HideShow
#> 33 — matches book p. 627
# The two routes compared at the same sample size, n = 31
n_31   <- 31
lam_31 <- a_power * n_31 * f_implied^2 / (1 - rho_bar)
cat("Unadjusted test at n = 31, under the printed matrix:",
    round(power_unirep(mu_power, Sigma_power, n_31,
                       test = "uncorrected")$power, 4), "\n")
HideShow
Unadjusted test at n = 31, under the printed matrix: 0.8022 
HideShow
cat("The same test at n = 31, as Equation 11.50 sees it: ",
    round(pf(qf(0.95, df1 = a_power - 1, df2 = (a_power - 1) * (n_31 - 1)),
             df1 = a_power - 1, df2 = (a_power - 1) * (n_31 - 1),
             ncp = lam_31, lower.tail = FALSE), 4), "\n")
HideShow
The same test at n = 31, as Equation 11.50 sees it:  0.8544 
HideShow
#> .8022 delivered against .8544 credited
cat("GG power at n = 32 and n = 33:",
    round(power_unirep(mu_power, Sigma_power, 32, test = "GG")$power, 4), "and",
    round(power_unirep(mu_power, Sigma_power, 33, test = "GG")$power, 4), "\n")
HideShow
GG power at n = 32 and n = 33: 0.7914 and 0.8045 

Two of those three integers are the book’s, and they answer different questions. The 28 is the requirement the book gives for the compound-symmetric case with every correlation at .50 (p. 627), where it holds “whether we use an unadjusted test or an ε̂\hat{\varepsilon}-adjusted test”; solving the noncentral FF for power ≥\geq .80, rather than equating noncentrality parameters as the closed form earlier in this section did, lands on it exactly rather than on the 26.5 that route produced. The 33 is the requirement the book gives for the unequal-correlation matrix under the ε̂\hat{\varepsilon}-adjusted test (p. 627), and the search reaches it because n=32n = 32 gives .7914 and n=33n = 33 gives .8045.

The 31 is the number that makes the comparison honest. Under the printed matrix the unadjusted test needs 31 subjects, not 28: the spherical calculation credits it with .8544 at that sample size, while the test itself delivers .8022. So the price of the recommended adjustment in this design is two subjects, 31 against 33 — and the five-subject gap between 28 and 33 is a gap between two designs, not between two tests.

That the search lands on 33 is a confirmation, not a guarantee. The 33 itself comes from GLIMMPSE and SAS GLMPOWER solving for sample size under the ε̂\hat{\varepsilon}-adjusted test, and different exact solutions for a design that violates sphericity need not land on the same integer: the quantity is approximated differently by different programs, and a power curve that crosses .80 between two consecutive integers will be rounded by whichever side of the crossing a given method falls on. Two subjects is also a small enough difference to be worth reading alongside the book’s warning on p. 627, offered where the unadjusted and adjusted requirements differed by a single subject, that “the difference is not always this small.”

In DMAR: planning a longitudinal within-subjects study

Every calculation above fixes a sample size and reads off the resulting power; smallest_n() then had to step through candidate sample sizes one at a time to invert it. When the within-subjects design is a polynomial change model (subjects measured repeatedly over time, with interest in the slope of change), DMAR solves for the sample size directly. Two complementary planners are available: an accuracy-in-parameter-estimation (AIPE) planner that targets a confidence-interval width, and a power planner that targets statistical power.

ss_aipe_pcm() plans the per-group sample size so that the confidence interval on the group-by-time linear slope difference is no wider than a target. The calls below use the level-one error variance of 0.0262 and between-subject slope variance of 0.003 that DMAR’s documentation takes from Kelley and Rausch (2011).

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

Confidence level: 95%

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

# Doubling the occasions to M = 10 sharpens the slope estimate:
ss_aipe_pcm(true_var_trend = 0.003, true_var_error = 0.0262,
            duration = 9, frequency = 1, width = 0.025, conf_level = 0.95)
term value
necessary_n_per_group 165

Confidence level: 95%

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

# Adding 85% assurance (the realized CI meets the target width with
# probability 0.85, not just on average) raises the requirement:
ss_aipe_pcm(true_var_trend = 0.003, true_var_error = 0.0262,
            duration = 4, frequency = 1, width = 0.025,
            conf_level = 0.95, assurance = 0.85)
term value
necessary_n_per_group 295

Confidence level: 95%

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

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

HideShow
ss_power_pcm(true_std_reg_coef = -0.40, true_var_trend = 0.003, true_var_error = 0.0262,
             frequency = 1, duration = 4, desired_power = 0.80)
term value
necessary_n_per_group 185
total_N 370
actual_power 0.801
frequency 1
duration 4
n_occasions 5
polynomial_order 1
true_reg_coef -0.022
true_std_reg_coef -0.400
true_var_error 0.026
true_var_trend 0.003
true_var_trend_error 0.003
reliability 0.534
noncentral_t_parm 2.811
HideShow
#> 185 per group, 370 in total, achieved power .801; DMAR documents this as the
#> Raudenbush and Liu (2001) National Youth Survey illustration

These two planners answer different questions, the accuracy of the slope estimate versus the power to detect a slope difference. Both make explicit how the number of measurement occasions and the within-subject correlation structure drive the sample size required for a longitudinal within-subjects design. Neither number appears in the printed book; they are reproductions of the sources DMAR’s documentation cites.

11.17 — Intraclass Correlations for Assessing Reliability

Intraclass correlations (ICCs) adapt the within-subjects ANOVA framework to measure the reliability of ratings given by multiple judges (or items). Following Shrout and Fleiss (1979), the key decision is whether you care about agreement (do the judges give the same numbers?) or consistency (do the judges rank the subjects in the same order?).

  • Case 2 (agreement), Equation 11.51: ICC(2,1)=MSS−MSA×SMSS+(a−1)MSA×S+a(MSA−MSA×S)/nICC(2,1) = \frac{MS_S - MS_{A \times S}}{MS_S + (a-1)MS_{A \times S} + a(MS_A - MS_{A \times S})/n}

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

The distinction is clearest in the artificial data of Table 11.20: five subjects rated by three judges, where Judge 2 rates everyone exactly 4 points below Judge 1 and Judge 3 rates everyone exactly 2 points above. There is literally no interaction, so MSA×S=0MS_{A \times S} = 0 and the usual FF tests are undefined. We therefore read the mean squares straight off the two-way decomposition rather than from an FF table.

HideShow
data(chapter_11_table_20)

# Reshape the ratings into the subjects-by-judges layout the book prints
ratings_20 <- chapter_11_table_20 |>
  pivot_wider(names_from = Judge, values_from = Rating, names_prefix = "Judge") |>
  column_to_rownames("Subject") |>
  as.matrix()
ratings_20
HideShow
  Judge1 Judge2 Judge3
1      9      5     11
2      6      2      8
3      8      4     10
4      7      3      9
5      4      0      6
HideShow
#> matches Table 11.20, book p. 629

# Two-way decomposition: subject, judge, and residual (A x S) sums of squares
n <- nrow(ratings_20)   # 5 subjects
a <- ncol(ratings_20)   # 3 judges
grand     <- mean(ratings_20)
subj_dev  <- rowMeans(ratings_20) - grand
judge_dev <- colMeans(ratings_20) - grand
resid_mat <- ratings_20 - outer(rowMeans(ratings_20), colMeans(ratings_20), "+") + grand

MS_S   <- a * sum(subj_dev^2) / (n - 1)
MS_A   <- n * sum(judge_dev^2) / (a - 1)
MS_AxS <- sum(resid_mat^2) / ((n - 1) * (a - 1))

cat("MS_S:", round(MS_S, 2), " MS_A:", round(MS_A, 2), " MS_AxS:", round(MS_AxS, 2), "\n")
HideShow
MS_S: 11.1  MS_A: 46.67  MS_AxS: 0 
HideShow
#> 11.10, 46.67, 0.00 — match book p. 630

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

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

Consistency is perfect, so ICC(3,1)=1.00ICC(3,1) = 1.00. Agreement is poor, because the judges use very different parts of the scale, and ICC(2,1)ICC(2,1) is only .28. Which of the two is the right reliability depends entirely on whether mean differences between judges should count against you.

Composite reliability

Often we want the reliability not of a single judge but of the average over all judges. The book’s running example is Table 11.19, six subjects rated by four judges, also in AMCP. Here MSA×SMS_{A \times S} is nonzero, so the ordinary aov() route works, and we compute all four Shrout and Fleiss coefficients from the mean squares.

HideShow
data(chapter_11_table_19)
chapter_11_table_19$Subject <- factor(chapter_11_table_19$Subject)
chapter_11_table_19$Judge   <- factor(chapter_11_table_19$Judge)

# Mean squares from the Subject + Judge ANOVA on the ratings.
sf      <- summary(aov(Rating ~ Subject + Judge, data = chapter_11_table_19))[[1]]
MS_S    <- sf["Subject",   "Mean Sq"]
MS_A    <- sf["Judge",     "Mean Sq"]
MS_AxS  <- sf["Residuals", "Mean Sq"]
n_19    <- nlevels(chapter_11_table_19$Subject)  # subjects (6)
a_19    <- nlevels(chapter_11_table_19$Judge)    # judges (4)

# Single-judge coefficients (Equations 11.51 and 11.52).
icc_2_1 <- (MS_S - MS_AxS) / (MS_S + (a_19 - 1) * MS_AxS + a_19 * (MS_A - MS_AxS) / n_19)
icc_3_1 <- (MS_S - MS_AxS) / (MS_S + (a_19 - 1) * MS_AxS)

# Composite (a-judge average) coefficients (Equations 11.53 and 11.54).
icc_2_a <- (MS_S - MS_AxS) / (MS_S + (MS_A - MS_AxS) / n_19)
icc_3_a <- (MS_S - MS_AxS) / MS_S

cat(
  "Single-judge ICC(2,1) Agreement:", round(icc_2_1, 2),
  "\nSingle-judge ICC(3,1) Consistency:", round(icc_3_1, 2),
  "\n\nComposite ICC(2,4) Agreement:", round(icc_2_a, 2),
  "\nComposite ICC(3,4) Consistency (Cronbach's alpha):", round(icc_3_a, 2),
  "\n"
)
HideShow
Single-judge ICC(2,1) Agreement: 0.29 
Single-judge ICC(3,1) Consistency: 0.71 

Composite ICC(2,4) Agreement: 0.62 
Composite ICC(3,4) Consistency (Cronbach's alpha): 0.91 
HideShow
#> ICC(2,1) = .29 and ICC(3,1) = .71 — match book p. 630
#> ICC(2,4) = .62 and ICC(3,4) = .91 — match book p. 631

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

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

Averaging over four judges lifts consistency reliability from .71 for a single judge to .91 for the four-judge mean.

In DMAR: the four coefficients with confidence intervals

The formulas above give point estimates only. DMAR’s icc() also returns the confidence intervals and the significance test that Shrout and Fleiss describe, taking the subjects-by-judges matrix directly.

HideShow
ratings_19 <- chapter_11_table_19 |>
  pivot_wider(names_from = Judge, values_from = Rating, names_prefix = "Judge") |>
  column_to_rownames("Subject") |>
  as.matrix()
ratings_19
HideShow
  Judge1 Judge2 Judge3 Judge4
1      9      2      5      8
2      6      1      3      2
3      8      4      6      8
4      7      1      2      6
5     10      5      6      9
6      6      2      4      7
HideShow
#> matches Table 11.19, book p. 628

for (case in c("ICC(2,1)", "ICC(3,1)", "ICC(2,k)", "ICC(3,k)")) {
  print(icc(ratings_19, type = case, conf_level = 0.95))
}
HideShow
 type     value ci_lower ci_upper F_value df_1 df_2 p_value
 ICC(2,1) 0.290 0.019    0.761    11.027  5    15   0.0001 

Confidence level: 95%
 type     value ci_lower ci_upper F_value df_1 df_2 p_value
 ICC(3,1) 0.715 0.342    0.946    11.027  5    15   0.0001 

Confidence level: 95%
 type     value ci_lower ci_upper F_value df_1 df_2 p_value
 ICC(2,k) 0.620 0.071    0.927    11.027  5    15   0.0001 

Confidence level: 95%
 type     value ci_lower ci_upper F_value df_1 df_2 p_value
 ICC(3,k) 0.909 0.676    0.986    11.027  5    15   0.0001 

Confidence level: 95%
HideShow
#> point estimates .290, .715, .620, .909 — the same four coefficients computed by
#> hand above, and matching the book's .29, .71 (p. 630) and .62, .91 (p. 631)

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

HideShow
reliability_alpha(data = as.data.frame(ratings_19), ci_method = "none")
term value ci_method
estimate 0.909 none
se NA none
ci_lower NA none
ci_upper NA none
conf_level 0.950 none
N 6 none
N_complete 6 none
n_items 4 none
HideShow
#> alpha = .909 — the same value as ICC(3,4) above, confirming the equivalence

That equivalence is why ICC(3,k)ICC(3,k) is so often the reliability that behavioral measurement actually reports.

How to Cite This Page

The book. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.

This page. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Chapter 11: One-Way Within-Subjects Designs: Univariate Approach (R code and instructions). Companion materials for Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). https://DesigningExperiments.com

These examples use DMAR 1.2.0. The printed book predates DMAR.

References

Chapter 12: Higher-Order Designs with Within-Subjects Factors: Univariate Approach

Open the separate reading

Code
Results
On this page

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

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

HideShow
# Load all of the packages used.
library(tidyverse)      # data wrangling and plotting (dplyr, tidyr, ggplot2, and friends)
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(effectsize)     # effect sizes (eta-squared, omega-squared)
library(emmeans)        # estimated marginal means and contrasts
library(car)            # Anova() for Type II/III tests and regression diagnostics
library(broom)          # tidy model output into data frames
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables

12.2 — Designs with Two Within-Subjects Factors

Load the data for Table 12.1 from the AMCP package.

HideShow
data(chapter_12_table_1)

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

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

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

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

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

12.2.1 — Omnibus Tests

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

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

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

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

12.2.2 — Numerical Example

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Confidence level: 95%

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

Confidence level: 95%

12.2.3 — Further Investigation of Main Effects

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    One Sample t-test

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

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

12.2.4 — Further Investigation of an Interaction—Simple Effects

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

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

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

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

summary(Simple_Angle_w_Abs)
HideShow

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

12.2.5 — Interaction Contrasts

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

12.2.7 — Assumptions

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

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

Assumption for Factor A (Angle)

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

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

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

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

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

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

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

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

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

12.2.8 — Adjusted Univariate Tests

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

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

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

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

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

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

Univariate Type III Repeated-Measures ANOVA Assuming Sphericity

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


Mauchly Tests for Sphericity

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


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

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

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

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

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

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

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

12.2.9 — Confidence Intervals

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

12.2.10 — Quasi-FF Ratios

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

12.3.1 — Omnibus Tests

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

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

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

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

12.3.1.4 — Numerical Example

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

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

summary(Mixed_ANOVA)
HideShow

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

12.3.2 — Further Investigation of Main Effects

12.3.2.1 — Between-Subjects Factor

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

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

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

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

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

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

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

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

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

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

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

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


    Young — —
    Old 94 21, 167 0.015
Abbreviation: CI = Confidence Interval
12.3.2.2 — Within-Subjects Factor

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# Corrected F-value
F_value <- SS_Quad / MS_Error_Separate

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

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

12.3.3 — Further Investigation of an Interaction—Simple Effects

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

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

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

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

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

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

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

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

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

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

summary(simple_angle_young)
HideShow

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

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

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

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

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

MS_B_at_A1 / MS_BxS_A
HideShow
[1] 47.94708
HideShow
#> 47.95 — matches book p. 672
12.3.3.2 — Between-Subjects Effects at a Fixed Level of Within-Subjects Factor

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

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

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

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

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

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

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

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

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

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

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

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

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

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

12.3.4 — Interaction Contrasts

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

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

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

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

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

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

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

HideShow
quad_anova
HideShow
Anova Table (Type III tests)

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

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

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

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

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

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

12.3.5 — Assumptions

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

12.3.6 — Adjusted Univariate Tests

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

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

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

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

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

Univariate Type II Repeated-Measures ANOVA Assuming Sphericity

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


Mauchly Tests for Sphericity

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


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

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

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

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

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

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

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

12.4 — Power Analysis and Sample Size Planning

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

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

The one calculation behind every number in this section

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

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

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

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

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

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

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

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

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

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

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

12.4.1 — Designs with Two Within-Subjects Factors

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

$B
[1] 100 100

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

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

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

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

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

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

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

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

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

  1. Example 1: A 2x2 Mixed Design

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Key Takeaways for Mixed Designs

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

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

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

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

In DMAR: planning a within-subjects polynomial trend

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

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

Confidence level: 95%

HideShow
#> necessary_n_per_group = 278, matches Kelley & Rausch (2011, Table 1, M = 5)

# With 85% assurance the realized CI meets the target width with probability
# 0.85, not merely on average:
ss_aipe_pcm(true_var_trend = 0.003, true_var_error = 0.0262,
            duration = 4, frequency = 1, width = 0.025,
            conf_level = 0.95, assurance = 0.85)
term value
necessary_n_per_group 295

Confidence level: 95%

HideShow
#> necessary_n_per_group = 295, matches Kelley & Rausch (2011, Table 2, M = 5)

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

HideShow
# The effect is given on the standardized scale, so true_std_reg_coef is the
# argument that carries it.
ss_power_pcm(true_std_reg_coef = -0.40, true_var_trend = 0.003,
             true_var_error = 0.0262,
             frequency = 1, duration = 4, desired_power = 0.80)
term value
necessary_n_per_group 185
total_N 370
actual_power 0.801
frequency 1
duration 4
n_occasions 5
polynomial_order 1
true_reg_coef -0.022
true_std_reg_coef -0.400
true_var_error 0.026
true_var_trend 0.003
true_var_trend_error 0.003
reliability 0.534
noncentral_t_parm 2.811
HideShow
#> necessary_n_per_group = 185 and total_N = 370, matching Raudenbush & Liu
#> (2001, p. 393)

12.5 — More Complex Designs

12.5.1 — Designs with Additional Factors

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

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

12.5.2 — Latin Square Designs

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

anova(latin_restricted, latin_full)
HideShow
Analysis of Variance Table

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

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

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


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

How to Cite This Page

The book. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.

This page. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Chapter 12: Higher-Order Designs with Within-Subjects Factors: Univariate Approach (R code and instructions). Companion materials for Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). https://DesigningExperiments.com

These examples use DMAR 1.2.0. The printed book predates DMAR.

References

Chapter 13: One-Way Within-Subjects Designs: Multivariate Approach

Open the separate reading

Code
Results
On this page
HideShow
# Load all of the packages used.
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(tidyverse)      # data wrangling and plotting (dplyr, ggplot2, and friends)
library(car)            # Anova() for Type II/III tests and regression diagnostics
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison 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.

HideShow
data(chapter_13_table_1)
chapter_13_table_1
HideShow
  Time1 Time2
1     2     3
2     4     7
3     6     8
4     8     9
5    10    13
HideShow
# Create difference score
chapter_13_table_1$Difference <- chapter_13_table_1$Time2 - chapter_13_table_1$Time1
chapter_13_table_1
HideShow
  Time1 Time2 Difference
1     2     3          1
2     4     7          3
3     6     8          2
4     8     9          1
5    10    13          3
HideShow
#> 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.

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

Call:
lm(formula = Difference ~ 1, data = chapter_13_table_1)

Residuals:
         1          2          3          4          5 
-1.000e+00  1.000e+00 -1.406e-17 -1.000e+00  1.000e+00 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)  
(Intercept)   2.0000     0.4472   4.472   0.0111 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1 on 4 degrees of 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.

HideShow
# 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")
HideShow
n = 5  Dbar = 2  s^2_D = 1  F = 20 
HideShow
#> 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)
HideShow
[1] 7.708647
HideShow
#> 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.

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

    One Sample t-test

data:  chapter_13_table_1$Difference
t = 4.4721, df = 4, p-value = 0.01106
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 0.758336 3.241664
sample estimates:
mean of x 
        2 
HideShow
# 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
)
HideShow

    Paired t-test

data:  chapter_13_table_1$Time2 and chapter_13_table_1$Time1
t = 4.4721, df = 4, p-value = 0.01106
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
 0.758336 3.241664
sample estimates:
mean difference 
              2 
HideShow
#> 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).

HideShow
data(chapter_13_table_2)
chapter_13_table_2
HideShow
  Time1 Time2 Time3
1     2     3     5
2     4     7     9
3     6     8     8
4     8     9     8
5    10    13    15
6     3     4     9
7     6     9     8
8     9    11    10
HideShow
#> 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
HideShow
  Time1 Time2 Time3 D1 D2
1     2     3     5  1  2
2     4     7     9  3  2
3     6     8     8  2  0
4     8     9     8  1 -1
5    10    13    15  3  2
6     3     4     9  1  5
7     6     9     8  3 -1
8     9    11    10  2 -1
HideShow
colMeans(chapter_13_table_2[, c("D1", "D2")])
HideShow
D1 D2 
 2  1 
HideShow
#> 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).

HideShow
n <- nrow(chapter_13_table_2)
D1_bar <- mean(chapter_13_table_2$D1)
D2_bar <- mean(chapter_13_table_2$D2)

# Full Model SSCP Matrix Elements
E11_F <- sum((chapter_13_table_2$D1 - D1_bar)^2)
E22_F <- sum((chapter_13_table_2$D2 - D2_bar)^2)
E12_F <- sum((chapter_13_table_2$D1 - D1_bar) * (chapter_13_table_2$D2 - D2_bar))

# Assemble the Full Model Matrix E(F)
E_F <- matrix(c(E11_F, E12_F,
                E12_F, E22_F), nrow = 2, byrow = TRUE)

# Restricted Model SSCP Matrix Elements (Predicted score is 0)
E11_R <- sum(chapter_13_table_2$D1^2)
E22_R <- sum(chapter_13_table_2$D2^2)
E12_R <- sum(chapter_13_table_2$D1 * chapter_13_table_2$D2)

# Assemble the Restricted Model Matrix E(R)
E_R <- matrix(c(E11_R, E12_R,
                E12_R, E22_R), nrow = 2, byrow = TRUE)

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

print("Restricted Model Matrix E(R):")
HideShow
[1] "Restricted Model Matrix E(R):"
HideShow
print(E_R)
HideShow
     [,1] [,2]
[1,]   38   13
[2,]   13   40
HideShow
#> 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.

HideShow
# 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")
HideShow
Determinant of E(F): 183 
Determinant of E(R): 1351 
HideShow
#> |E(F)| = 183, |E(R)| = 1351 — matches book p. 719

# Calculate the F-statistic (Equation 13.23)
# F = ((det(E_R) - det(E_F)) / 2) / (det(E_F) / (n - 2))
F_stat <- ((det_ER - det_EF) / 2) / (det_EF / (n - 2))

cat("Observed F-statistic:", F_stat,
    "\np-value:", pf(F_stat, 2, n - 2, lower.tail = FALSE), "\n")
HideShow
Observed F-statistic: 19.14754 
p-value: 0.002485348 
HideShow
#> 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.

HideShow
# 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)
HideShow
Analysis of Variance Table

            Df  Pillai approx F num Df den Df   Pr(>F)   
(Intercept)  1 0.86454   19.148      2      6 0.002485 **
Residuals    7                                           
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> 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.

HideShow
# Alternative MANOVA tests.
anova(MANOVA_Diff_3DV, test="Wilks")
HideShow
Analysis of Variance Table

            Df   Wilks approx F num Df den Df   Pr(>F)   
(Intercept)  1 0.13545   19.148      2      6 0.002485 **
Residuals    7                                           
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
anova(MANOVA_Diff_3DV, test="Hotelling-Lawley")
HideShow
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
HideShow
anova(MANOVA_Diff_3DV, test="Roy")
HideShow
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:

HideShow
# 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
HideShow
[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.

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

HideShow
data(chapter_13_table_5)
chapter_13_table_5
HideShow
   SetA_D1 SetA_D2 SetB_D1 SetB_D2
1       -3    -3.1      -3    -1.1
2       -3    -2.9      -3     1.2
3       -2    -2.2      -2    -2.9
4       -2    -1.8      -2     2.8
5       -1    -1.1      -1    -3.1
6       -1    -0.9      -1     3.2
7        0    -0.2       0    -1.8
8        0     0.2       0     1.9
9        1     0.8       1    -2.2
10       1     1.2       1     2.1
11       2     1.9       2    -0.9
12       2     2.1       2     0.8
13       3     2.8       3    -0.2
14       3     3.2       3     0.2
HideShow
# Every one-dimensional summary is identical across the two data sets.
colSums(chapter_13_table_5)
HideShow
     SetA_D1      SetA_D2      SetB_D1      SetB_D2 
0.000000e+00 0.000000e+00 0.000000e+00 1.110223e-16 
HideShow
colSums(chapter_13_table_5^2)
HideShow
SetA_D1 SetA_D2 SetB_D1 SetB_D2 
  56.00   56.38   56.00   56.38 
HideShow
#> Each D1 column sums to 0 with sum of squares 56.00, and each D2 column sums to 0
#> with sum of squares 56.38 — matches Table 13.5, book p. 717

# Sums of cross-products, the one place the two data sets part company.
with(chapter_13_table_5, c(SetA = sum(SetA_D1 * SetA_D2), SetB = sum(SetB_D1 * SetB_D2)))
HideShow
SetA SetB 
56.0 -0.5 
HideShow
#> 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.

HideShow
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)
HideShow
Data set (a) Data set (b) 
       21.28      3157.03 
HideShow
#> 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.

HideShow
# Join the two edges to show the spread of each cloud.
hull_order <- function(d) rbind(d[seq(1, nrow(d), by = 2), ],
                               d[rev(seq(2, nrow(d), by = 2)), ])

label_a <- "Data set (a): nearly collinear"
label_b <- "Data set (b): nearly uncorrelated"

outline <- bind_rows(
  data.frame(hull_order(data.frame(D1 = set_a[, 1], D2 = set_a[, 2])), Set = label_a),
  data.frame(hull_order(data.frame(D1 = set_b[, 1], D2 = set_b[, 2])), Set = label_b)
)
points_df <- bind_rows(
  data.frame(D1 = set_a[, 1], D2 = set_a[, 2], Set = label_a),
  data.frame(D1 = set_b[, 1], D2 = set_b[, 2], Set = label_b)
)
det_labels <- data.frame(
  Set   = c(label_a, label_b),
  D1    = -3.4,
  D2    = 3.4,
  label = sprintf("Determinant = %.2f", c(det_a, det_b))
)
HideShow
ggplot(points_df, aes(x = D1, y = D2)) +
  geom_polygon(data = outline, fill = NA, color = "#0C2340", linewidth = 0.4) +
  geom_point(shape = 21, fill = "white", color = "black", size = 2.4, stroke = 0.7) +
  geom_text(data = det_labels, aes(label = label),
            color = "#0C2340", fontface = "bold", hjust = 0, size = 3.6) +
  facet_wrap(~ Set, ncol = 1) +
  coord_fixed(ratio = 1, xlim = c(-3.6, 3.6), ylim = c(-3.6, 3.6)) +
  labs(x = expression(italic(D)[1]~"score"), y = expression(italic(D)[2]~"score"))
Figure 13.2. Scores on \(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.

HideShow
data(chapter_13_table_6)

# Create the three difference variables (matching Table 13.7)
chapter_13_table_6$D1 <- chapter_13_table_6$Months36 - chapter_13_table_6$Months30
chapter_13_table_6$D2 <- chapter_13_table_6$Months42 - chapter_13_table_6$Months36
chapter_13_table_6$D3 <- chapter_13_table_6$Months48 - chapter_13_table_6$Months42

# View the first few rows to verify the D variables
head(chapter_13_table_6)
HideShow
  Months30 Months36 Months42 Months48  D1  D2 D3
1      108       96      110      122 -12  14 12
2      103      117      127      133  14  10  6
3       96      107      106      107  11  -1  1
4       84       85       92       99   1   7  7
5      118      125      125      116   7   0 -9
6      110      107       96       91  -3 -11 -5
HideShow
colMeans(chapter_13_table_6[, c("D1", "D2", "D3")])
HideShow
D1 D2 D3 
 4  3  2 
HideShow
#> 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.

HideShow
n <- nrow(chapter_13_table_6)
a <- 4

# Full Model Matrix E(F): Uses mean-centered variables (deviations from the mean)
e1_F <- chapter_13_table_6$D1 - mean(chapter_13_table_6$D1)
e2_F <- chapter_13_table_6$D2 - mean(chapter_13_table_6$D2)
e3_F <- chapter_13_table_6$D3 - mean(chapter_13_table_6$D3)

E_F <- crossprod(cbind(e1_F, e2_F, e3_F))

# Restricted Model Matrix E(R): Uses the raw scores (deviations from zero)
E_R <- crossprod(cbind(chapter_13_table_6$D1, chapter_13_table_6$D2, chapter_13_table_6$D3))

# Full Model Matrix E(F)
print(E_F)
HideShow
     e1_F e2_F e3_F
e1_F  878 -329 -440
e2_F -329 1004  399
e3_F -440  399  658
HideShow
#> 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)
HideShow
     [,1] [,2] [,3]
[1,] 1070 -185 -344
[2,] -185 1112  471
[3,] -344  471  706
HideShow
#> 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.

HideShow
# 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")
HideShow
Determinant of E(F): 290177920 
Determinant of E(R): 506853568 
HideShow
#> |E(F)| = 290,177,920 and |E(R)| = 506,853,568 — matches book p. 721

# Calculate the F-statistic
num_df <- a - 1
den_df <- n - a + 1

F_stat <- ((det_ER - det_EF) / num_df) / (det_EF / den_df)
p_value <- pf(F_stat, num_df, den_df, lower.tail = FALSE)

cat("Observed F-statistic:", F_stat,
    "\nP-value:", p_value, "\n")
HideShow
Observed F-statistic: 2.240098 
P-value: 0.1528393 
HideShow
#> 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().

HideShow
# 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)
HideShow
Analysis of Variance Table

            Df  Pillai approx F num Df den Df Pr(>F)
(Intercept)  1 0.42749   2.2401      3      9 0.1528
Residuals   11                                      
HideShow
#> 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.

HideShow
anova(MANOVA_4DV, test="Pillai")
HideShow
Analysis of Variance Table

            Df  Pillai approx F num Df den Df Pr(>F)
(Intercept)  1 0.42749   2.2401      3      9 0.1528
Residuals   11                                      
HideShow
anova(MANOVA_4DV, test="Wilks")
HideShow
Analysis of Variance Table

            Df   Wilks approx F num Df den Df Pr(>F)
(Intercept)  1 0.57251   2.2401      3      9 0.1528
Residuals   11                                      
HideShow
anova(MANOVA_4DV, test="Hotelling-Lawley")
HideShow
Analysis of Variance Table

            Df Hotelling-Lawley approx F num Df den Df Pr(>F)
(Intercept)  1           0.7467   2.2401      3      9 0.1528
Residuals   11                                               
HideShow
anova(MANOVA_4DV, test="Roy")
HideShow
Analysis of Variance Table

            Df    Roy approx F num Df den Df Pr(>F)
(Intercept)  1 0.7467   2.2401      3      9 0.1528
Residuals   11                                     

The four statistics all map to the same approximate 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:

HideShow
# Pull each multivariate statistic and its approximate F from anova.mlm().
# Each anova() object stores the test value in a column named after the statistic
# (e.g., "Pillai", "Wilks"), so read that column by name; the F, df, and p columns
# are shared across all four.
tests  <- c("Pillai", "Wilks", "Hotelling-Lawley", "Roy")
mantab <- lapply(tests, function(tt) {
  a <- anova(MANOVA_4DV, test = tt)               # row 1 = Intercept term
  data.frame(Test = tt, Statistic = a[[tt]][1], Fapprox = a$`approx F`[1],
             num_df = a$`num Df`[1], den_df = a$`den Df`[1], p = a$`Pr(>F)`[1])
})
do.call(rbind, mantab) |>
  gt() |>
  fmt_number(columns = c(Statistic, Fapprox), decimals = 3) |>
  fmt_number(columns = p, decimals = 4) |>
  cols_label(Fapprox = md("Approx. *F*"), num_df = md("*df*~num~"),
             den_df = md("*df*~den~"), p = md("*p*")) |>
  tab_header(title = md("**Table 1**. Multivariate Tests of the Omnibus Hypothesis (McCarthy Data)")) |>
  cols_align(align = "center", columns = -Test)
Table 1. Multivariate Tests of the Omnibus Hypothesis (McCarthy Data)
Test Statistic Approx. F dfnum dfden p
Pillai 0.427 2.240 3 9 0.1528
Wilks 0.573 2.240 3 9 0.1528
Hotelling-Lawley 0.747 2.240 3 9 0.1528
Roy 0.747 2.240 3 9 0.1528
HideShow
#> 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.

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

Type III MANOVA Tests: Pillai test statistic
            Df test stat approx F num Df den Df Pr(>F)
(Intercept)  1   0.42749   2.2401      3      9 0.1528
HideShow
# Type II Sums of Squares
Anova(MANOVA_4DV, type=c("II"))
HideShow

Type III MANOVA Tests: Pillai test statistic
            Df test stat approx F num Df den Df Pr(>F)
(Intercept)  1   0.42749   2.2401      3      9 0.1528
HideShow
#> 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.

HideShow
# 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")
HideShow
Wilks's Lambda: 0.5725084 
HideShow
#> 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")
HideShow
Multivariate Omega Squared: 0.2823093 
HideShow
#> 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.

HideShow
data(chapter_13_table_2)

names(chapter_13_table_2)
HideShow
[1] "Time1" "Time2" "Time3"
HideShow
# Create Linear and Quadratic D variables
# Linear trend coefficients for a=3: -1, 0, 1
chapter_13_table_2$D_lin <- chapter_13_table_2$Time3 - chapter_13_table_2$Time1

# Quadratic trend coefficients for a=3: -1, 2, -1
chapter_13_table_2$D_quad <- 2 * chapter_13_table_2$Time2 - chapter_13_table_2$Time1 - chapter_13_table_2$Time3

# Create a Subject column so the output matches Table 13.10
chapter_13_table_2$Subject <- 1:nrow(chapter_13_table_2)

# View the new variables
chapter_13_table_2[, c("Subject", "D_lin", "D_quad")]
HideShow
  Subject D_lin D_quad
1       1     3     -1
2       2     5      1
3       3     2      2
4       4     0      2
5       5     5      1
6       6     6     -4
7       7     2      4
8       8     1      3
HideShow
#> 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.

HideShow
# 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)
HideShow
Analysis of Variance Table

            Df  Pillai approx F num Df den Df   Pr(>F)   
(Intercept)  1 0.86454   19.148      2      6 0.002485 **
Residuals    7                                           
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> 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.

HideShow
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
HideShow
       D_lin D_quad
D_lin     32    -26
D_quad   -26     44
HideShow
#> rows (32, -26) and (-26, 44) — matches book p. 726
E_R_trend
HideShow
       D_lin D_quad
D_lin    104     -2
D_quad    -2     52
HideShow
#> rows (104, -2) and (-2, 52) — matches book p. 726

c("|E(F)|" = det(E_F_trend), "|E(R)|" = det(E_R_trend))
HideShow
|E(F)| |E(R)| 
   732   5404 
HideShow
#> 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))
HideShow
[1] 19.14754
HideShow
#> 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.

HideShow
data(chapter_13_table_10)
poly <- chapter_13_table_10
poly
HideShow
  Linear Quadratic
1      3        -1
2      5         1
3      2         2
4      0         2
5      5         1
6      6        -4
7      2         4
8      1         3
HideShow
# Omnibus multivariate test that the Linear and Quadratic trends jointly differ from 0.
# Note intercept = TRUE: summary() for a manova object drops the intercept row by
# default, and the intercept IS the hypothesis of interest here, so without it the
# table comes back empty.
fit_poly <- manova(as.matrix(poly) ~ 1)
summary(fit_poly, test = "Hotelling-Lawley", intercept = TRUE)
HideShow
            Df Hotelling-Lawley approx F num Df den Df   Pr(>F)   
(Intercept)  1           6.3825   19.148      2      6 0.002485 **
Residuals    7                                                    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> 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)
HideShow

    One Sample t-test

data:  poly$Linear
t = 3.9686, df = 7, p-value = 0.005402
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 1.212512 4.787488
sample estimates:
mean of x 
        3 
HideShow
t.test(x = poly$Quadratic, mu = 0, alternative = "two.sided", conf.level = 0.95)
HideShow

    One Sample t-test

data:  poly$Quadratic
t = 1.1282, df = 7, p-value = 0.2964
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 -1.096015  3.096015
sample estimates:
mean of x 
        1 

The book does not print a tt for these contrasts; it prints an FF. The two are the same test, because a contrast has 1 numerator degree of freedom:

HideShow
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))
HideShow
        t t_squared 
 3.968627 15.750000 
HideShow
#> 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:

HideShow
# 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)
HideShow
E_F E_R 
 32 104 
HideShow
#> 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")
HideShow
F-statistic for the Linear Contrast: 15.75 
HideShow
#> 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.

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

Call:
lm(formula = D_lin ~ 1, data = chapter_13_table_2)

Residuals:
   Min     1Q Median     3Q    Max 
 -3.00  -1.25  -0.50   2.00   3.00 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)   
(Intercept)   3.0000     0.7559   3.969   0.0054 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.138 on 7 degrees of 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.

HideShow
# 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)
HideShow
[1] 5.591448
HideShow
#> 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.

HideShow
# 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")
HideShow
Raw p-value for the Linear Trend: 0.005401769 
HideShow
#> 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")
HideShow
Bonferroni Critical p-value: 0.025 
HideShow
#> .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.

HideShow
# 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
HideShow
[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.

HideShow
# 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)
HideShow
                   C alpha_per_comparison 
          3.00000000           0.01666667 
13.9.3 — Post Hoc Complex Comparisons

If we decide after looking at the data to test a complex comparison, we must use the Roy–Bose critical value, the multivariate extension of Scheffé’s method.

The book’s example asks, for the Table 13.2 data, whether level 1 differs from the average of levels 2 and 3 — a contrast chosen after noticing that levels 2 and 3 have similar means. The 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.

HideShow
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
HideShow
[1] -2.0 -4.0 -2.0 -0.5 -4.0 -3.5 -2.5 -1.5
HideShow
# 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")
HideShow
Dbar = -2.5  s^2_D = 1.571429  F = 31.81818 
HideShow
#> 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).

HideShow
a <- 3
n <- 8
alpha_FW <- 0.05

# Find the critical F for the omnibus test (df1 = a-1, df2 = n-a+1)
F_crit_omnibus <- qf(alpha_FW, df1 = a - 1, df2 = n - a + 1, lower.tail = FALSE)

# Calculate the Roy-Bose Critical Value (Equation 13.29)
CV_RB <- ((n - 1) * (a - 1) * F_crit_omnibus) / (n - a + 1)

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

HideShow
# The book's arithmetic, using the rounded tabled value
((n - 1) * (a - 1) * 5.14) / (n - a + 1)
HideShow
[1] 11.99333
HideShow
#> 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.

HideShow
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")
HideShow
Sample Mean Difference: 4 
HideShow
cat("Standard Error of Difference:", se_D1, "\n")
HideShow
Standard Error of Difference: 2.579053 
HideShow
#> 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.

HideShow
n <- length(D1)
df <- n - 1

# Critical t-value for unadjusted alpha = .05 (two-tailed). Equivalently, the square
# root of the critical F with 1 and n - 1 degrees of freedom, which is how the book
# writes w in Equation 13.30.
t_crit_unadj <- qt(0.025, df, lower.tail = FALSE)
c(t_crit = t_crit_unadj, sqrt_F_crit = sqrt(qf(0.05, 1, df, lower.tail = FALSE)))
HideShow
     t_crit sqrt_F_crit 
   2.200985    2.200985 
HideShow
#> 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")
HideShow
Margin of error: 5.676458 
HideShow
cat("Unadjusted 95% CI: [", CI_unadj[1], ",", CI_unadj[2], "]\n")
HideShow
Unadjusted 95% CI: [ -1.676458 , 9.676458 ]
HideShow
#> 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.

HideShow
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)
HideShow
  F_crit        w 
7.952590 2.820034 
HideShow
#> 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")
HideShow
Margin of error: 7.273017 
HideShow
cat("Bonferroni Adjusted 95% CI: [", CI_bonf[1], ",", CI_bonf[2], "]\n")
HideShow
Bonferroni Adjusted 95% CI: [ -3.273017 , 11.27302 ]
HideShow
#> 4.00 +/- 7.27 — matches book p. 732

# How much wider the Bonferroni interval is
moe_bonf / moe_unadj
HideShow
[1] 1.28126
HideShow
#> 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).

HideShow
# 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")
HideShow
Deviations: -9 -3 3 9  Sum of squares: 180 
HideShow
#> 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")
HideShow
Scaled Slope Coefficients: -0.05 -0.01666667 0.01666667 0.05 
HideShow
#> -9/180, -3/180, 3/180, 9/180 — matches book p. 733

# Create the D variable representing the slope
chapter_13_table_6$D_slope <-
  slope_coefs[1] * chapter_13_table_6$Months30 +
  slope_coefs[2] * chapter_13_table_6$Months36 +
  slope_coefs[3] * chapter_13_table_6$Months42 +
  slope_coefs[4] * chapter_13_table_6$Months48

# Run an intercept-only model to get the confidence interval
lm_slope <- lm(D_slope ~ 1, data = chapter_13_table_6)

# Output the estimated slope
summary(lm_slope)$coefficients
HideShow
            Estimate Std. Error  t value   Pr(>|t|)
(Intercept)      0.5  0.2230792 2.241357 0.04659037
HideShow
# the 95% CI
confint(lm_slope)
HideShow
                  2.5 %    97.5 %
(Intercept) 0.009006088 0.9909939
HideShow
#> 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.

HideShow
mc <- chapter_13_table_6
mc$D_36_30 <- mc$Months36 - mc$Months30
mc$D_42_36 <- mc$Months42 - mc$Months36
mc$D_48_42 <- mc$Months48 - mc$Months42
mc$D_48_30 <- mc$Months48 - mc$Months30   # the one significant pairwise difference

fit_36_30 <- lm(D_36_30 ~ 1, data = mc)
fit_42_36 <- lm(D_42_36 ~ 1, data = mc)
fit_48_42 <- lm(D_48_42 ~ 1, data = mc)
fit_48_30 <- lm(D_48_30 ~ 1, data = mc)
fit_slope <- lm(D_slope ~ 1, data = mc)   # D_slope built in the previous 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:

HideShow
modelsummary(
  list("36 - 30" = fit_36_30, "42 - 36" = fit_42_36, "48 - 42" = fit_48_42,
       "48 - 30" = fit_48_30, "Mean linear" = fit_slope),
  estimate  = "{estimate}",
  statistic = "({std.error})",   # standard errors in parentheses, APA style
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  stars     = TRUE,
  output    = "gt"               # gt backend, to match the gtsummary table below
)
36 - 30 42 - 36 48 - 42 48 - 30 Mean linear
(Intercept) 4.000 3.000 2.000 9.000 0.500
(2.579) (2.758) (2.233) (3.693) (0.223)
Num.Obs. 12 12 12 12 12
AIC 89.6 91.2 86.1 98.2 30.8
BIC 90.5 92.1 87.1 99.2 31.8
Log.Lik. -42.784 -43.588 -41.053 -47.091 -13.412
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001
HideShow
#> 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:

HideShow
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
HideShow
#> 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.

HideShow
data(chapter_13_table_2)

# Define the original unnormalized coefficients
coef_lin <- c(-1, 0, 1)
coef_quad <- c(-1, 2, -1)

# Normalization step: Divide by the square root of the sum of squared coefficients
norm_lin <- coef_lin / sqrt(sum(coef_lin^2))
norm_quad <- coef_quad / sqrt(sum(coef_quad^2))

cat("Normalized Linear Coefficients:", norm_lin, "\n")
HideShow
Normalized Linear Coefficients: -0.7071068 0 0.7071068 
HideShow
cat("Normalized Quadratic Coefficients:", norm_quad, "\n\n")
HideShow
Normalized Quadratic Coefficients: -0.4082483 0.8164966 -0.4082483 
HideShow
#> -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")
HideShow
Sum of cross-products: 0 
HideShow
cat("Sums of squared coefficients:", sum(norm_lin^2), sum(norm_quad^2), "\n")
HideShow
Sums of squared coefficients: 1 1 
HideShow
# Apply the normalized coefficients to create D*_1 and D*_2
chapter_13_table_2$D_star_1 <-
  norm_lin[1] * chapter_13_table_2$Time1 +
  norm_lin[2] * chapter_13_table_2$Time2 +
  norm_lin[3] * chapter_13_table_2$Time3

chapter_13_table_2$D_star_2 <-
  norm_quad[1] * chapter_13_table_2$Time1 +
  norm_quad[2] * chapter_13_table_2$Time2 +
  norm_quad[3] * chapter_13_table_2$Time3

# View the normalized D variables
chapter_13_table_2[, c("Time1", "Time2", "Time3", "D_star_1", "D_star_2")]
HideShow
  Time1 Time2 Time3  D_star_1   D_star_2
1     2     3     5 2.1213203 -0.4082483
2     4     7     9 3.5355339  0.4082483
3     6     8     8 1.4142136  0.8164966
4     8     9     8 0.0000000  0.8164966
5    10    13    15 3.5355339  0.4082483
6     3     4     9 4.2426407 -1.6329932
7     6     9     8 1.4142136  1.6329932
8     9    11    10 0.7071068  1.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.

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

HideShow
# Run intercept-only models on the normalized variables
model_D1_star <- lm(D_star_1 ~ 1, data = chapter_13_table_2)
model_D2_star <- lm(D_star_2 ~ 1, data = chapter_13_table_2)

# Combine the residuals into a matrix
resid_matrix_star <- cbind(model_D1_star$residuals, model_D2_star$residuals)

# Calculate the Full Model Error Matrix E*(F)
E_star_F <- t(resid_matrix_star) %*% resid_matrix_star

# Calculate the Restricted Model Error Matrix E*(R)
Y_matrix_star <- cbind(chapter_13_table_2$D_star_1, chapter_13_table_2$D_star_2)
E_star_R <- t(Y_matrix_star) %*% Y_matrix_star

# Full Model Error Matrix E*(F)
print(E_star_F)
HideShow
          [,1]      [,2]
[1,] 16.000000 -7.505553
[2,] -7.505553  7.333333
HideShow
#> 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)
HideShow
           [,1]       [,2]
[1,] 52.0000000 -0.5773503
[2,] -0.5773503  8.6666667
HideShow
#> 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:

HideShow
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)
HideShow
 |E*(F)|  |E*(R)| 
 61.0000 450.3333 
HideShow
#> 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)
HideShow
[1] 19.14754
HideShow
#> 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.

HideShow
# Extract the traces and compute the Mixed-Model SS
trace_E_star_F <- sum(diag(E_star_F))
trace_E_star_R <- sum(diag(E_star_R))

SS_interaction <- trace_E_star_F
SS_time <- trace_E_star_R - trace_E_star_F

cat(
  "Trace of E*(F) [SS Interaction / Error]:", SS_interaction, "\n",
  "Trace of E*(R):", trace_E_star_R, "\n",
  "Trace of E*(R) - Trace of E*(F) [SS Time Effect]:", SS_time, "\n"
)
HideShow
Trace of E*(F) [SS Interaction / Error]: 23.33333 
 Trace of E*(R): 60.66667 
 Trace of E*(R) - Trace of E*(F) [SS Time Effect]: 37.33333 
HideShow
#> 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}:

HideShow
# Mixed-model ANOVA for the Table 13.2 data (a = 3 levels, n = 8 subjects),
# built from the traces of the orthonormal error matrices computed above.
a_lev <- 3
n_sub <- 8
df_time <- a_lev - 1                 # 2
df_axs  <- (a_lev - 1) * (n_sub - 1) # 14

ms_time <- SS_time / df_time
ms_axs  <- SS_interaction / df_axs
F_time  <- ms_time / ms_axs
p_time  <- pf(F_time, df_time, df_axs, lower.tail = FALSE)

tibble::tibble(
  Source = c("Time", "Subjects × Time"),
  SS     = c(SS_time, SS_interaction),
  df     = c(df_time, df_axs),
  MS     = c(ms_time, ms_axs),
  Fstat  = c(F_time, NA_real_),
  p      = c(p_time, NA_real_)
) |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 4) |>
  fmt_number(columns = p, decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*")) |>
  tab_header(title = md("**Table 2**. Mixed-Model Analysis of the Data in Table 13.2")) |>
  cols_align(align = "center", columns = -Source)
Table 2. Mixed-Model Analysis of the Data in Table 13.2
Source SS df MS F p
Time 37.3333 2 18.6667 11.2000 0.0012
Subjects × Time 23.3333 14 1.6667

HideShow
#> 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.

HideShow
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
HideShow
#> 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.

HideShow
data(chapter_13_table_2)

# Create the normalized Linear Trend D variable (from previous section)
coef_lin <- c(-1, 0, 1)
norm_lin <- coef_lin / sqrt(sum(coef_lin^2))
chapter_13_table_2$D_star_1 <-
  norm_lin[1] * chapter_13_table_2$Time1 +
  norm_lin[2] * chapter_13_table_2$Time2 +
  norm_lin[3] * chapter_13_table_2$Time3

# Calculate values for the formulas
n <- 8
a <- 3

# E*(F) is the sum of squared deviations from the mean for our normalized variable
E_star_F <- sum((chapter_13_table_2$D_star_1 - mean(chapter_13_table_2$D_star_1))^2)

# The numerator is the difference in errors between restricted and full models
# E*(R) - E*(F) = n * (mean of D*_1)^2
numerator <- n * (mean(chapter_13_table_2$D_star_1))^2

# Multivariate F (Uses Separate Error Term)
# Denominator is simply the variance of the D*_1 variable
multi_denom <- E_star_F / (n - 1)
F_multi <- numerator / multi_denom

# Mixed-Model F (Uses Pooled Error Term)
# Denominator is MS_AxS, the trace of E*(F) divided by its degrees of freedom. We
# recompute it here rather than retyping 1.6667, so the page stands on its own.
MS_AxS <- SS_interaction / ((a - 1) * (n - 1))
F_mixed <- numerator / MS_AxS

cat(
  "Numerator (n * mean^2):", numerator, "\n",
  "MS_AxS (pooled error term):", MS_AxS, "\n",
  "Multivariate F (Separate Error Term):", F_multi, "\n",
  "Mixed-Model F (Pooled Error Term):", F_mixed, "\n"
)
HideShow
Numerator (n * mean^2): 36 
 MS_AxS (pooled error term): 1.666667 
 Multivariate F (Separate Error Term): 15.75 
 Mixed-Model F (Pooled Error Term): 21.6 
HideShow
#> 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.

HideShow
# Numerator is shared; only the denominator differs.
c(separate_error_term = E_star_F / (n - 1),
  pooled_error_term   = MS_AxS)
HideShow
separate_error_term   pooled_error_term 
           2.285714            1.666667 
HideShow
#> 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.

HideShow
# Create the normalized D variable for Time 2 - Time 1
coef_t1_t2 <- c(-1, 1, 0)
norm_t1_t2 <- coef_t1_t2 / sqrt(sum(coef_t1_t2^2))

chapter_13_table_2$D_star_T1_T2 <-
  norm_t1_t2[1] * chapter_13_table_2$Time1 +
  norm_t1_t2[2] * chapter_13_table_2$Time2 +
  norm_t1_t2[3] * chapter_13_table_2$Time3

# E*(F) for this specific contrast
E_star_F_T1_T2 <- sum((chapter_13_table_2$D_star_T1_T2 - mean(chapter_13_table_2$D_star_T1_T2))^2)

# Numerator
numerator_T1_T2 <- n * (mean(chapter_13_table_2$D_star_T1_T2))^2

# Multivariate F
multi_denom_T1_T2 <- E_star_F_T1_T2 / (n - 1)
F_multi_T1_T2 <- numerator_T1_T2 / multi_denom_T1_T2

# Mixed-Model F
# Uses the same pooled error term as before!
F_mixed_T1_T2 <- numerator_T1_T2 / MS_AxS

cat(
  "Numerator (n * mean^2):", numerator_T1_T2, "\n",
  "Separate error term:", multi_denom_T1_T2, "\n",
  "Multivariate F (Separate Error Term):", F_multi_T1_T2, "\n",
  "Mixed-Model F (Pooled Error Term):", F_mixed_T1_T2, "\n"
)
HideShow
Numerator (n * mean^2): 16 
 Separate error term: 0.4285714 
 Multivariate F (Separate Error Term): 37.33333 
 Mixed-Model F (Pooled Error Term): 9.6 
HideShow
#> 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():

HideShow
# Mauchly's test of sphericity, from base R's stats package, on the Table 13.2 data.
wide_13_2 <- as.matrix(chapter_13_table_2[, c("Time1", "Time2", "Time3")])
mlm_13_2  <- lm(wide_13_2 ~ 1)
idata     <- data.frame(Time = factor(c("Time1", "Time2", "Time3")))
mauchly.test(mlm_13_2, X = ~ 1, idata = idata)
HideShow

    Mauchly's test of sphericity
    Contrasts orthogonal to
    ~1


data:  SSD matrix from lm(formula = wide_13_2 ~ 1)
W = 0.44816, p-value = 0.09001

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

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

HideShow
# Equation 13.40, written out. Sigma is built from a correlation matrix and a common
# variance; C has a - 1 rows for the omnibus test or 1 row for a single contrast.
ncp_multivariate <- function(mu, R, variance, C, n) {
  Sigma <- variance * R
  Cmu   <- C %*% mu
  n * as.numeric(t(Cmu) %*% solve(C %*% Sigma %*% t(C)) %*% Cmu)
}

# Power of the multivariate omnibus test: df1 = a - 1, df2 = n - a + 1.
power_multivariate <- function(mu, R, variance, C, n, a, alpha = 0.05) {
  lambda <- ncp_multivariate(mu, R, variance, C, n)
  df1 <- nrow(C)
  df2 <- if (df1 == 1) n - 1 else n - a + 1
  pf(qf(1 - alpha, df1, df2), df1, df2, ncp = lambda, lower.tail = FALSE)
}
Comparing the power of the approaches

When planning a study, you might wonder whether to use the univariate mixed-model approach (with the Greenhouse–Geisser ε̂\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.

HideShow
variance_pop <- 96          # the book's population variance; sd = 9.79796
C_omnibus    <- rbind(c(-1, 1, 0),
                      c(0, -1, 1))

mu_scenario_1 <- c(10, 13, 16)
cor_matrix_1  <- matrix(c(1.0, 0.6, 0.3,
                          0.6, 1.0, 0.6,
                          0.3, 0.6, 1.0), nrow = 3)

mu_scenario_2 <- c(10, 16, 13)
cor_matrix_2  <- matrix(c(1.0, 0.6, 0.3,
                          0.6, 1.0, 0.3,
                          0.3, 0.3, 1.0), nrow = 3)

sample_sizes <- c(10, 15, 20, 25, 30)

mv_power_table <- data.frame(
  n = sample_sizes,
  Scenario_1 = sapply(sample_sizes, function(nn)
    power_multivariate(mu_scenario_1, cor_matrix_1, variance_pop, C_omnibus, nn, a = 3)),
  Scenario_2 = sapply(sample_sizes, function(nn)
    power_multivariate(mu_scenario_2, cor_matrix_2, variance_pop, C_omnibus, nn, a = 3))
)
round(mv_power_table, 3)
HideShow
   n Scenario_1 Scenario_2
1 10      0.212      0.343
2 15      0.340      0.550
3 20      0.463      0.712
4 25      0.574      0.826
5 30      0.669      0.899
HideShow
#> 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.

HideShow
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))
HideShow
   n Linear_trend
1 10        0.310
2 15        0.463
3 20        0.594
4 25        0.700
5 30        0.782
HideShow
#> .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:

HideShow
# Two closed-form epsilons, both functions of the eigenvalues of E* = U Sigma U',
# where U is an ORTHONORMAL basis for the (a - 1)-dimensional space of
# within-subjects contrasts.
epsilon_unirep <- function(mu, R, variance, n) {
  a  <- length(mu)
  rM <- a - 1                 # dimension of the contrast space
  nu <- n - 1                 # error degrees of freedom

  # An orthonormal U: Helmert contrasts, each row rescaled to unit length.
  U     <- t(apply(t(contr.helmert(a)), 1, function(r) r / sqrt(sum(r^2))))
  Estar <- U %*% (variance * R) %*% t(U)
  phi   <- eigen(Estar, symmetric = TRUE)$values

  # Box's epsilon: a fixed feature of Sigma, with no n in it.
  eps_pop <- sum(phi)^2 / (rM * sum(phi^2))

  # Muller and Barton's (1989) closed-form APPROXIMATION to E(epsilon-hat), and
  # the quantity SAS uses: num is E[tr(W)^2] and den is E[tr(W^2)] for W
  # Wishart on nu degrees of freedom, so this is a ratio of expectations
  # standing in for the expectation of the ratio that epsilon-hat is.
  num <- 2 * nu * sum(phi^2) + nu^2 * sum(phi)^2
  den <- nu * (nu + 2) * sum(phi^2) +
         2 * nu * sum(outer(phi, phi)[lower.tri(diag(rM))])

  c(epsilon_population = eps_pop, epsilon_MB = num / (rM * den))
}

# E(epsilon-hat) itself, by direct simulation. Epsilon-hat is a function of the
# sample covariance matrix alone, so the means play no part here: each replicate
# draws n subjects' contrast scores, forms their covariance, and applies Box's
# formula to it. 113 is the seed used throughout these notes.
E_eps_hat_sim <- function(mu, R, variance, n, reps = 50000, seed = 113) {
  set.seed(seed)
  a     <- length(mu); b <- a - 1
  U     <- t(apply(t(contr.helmert(a)), 1, function(r) r / sqrt(sum(r^2))))
  Estar <- U %*% (variance * R) %*% t(U)
  L     <- t(chol(Estar))                 # to give the contrasts their covariance

  id <- rep(seq_len(reps), each = n)
  D  <- matrix(rnorm(n * reps * b), n * reps, b) %*% t(L)
  M  <- rowsum(D, id) / n                 # contrast means, one row per replicate
  tr <- numeric(reps); tr_sq <- numeric(reps)
  for (j in seq_len(b)) for (k in seq_len(b)) {
    s <- (rowsum(D[, j] * D[, k], id)[, 1] - n * M[, j] * M[, k]) / (n - 1)
    if (j == k) tr <- tr + s
    tr_sq <- tr_sq + s^2
  }
  mean(tr^2 / (b * tr_sq))                # average of Box's epsilon-hat
}

eps_table <- data.frame(
  n = sample_sizes,
  t(sapply(sample_sizes, function(nn)
    epsilon_unirep(mu_scenario_1, cor_matrix_1, variance_pop, nn))),
  S1_sim = sapply(sample_sizes, function(nn)
    E_eps_hat_sim(mu_scenario_1, cor_matrix_1, variance_pop, nn)),
  t(sapply(sample_sizes, function(nn)
    epsilon_unirep(mu_scenario_2, cor_matrix_2, variance_pop, nn))),
  S2_sim = sapply(sample_sizes, function(nn)
    E_eps_hat_sim(mu_scenario_2, cor_matrix_2, variance_pop, nn))
)
names(eps_table) <- c("n", "S1_epsilon", "S1_MB_approx", "S1_E_eps_hat",
                      "S2_epsilon", "S2_MB_approx", "S2_E_eps_hat")
round(eps_table, 3)
HideShow
   n S1_epsilon S1_MB_approx S1_E_eps_hat S2_epsilon S2_MB_approx S2_E_eps_hat
1 10      0.862        0.747        0.787        0.9        0.771        0.806
2 15      0.862        0.781        0.812        0.9        0.810        0.836
3 20      0.862        0.800        0.827        0.9        0.830        0.852
4 25      0.862        0.812        0.833        0.9        0.843        0.861
5 30      0.862        0.820        0.839        0.9        0.852        0.868
HideShow
#> 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:

HideShow
# Power of the Greenhouse-Geisser-corrected univariate test, by the UNIREP
# approximation of Muller and Barton (1989) and Muller, Edwards, Simpson, and
# Taylor (2007) -- the calculation PROC GLMPOWER performs for mtest = gg.
power_unirep_gg <- function(mu, R, variance, n, alpha = 0.05,
                            epsilon = c("muller_barton", "population",
                                        "simulated")) {
  epsilon <- match.arg(epsilon)
  a <- length(mu); rM <- a - 1; nu <- n - 1

  U     <- t(apply(t(contr.helmert(a)), 1, function(r) r / sqrt(sum(r^2))))
  Estar <- U %*% (variance * R) %*% t(U)
  ev    <- eigen(Estar, symmetric = TRUE)
  phi   <- ev$values                     # weights of the chi-squares
  gamma <- ev$vectors
  theta <- as.numeric(U %*% mu)          # contrast means
  omega <- n * diag(t(gamma) %*% outer(theta, theta) %*% gamma) / phi

  # Two-moment (Satterthwaite) match to the two weighted sums of chi-squares.
  s1 <- sum(phi);   s2 <- sum(phi * omega)
  s3 <- sum(phi^2); s4 <- sum(phi^2 * omega)
  ratio_hyp <- (s3 + 2 * s4) / (s1 + 2 * s2)
  ratio_err <- s3 / s1
  df1_star  <- s1 / ratio_hyp
  df2_star  <- nu * s1 / ratio_err
  lambda    <- s2 / ratio_hyp

  # Which epsilon sets the critical value: Muller and Barton's closed form, as
  # the book's calculation does it; the population value an idealized test
  # would know; or E(epsilon-hat) itself, simulated.
  eps <- epsilon_unirep(mu, R, variance, n)
  e   <- switch(epsilon,
                muller_barton = eps[["epsilon_MB"]],
                population    = eps[["epsilon_population"]],
                simulated     = E_eps_hat_sim(mu, R, variance, n))

  crit <- qf(1 - alpha, rM * e, rM * nu * e)
  pf(crit, df1_star, df2_star, ncp = lambda, lower.tail = FALSE)
}

gg_power_table <- data.frame(
  n = sample_sizes,
  Scenario_1 = sapply(sample_sizes, function(nn)
    power_unirep_gg(mu_scenario_1, cor_matrix_1, variance_pop, nn)),
  Scenario_2 = sapply(sample_sizes, function(nn)
    power_unirep_gg(mu_scenario_2, cor_matrix_2, variance_pop, nn))
)
round(gg_power_table, 3)
HideShow
   n Scenario_1 Scenario_2
1 10      0.282      0.233
2 15      0.437      0.398
3 20      0.569      0.555
4 25      0.677      0.688
5 30      0.763      0.791
HideShow
#> 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.

HideShow
# The test a researcher actually runs, simulated. Each replicate draws its own
# sample, computes its own epsilon-hat, and is judged against its own critical
# value. 113 is the seed used throughout these notes.
power_gg_sim <- function(mu, R, variance, n, alpha = 0.05, reps = 20000,
                         chunk = 5000, seed = 113) {
  set.seed(seed)
  a <- length(mu); b <- a - 1
  U     <- t(apply(t(contr.helmert(a)), 1, function(r) r / sqrt(sum(r^2))))
  Estar <- U %*% (variance * R) %*% t(U)
  theta <- as.numeric(U %*% mu)
  L     <- t(chol(Estar))                 # to give the contrasts their covariance

  rejections <- 0; done <- 0
  while (done < reps) {                   # in chunks, to keep memory modest
    this <- min(chunk, reps - done)
    id   <- rep(seq_len(this), each = n)
    D    <- matrix(rnorm(n * this * b), n * this, b) %*% t(L)
    D    <- sweep(D, 2, theta, "+")       # this * n subjects, b contrast scores
    Mean <- rowsum(D, id) / n             # contrast means, one row per replicate
    S    <- array(0, c(this, b, b))       # contrast covariance, per replicate
    for (j in seq_len(b)) for (k in j:b) {
      s <- (rowsum(D[, j] * D[, k], id)[, 1] - n * Mean[, j] * Mean[, k]) / (n - 1)
      S[, j, k] <- s; S[, k, j] <- s
    }
    tr <- numeric(this); tr_sq <- numeric(this)
    for (j in seq_len(b)) tr <- tr + S[, j, j]
    for (j in seq_len(b)) for (k in seq_len(b)) tr_sq <- tr_sq + S[, j, k]^2

    F_stat  <- n * rowSums(Mean^2) / tr
    eps_hat <- tr^2 / (b * tr_sq)         # Greenhouse-Geisser, from this sample
    rejections <- rejections +
      sum(F_stat > qf(1 - alpha, b * eps_hat, b * (n - 1) * eps_hat))
    done <- done + this
  }
  rejections / reps
}

gg_check <- data.frame(
  n              = sample_sizes,
  Book_S1        = c(.282, .437, .569, .677, .763),
  Closed_form_S1 = gg_power_table$Scenario_1,
  Simulated_S1   = sapply(sample_sizes, function(nn)
    power_gg_sim(mu_scenario_1, cor_matrix_1, variance_pop, nn)),
  Book_S2        = c(.233, .398, .555, .688, .791),
  Closed_form_S2 = gg_power_table$Scenario_2,
  Simulated_S2   = sapply(sample_sizes, function(nn)
    power_gg_sim(mu_scenario_2, cor_matrix_2, variance_pop, nn))
)
round(gg_check, 3)
HideShow
   n Book_S1 Closed_form_S1 Simulated_S1 Book_S2 Closed_form_S2 Simulated_S2
1 10   0.282          0.282        0.284   0.233          0.233        0.241
2 15   0.437          0.437        0.436   0.398          0.398        0.408
3 20   0.569          0.569        0.567   0.555          0.555        0.556
4 25   0.677          0.677        0.673   0.688          0.688        0.684
5 30   0.763          0.763        0.760   0.791          0.791        0.788
HideShow
#> 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
HideShow
[1] 0.0035
HideShow
round(sqrt(gg_check$Simulated_S1 * (1 - gg_check$Simulated_S1) / 20000), 4)
HideShow
[1] 0.0032 0.0035 0.0035 0.0033 0.0030
HideShow
#> .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:

HideShow
eps_source_table <- data.frame(
  n           = sample_sizes,
  MB_S1       = gg_power_table$Scenario_1,
  Sim_eps_S1  = sapply(sample_sizes, function(nn)
    power_unirep_gg(mu_scenario_1, cor_matrix_1, variance_pop, nn,
                    epsilon = "simulated")),
  MB_S2       = gg_power_table$Scenario_2,
  Sim_eps_S2  = sapply(sample_sizes, function(nn)
    power_unirep_gg(mu_scenario_2, cor_matrix_2, variance_pop, nn,
                    epsilon = "simulated"))
)
round(eps_source_table, 3)
HideShow
   n MB_S1 Sim_eps_S1 MB_S2 Sim_eps_S2
1 10 0.282      0.292 0.233      0.243
2 15 0.437      0.444 0.398      0.406
3 20 0.569      0.575 0.555      0.561
4 25 0.677      0.682 0.688      0.693
5 30 0.763      0.766 0.791      0.794
HideShow
#> 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:

HideShow
known_eps_table <- data.frame(
  n = sample_sizes,
  Book_S1          = c(.282, .437, .569, .677, .763),
  Known_epsilon_S1 = sapply(sample_sizes, function(nn)
    power_unirep_gg(mu_scenario_1, cor_matrix_1, variance_pop, nn,
                    epsilon = "population")),
  Book_S2          = c(.233, .398, .555, .688, .791),
  Known_epsilon_S2 = sapply(sample_sizes, function(nn)
    power_unirep_gg(mu_scenario_2, cor_matrix_2, variance_pop, nn,
                    epsilon = "population"))
)
round(known_eps_table, 3)
HideShow
   n Book_S1 Known_epsilon_S1 Book_S2 Known_epsilon_S2
1 10   0.282            0.309   0.233            0.266
2 15   0.437            0.456   0.398            0.424
3 20   0.569            0.583   0.555            0.575
4 25   0.677            0.687   0.688            0.702
5 30   0.763            0.770   0.791            0.801
HideShow
#> 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}:

HideShow
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)
HideShow
   n GG_adjusted Multivariate Linear_trend
1 10       0.282        0.212        0.310
2 15       0.437        0.340        0.463
3 20       0.569        0.463        0.594
4 25       0.677        0.574        0.700
5 30       0.763        0.669        0.782
HideShow
#> 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

Chapter 14: Higher Order Designs with Within-Subjects Factors: The Multivariate Approach

Open the separate reading

Code
Results
On this page

Chapter 14 extends the multivariate approach to higher-order experimental designs, specifically focusing on designs with multiple within-subjects factors and mixed (split-plot) designs containing both within- and between-subjects factors. By transforming repeated measures into composite difference (DD) variables, the text demonstrates how to test main effects and interactions without relying on the restrictive sphericity assumption required by the traditional univariate mixed-model approach. Once omnibus multivariate tests establish statistical significance, the chapter details how to rigorously probe these findings using simple effects tests, interaction contrasts, and confidence intervals. It also addresses the unique analytical needs of longitudinal randomized designs, emphasizing the superiority of MANCOVA over repeated measures ANOVA for evaluating treatment effects over time while controlling for baseline scores. Finally, the chapter equips researchers with practical tools for power analysis and sample size planning, demonstrating how different methodological choices and contrast specifications impact statistical power in these complex designs.

Chapter 1 explains how the book’s data sets are named in AMCP and covers the operational details of R that we do not repeat here. This chapter uses four of those data sets: chapter_14_table_1 (the 2×22 \times 2 perceptual experiment), chapter_14_table_4 (the 2×32 \times 3 version of the same experiment), chapter_14_table_7 (the split-plot design with two angle conditions), and chapter_14_table_9 (the split-plot design with three angle conditions).

HideShow
# Load all of the packages used.
library(tidyverse)      # data wrangling and plotting (dplyr, ggplot2, and friends)
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(MASS)           # mvrnorm(): multivariate normal data for the power simulations
library(car)            # Anova() and Manova() for Type II/III tests
library(broom)          # tidy model output into data frames
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables

14.2 — Two Within-Subjects Factors, Each with Two Levels

To explore the multivariate approach for a 2×22 \times 2 within-subjects design, we rely on the perceptual experiment data introduced in the text (Table 14.1, p. 768). In this study, 10 participants are measured on their reaction times to recognize a target letter. There are two within-subjects factors: Noise (Absent vs. Present) and Angle (0 degrees vs. 8 degrees).

Let’s begin by loading the data for this example.

HideShow
data(chapter_14_table_1)
str(chapter_14_table_1)
HideShow
'data.frame':   10 obs. of  4 variables:
 $ Absent0 : int  420 420 480 420 540 360 480 480 540 480
 $ Absent8 : int  480 480 540 540 540 360 600 660 540 540
 $ Present0: int  480 360 660 480 480 360 540 540 480 540
 $ Present8: int  780 600 780 900 720 540 840 900 780 780
HideShow
chapter_14_table_1
HideShow
   Absent0 Absent8 Present0 Present8
1      420     480      480      780
2      420     480      360      600
3      480     540      660      780
4      420     540      480      900
5      540     540      480      720
6      360     360      360      540
7      480     600      540      840
8      480     660      540      900
9      540     540      480      780
10     480     540      540      780
HideShow
# Cell means, to check the data against the book.
colMeans(chapter_14_table_1)
HideShow
 Absent0  Absent8 Present0 Present8 
     462      528      492      762 
HideShow
#> 462, 528, 492, 762 — matches the Mean row of Table 14.1 (p. 768) and the
#> cell means of Table 14.2 (p. 769).

Table 14.2 (p. 769) also reports the marginal means, which are what the two main effects compare. They follow from the cell means.

HideShow
# Marginal means for Angle (averaging over Noise) and for Noise (averaging over Angle).
with(chapter_14_table_1, c(
  Angle0 = mean(c(Absent0, Present0)),
  Angle8 = mean(c(Absent8, Present8))
))
HideShow
Angle0 Angle8 
   477    645 
HideShow
#> 477 and 645 — matches Table 14.2 (p. 769).

with(chapter_14_table_1, c(
  Noise_Absent  = mean(c(Absent0, Absent8)),
  Noise_Present = mean(c(Present0, Present8))
))
HideShow
 Noise_Absent Noise_Present 
          495           627 
HideShow
#> 495 and 627 — matches Table 14.2 (p. 769).

Because both factors have exactly two levels, any main effect or interaction will only have 1 degree of freedom. This means we can test each omnibus effect individually by constructing a single difference score (DD variable) for each one.

  • D1D_1 (Main Effect of Angle): Averages across the Noise factor and subtracts the 0-degree angle scores from the 8-degree angle scores.

  • D2D_2 (Main Effect of Noise): Averages across the Angle factor and subtracts the Noise-Absent scores from the Noise-Present scores.

  • D3D_3 (Angle ×\times Noise Interaction): Measures how the Angle effect changes depending on the presence or absence of Noise.

14.2.1 — Formation of Main-Effect DD Variables
HideShow
# Create difference scores, per the rationale given in the book.
# D1 is Equation 14.1 (p. 770) and D2 is Equation 14.9 (p. 771).
chapter_14_table_1$D1 <- .5*(chapter_14_table_1$Absent8 + chapter_14_table_1$Present8) - .5*(chapter_14_table_1$Absent0 + chapter_14_table_1$Present0)

chapter_14_table_1$D2 <- .5*(chapter_14_table_1$Present0 + chapter_14_table_1$Present8) - .5*(chapter_14_table_1$Absent0 + chapter_14_table_1$Absent8)
14.2.2 — Formation of Interaction DD Variables

The interaction difference score is the difference between the Angle effect when Noise is present and the Angle effect when Noise is absent (Equation 14.10, p. 771).

HideShow
chapter_14_table_1$D3 <- (chapter_14_table_1$Present8 - chapter_14_table_1$Absent8) - (chapter_14_table_1$Present0 - chapter_14_table_1$Absent0)

chapter_14_table_1
HideShow
   Absent0 Absent8 Present0 Present8  D1  D2  D3
1      420     480      480      780 180 180 240
2      420     480      360      600 150  30 180
3      480     540      660      780  90 210  60
4      420     540      480      900 270 210 300
5      540     540      480      720 120  60 240
6      360     360      360      540  90  90 180
7      480     600      540      840 210 150 180
8      480     660      540      900 270 150 180
9      540     540      480      780 150  90 300
10     480     540      540      780 150 150 180

We can summarize these new difference scores to check the means and variability.

HideShow
# dplyr is loaded above as part of tidyverse.
chapter_14_table_1_Summary <- chapter_14_table_1 %>%
  summarize(
    Mean_D1 = mean(D1),
    Mean_D2 = mean(D2),
    Mean_D3 = mean(D3),
    SD_D1 = sd(D1),
    SD_D2 = sd(D2),
    SD_D3 = sd(D3)
  )

chapter_14_table_1_Summary
HideShow
  Mean_D1 Mean_D2 Mean_D3    SD_D1    SD_D2    SD_D3
1     168     132     204 65.11528 61.96773 70.42727
HideShow
#> Means 168, 132, and 204 — match the Mean row of Table 14.3 (p. 769).

# Or more simply using base R
summary(chapter_14_table_1[, c("D1", "D2", "D3")])
HideShow
       D1              D2              D3     
 Min.   : 90.0   Min.   : 30.0   Min.   : 60  
 1st Qu.:127.5   1st Qu.: 90.0   1st Qu.:180  
 Median :150.0   Median :150.0   Median :180  
 Mean   :168.0   Mean   :132.0   Mean   :204  
 3rd Qu.:202.5   3rd Qu.:172.5   3rd Qu.:240  
 Max.   :270.0   Max.   :210.0   Max.   :300  
Testing the hypotheses

The null hypothesis for each effect stipulates that the population mean of its respective DD variable is equal to zero (μ=0\mu = 0).

One way of testing the DD variables is a one-sample tt-test of each difference score against a null value of 0. Because each effect has 1 numerator degree of freedom, each tt here is the square root of the corresponding FF reported in the book.

HideShow
t.test(
  x           = chapter_14_table_1$D1,
  mu          = 0,
  alternative = "two.sided",
  conf.level  = 0.95
)
HideShow

    One Sample t-test

data:  chapter_14_table_1$D1
t = 8.1588, df = 9, p-value = 1.891e-05
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 121.4193 214.5807
sample estimates:
mean of x 
      168 
HideShow
#> t = 8.1588, and 8.1588^2 = 66.57 — matches the F on p. 771.

t.test(
  x           = chapter_14_table_1$D2,
  mu          = 0,
  alternative = "two.sided",
  conf.level  = 0.95
)
HideShow

    One Sample t-test

data:  chapter_14_table_1$D2
t = 6.7361, df = 9, p-value = 8.498e-05
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
  87.67095 176.32905
sample estimates:
mean of x 
      132 
HideShow
#> t = 6.7361, and 6.7361^2 = 45.375 — matches the F on p. 771.

t.test(
  x           = chapter_14_table_1$D3,
  mu          = 0,
  alternative = "two.sided",
  conf.level  = 0.95
)
HideShow

    One Sample t-test

data:  chapter_14_table_1$D3
t = 9.1599, df = 9, p-value = 7.391e-06
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 153.6194 254.3806
sample estimates:
mean of x 
      204 
HideShow
#> t = 9.1599, and 9.1599^2 = 83.90 — matches the F on p. 771.

Equivalently, the book computes each effect by hand with Equation 14.8 (p. 770), F=nD‾2/sD2F = n\bar{D}^2 / s^2_{D}. Plugging the actual sample values for each DD variable into that formula reproduces the book’s FF values exactly:

HideShow
n <- nrow(chapter_14_table_1)

# The ingredients the book reports for D1 on p. 771.
c(n = n, Dbar = mean(chapter_14_table_1$D1), s2 = var(chapter_14_table_1$D1))
HideShow
   n Dbar   s2 
  10  168 4240 
HideShow
#> n = 10, Dbar = 168, s^2 = 4,240 — matches p. 771.

# Equation 14.8 applied to each D variable.
F_D1 <- n * mean(chapter_14_table_1$D1)^2 / var(chapter_14_table_1$D1)
F_D2 <- n * mean(chapter_14_table_1$D2)^2 / var(chapter_14_table_1$D2)
F_D3 <- n * mean(chapter_14_table_1$D3)^2 / var(chapter_14_table_1$D3)

c(Angle_D1 = F_D1, Noise_D2 = F_D2, Interaction_D3 = F_D3)
HideShow
      Angle_D1       Noise_D2 Interaction_D3 
      66.56604       45.37500       83.90323 
HideShow
#> Angle  D1: F = 66.57 — matches book p. 771.
#> Noise  D2: F = 45.375 — matches book p. 771.
#> Inter. D3: F = 83.90 — matches book p. 771.

# Each observed F is referred to a critical F with 1 and n - 1 degrees of freedom.
qf(p = 1 - .05, df1 = 1, df2 = n - 1)
HideShow
[1] 5.117355
HideShow
#> 5.12 — matches the critical value quoted on p. 771.

The textbook explicitly frames these hypothesis tests as a comparison between a full model and a restricted model. We can map this framework onto R code.

Below, we fit two linear models for the Angle main effect (D1D_1). The first is the Full Model (which includes an intercept to estimate the mean), and the second is the Restricted Model (which forces the intercept to 0). We then compare the two using the anova() function to reproduce the FF-test in the book.

HideShow
# Full Model
D1_Model_Mean <- lm(D1 ~ 1, data=chapter_14_table_1)
summary(D1_Model_Mean)
HideShow

Call:
lm(formula = D1 ~ 1, data = chapter_14_table_1)

Residuals:
   Min     1Q Median     3Q    Max 
 -78.0  -40.5  -18.0   34.5  102.0 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   168.00      20.59   8.159 1.89e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 65.12 on 9 degrees of freedom
HideShow
# Restricted Model
D1_Model_Null <- lm(D1 ~ 0, data=chapter_14_table_1)

# Compare the restricted model to the full model
anova(D1_Model_Null, D1_Model_Mean)
HideShow
Analysis of Variance Table

Model 1: D1 ~ 0
Model 2: D1 ~ 1
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
1     10 320400                                  
2      9  38160  1    282240 66.566 1.891e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> The two RSS columns are E(R) and E(F) of Equations 14.6 and 14.5 (p. 770),
#> and the model comparison gives F = 66.57 — matches book p. 771.

Now that we have confirmed the main effect of Angle (D1), we can apply this exact same full-versus-restricted model comparison logic to test the main effect of Noise (D2) and the Angle x Noise interaction (D3).

HideShow
# Models for D2 (Noise Main Effect)
D2_Model_Mean <- lm(D2 ~ 1, data=chapter_14_table_1)
D2_Model_Null <- lm(D2 ~ 0, data=chapter_14_table_1)
anova(D2_Model_Null, D2_Model_Mean)
HideShow
Analysis of Variance Table

Model 1: D2 ~ 0
Model 2: D2 ~ 1
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
1     10 208800                                  
2      9  34560  1    174240 45.375 8.498e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 45.375 for the Noise main effect — matches book p. 771.

# Models for D3 (Angle x Noise Interaction)
D3_Model_Mean <- lm(D3 ~ 1, data=chapter_14_table_1)
D3_Model_Null <- lm(D3 ~ 0, data=chapter_14_table_1)
anova(D3_Model_Null, D3_Model_Mean)
HideShow
Analysis of Variance Table

Model 1: D3 ~ 0
Model 2: D3 ~ 1
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
1     10 460800                                  
2      9  44640  1    416160 83.903 7.391e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 83.90 for the Angle x Noise interaction — matches book p. 771.
14.2.3 — Relationship to the Mixed-Model Approach

It is important to note that because this is a 2×22 \times 2 design, the main effects and the interaction all have exactly 1 numerator degree of freedom. Consequently, the sphericity assumption required by the traditional mixed-model approach is necessarily satisfied. The book makes the point explicitly on p. 772: when every factor has only two levels, the multivariate and mixed-model approaches are identical, provided the mixed-model approach uses an error term of the form MSeffect×SMS_{\text{effect} \times S}. The degrees of freedom agree as well, so there is nothing to choose between the two approaches here.

14.3 — Multivariate Analysis of Two-Way a×ba \times b Within-Subjects Designs

To motivate the analysis of a general a×ba \times b within-subjects design, we continue with the perceptual experiment, but we now reinstate the 4-degree angle condition. This gives us a 2×32 \times 3 design (Noise: Absent vs. Present; Angle: 0, 4, and 8 degrees). Following the book, Angle is the AA factor, with a=3a = 3 levels, and Noise is the BB factor, with b=2b = 2 levels. These are the data of Table 14.4 (p. 774), which are the same data as Table 12.1 so that the multivariate and mixed-model analyses can be compared.

HideShow
data(chapter_14_table_4)
str(chapter_14_table_4)
HideShow
'data.frame':   10 obs. of  6 variables:
 $ Absent0 : int  420 420 480 420 540 360 480 480 540 480
 $ Absent4 : int  420 480 480 540 660 420 480 600 600 420
 $ Absent8 : int  480 480 540 540 540 360 600 660 540 540
 $ Present0: int  480 360 660 480 480 360 540 540 480 540
 $ Present4: int  600 480 780 780 660 480 720 720 720 660
 $ Present8: int  780 600 780 900 720 540 840 900 780 780
HideShow
chapter_14_table_4
HideShow
   Absent0 Absent4 Absent8 Present0 Present4 Present8
1      420     420     480      480      600      780
2      420     480     480      360      480      600
3      480     480     540      660      780      780
4      420     540     540      480      780      900
5      540     660     540      480      660      720
6      360     420     360      360      480      540
7      480     480     600      540      720      840
8      480     600     660      540      720      900
9      540     600     540      480      720      780
10     480     420     540      540      660      780
HideShow
# Cell means, to check the data against the book.
colMeans(chapter_14_table_4)
HideShow
 Absent0  Absent4  Absent8 Present0 Present4 Present8 
     462      510      528      492      660      762 
HideShow
#> 462, 510, 528, 492, 660, 762 — matches the Mean row of Table 14.4 (p. 774).

The six cell means are worth looking at before any test is run, because the whole argument of the section is about the pattern they form.

HideShow
cell_means <- chapter_14_table_4 |>
  summarize(across(Absent0:Present8, mean)) |>
  pivot_longer(everything(), names_to = "cell", values_to = "Mean_RT") |>
  mutate(
    Noise = if_else(str_starts(cell, "Absent"), "Absent", "Present"),
    Angle = as.numeric(str_remove(cell, "Absent|Present"))
  ) |>
  mutate(Noise = factor(Noise, levels = c("Absent", "Present")))

cell_means
HideShow
# A tibble: 6 × 4
  cell     Mean_RT Noise   Angle
  <chr>      <dbl> <fct>   <dbl>
1 Absent0      462 Absent      0
2 Absent4      510 Absent      4
3 Absent8      528 Absent      8
4 Present0     492 Present     0
5 Present4     660 Present     4
6 Present8     762 Present     8
HideShow
ggplot(cell_means, aes(x = Angle, y = Mean_RT, color = Noise, shape = Noise)) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 3) +
  scale_x_continuous(breaks = c(0, 4, 8)) +
  labs(
    x     = "Angle (degrees off center)",
    y     = "Mean reaction time (ms)",
    color = "Noise",
    shape = "Noise"
  )
Sample cell means for the \(2 \times 3\) perceptual experiment (Table 14.4, p. 774).

Sample cell means for the 2×32 \times 3 perceptual experiment (Table 14.4, p. 774).

14.3.1 — Formation of Main-Effect DD Variables

Because the Angle factor has three levels, we must form a−1=2a - 1 = 2 separate DD variables to test its main effect. Since Angle is quantitative, we will use coefficients for linear (-1, 0, 1) and quadratic (1, -2, 1) trends to create D1D_1 and D2D_2, respectively, averaging across the Noise factor (Equations 14.14 and 14.15, p. 774).

Because the Noise factor only has two levels, we only need b−1=1b - 1 = 1 DD variable (D3D_3) to test its main effect, which simply finds the difference between the average Noise Present and Noise Absent scores (Equation 14.16, p. 775).

HideShow
# Define Angle Main Effect D variables (Linear and Quadratic Trends)
chapter_14_table_4$D1 <- -1*(.5*(chapter_14_table_4$Absent0 + chapter_14_table_4$Present0)) + 0*(.5*(chapter_14_table_4$Absent4 + chapter_14_table_4$Present4)) + 1*(.5*(chapter_14_table_4$Absent8 + chapter_14_table_4$Present8))

chapter_14_table_4$D2 <- 1*(.5*(chapter_14_table_4$Absent0 + chapter_14_table_4$Present0)) - 2*(.5*(chapter_14_table_4$Absent4 + chapter_14_table_4$Present4)) + 1*(.5*(chapter_14_table_4$Absent8 + chapter_14_table_4$Present8))

# Define Noise Main Effect D variable
chapter_14_table_4$D3 <- (1/3)*(chapter_14_table_4$Present0 + chapter_14_table_4$Present4 + chapter_14_table_4$Present8) - (1/3)*(chapter_14_table_4$Absent0 + chapter_14_table_4$Absent4 + chapter_14_table_4$Absent8)
14.3.2 — Formation of Interaction DD Variables

The interaction requires (a−1)(b−1)=2(a - 1)(b - 1) = 2 DD variables. We create D4D_4 and D5D_5 by cross-multiplying the coefficients of the Angle variables (D1D_1, D2D_2) with the Noise variable (D3D_3), which is Equation 14.23 and Equation 14.24 (p. 776).

HideShow
# Define Interaction D variables (Cross-products of Main Effect coefficients)
chapter_14_table_4$D4 <- 1*chapter_14_table_4$Absent0 + 0*chapter_14_table_4$Absent4 - 1*chapter_14_table_4$Absent8 -1*chapter_14_table_4$Present0 + 0*chapter_14_table_4$Present4 + 1*chapter_14_table_4$Present8

chapter_14_table_4$D5 <- -1*chapter_14_table_4$Absent0 + 2*chapter_14_table_4$Absent4 -1*chapter_14_table_4$Absent8 + 1*chapter_14_table_4$Present0 - 2*chapter_14_table_4$Present4 + 1*chapter_14_table_4$Present8

# Review the resulting Difference variables
chapter_14_table_4[, c("D1", "D2", "D3", "D4", "D5")]
HideShow
    D1   D2  D3  D4   D5
1  180   60 180 240    0
2  150  -30  20 180   60
3   90  -30 240  60 -180
4  270 -150 220 300  -60
5  120 -180  40 240  120
6   90  -90  80 180   60
7  210   30 180 180 -180
8  270  -30 140 180   60
9  150 -150 100 300  -60
10 150   90 180 180 -180
HideShow
# Their means are the Mean row of Table 14.5.
colMeans(chapter_14_table_4[, c("D1", "D2", "D3", "D4", "D5")])
HideShow
 D1  D2  D3  D4  D5 
168 -48 138 204 -36 
HideShow
#> 168, -48, 138, 204, -36 — matches Table 14.5 (p. 775).
14.3.3 — Omnibus Tests—Multivariate Significance Tests

To test the main effect of Angle, we must test the null hypothesis that both D1D_1 and D2D_2 equal zero simultaneously. The book does this by building the error matrices E(F)E(F) and E(R)E(R) for the full and restricted models and comparing their determinants with Equation 14.28 (p. 777). Nothing but base R is needed for that, and it is worth doing once so the machinery is visible:

HideShow
D_A <- as.matrix(chapter_14_table_4[, c("D1", "D2")])
n   <- nrow(D_A)

# E(F): deviations from the sample means of D1 and D2.
E_F_A <- crossprod(sweep(D_A, 2, colMeans(D_A)))

# E(R): deviations from zero, which is what the null hypothesis asserts.
E_R_A <- crossprod(D_A)

E_F_A
HideShow
      D1    D2
D1 38160  3240
D2  3240 77760
HideShow
#> 38,160 and 77,760 on the diagonal, 3,240 off it — matches E(F) on p. 778.
E_R_A
HideShow
       D1     D2
D1 320400 -77400
D2 -77400 100800
HideShow
#> 320,400 and 100,800 on the diagonal, -77,400 off it — matches E(R) on p. 778.

c(det_E_F = det(E_F_A), det_E_R = det(E_R_A))
HideShow
    det_E_F     det_E_R 
 2956824000 26305560000 
HideShow
#> 2,956,824,000 and 26,305,560,000 — match the determinants on p. 778.

# Equation 14.28, with a = 3 levels of Angle.
a <- 3
F_A <- ((det(E_R_A) - det(E_F_A)) / (a - 1)) / (det(E_F_A) / (n - a + 1))
c(F_A = F_A, p = pf(F_A, df1 = a - 1, df2 = n - a + 1, lower.tail = FALSE))
HideShow
         F_A            p 
31.586237125  0.000159629 
HideShow
#> F = 31.59 with 2 and 8 df, p = .0002 — matches book p. 778.

R’s manova() does the same determinant arithmetic for us, and anova() on the fitted object reports it as Wilks’s Lambda with the same approximate FF.

HideShow
# Multivariate test for the Main Effect of Angle (A)
MANOVA_A <- manova(cbind(D1, D2) ~ 1, data=chapter_14_table_4)
anova(MANOVA_A, test="Wilks")
HideShow
Analysis of Variance Table

            Df  Wilks approx F num Df den Df    Pr(>F)    
(Intercept)  1 0.1124   31.586      2      8 0.0001596 ***
Residuals    9                                            
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> approx F = 31.586 with 2 and 8 df — matches the hand computation above and
#> book p. 778. Wilks's Lambda is det E(F) / det E(R) = 0.1124.

Here we test the main effect of Noise (B). Because there is only a single D3D_3 variable for that effect, the matrices have one row and one column, their determinants are just the single numbers they contain, and the multivariate test collapses to a univariate one. A model comparison or a one-sample tt-test does the job.

HideShow
# Approach 1: Model Comparison (ANOVA)
D3_Model_Mean <- aov(D3 ~ 1, data=chapter_14_table_4)
D3_Model_Null <- aov(D3 ~ 0, data=chapter_14_table_4)
anova(D3_Model_Null, D3_Model_Mean)
HideShow
Analysis of Variance Table

Model 1: D3 ~ 0
Model 2: D3 ~ 1
  Res.Df    RSS Df Sum of Sq      F   Pr(>F)    
1     10 241200                                 
2      9  50760  1    190440 33.766 0.000256 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> RSS of 241,200 and 50,760 are E(R) = [241,200] and E(F) = [50,760] on p. 778,
#> and F = 33.77 — matches book p. 778.

# Approach 2: One-Sample t-test
t.test(
  x           = chapter_14_table_4$D3,
  mu          = 0,
  alternative = "two.sided",
  conf.level  = 0.95
)
HideShow

    One Sample t-test

data:  chapter_14_table_4$D3
t = 5.8108, df = 9, p-value = 0.000256
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
  84.27674 191.72326
sample estimates:
mean of x 
      138 
HideShow
#> t = 5.8108, and 5.8108^2 = 33.77 — matches the F on p. 778.

Testing the Angle ×\times Noise interaction requires testing D4D_4 and D5D_5 simultaneously, so we return to manova() and Equation 14.30 (p. 778).

HideShow
# Multivariate test for the Interaction
MANOVA_Interaction <- manova(cbind(D4, D5) ~ 1, data=chapter_14_table_4)
anova(MANOVA_Interaction, test="Wilks")
HideShow
Analysis of Variance Table

            Df    Wilks approx F num Df den Df    Pr(>F)    
(Intercept)  1 0.081777   44.914      2      8 4.472e-05 ***
Residuals    9                                              
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> approx F = 44.914 with 2 and 8 df, p = .00004 — matches book p. 778.

Alternatively, we can use the Anova() function from the car package (loaded above), which reports the same tests with Pillai’s trace as its default statistic. With a single group every multivariate criterion gives the same FF, so the two routes agree exactly.

HideShow
# Notice we use lm() instead of manova() when passing to car::Anova()
Model_A_lm <- lm(cbind(D1, D2) ~ 1, data=chapter_14_table_4)
Model_B_lm <- lm(D3 ~ 1, data=chapter_14_table_4)
Model_Int_lm <- lm(cbind(D4, D5) ~ 1, data=chapter_14_table_4)

Anova(Model_A_lm, type="III")
HideShow

Type III MANOVA Tests: Pillai test statistic
            Df test stat approx F num Df den Df    Pr(>F)    
(Intercept)  1    0.8876   31.586      2      8 0.0001596 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> approx F = 31.586 — matches book p. 778.
Anova(Model_B_lm, type="III")
HideShow
Anova Table (Type III tests)

Response: D3
            Sum Sq Df F value   Pr(>F)    
(Intercept) 190440  1  33.766 0.000256 ***
Residuals    50760  9                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 33.766 — matches book p. 778.
Anova(Model_Int_lm, type="III")
HideShow

Type III MANOVA Tests: Pillai test statistic
            Df test stat approx F num Df den Df    Pr(>F)    
(Intercept)  1   0.91822   44.914      2      8 4.472e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> approx F = 44.914 — matches book p. 778.

14.4 — Measures of Effect

As noted in the text, while the multivariate approach is recommended for hypothesis testing, the mixed-model formulation of omega squared (ω̂2\hat{\omega}^2) is still preferred for estimating effect sizes because it treats individual differences between subjects as a source of total variance, just as between-subjects designs do. Those components do not come from the DD variables; they come from the mixed-model analysis of Chapter 12, which we can fit here with aov() and an Error() stratum.

HideShow
# Long format, with Noise and Angle spelled out level by level.
chapter_14_table_4$Subject <- factor(seq_len(nrow(chapter_14_table_4)))

within_long <- chapter_14_table_4 |>
  select(Subject, Absent0:Present8) |>
  pivot_longer(Absent0:Present8, names_to = "cell", values_to = "Score") |>
  mutate(Noise = case_when(
    str_starts(cell, "Absent")  ~ "Absent",
    str_starts(cell, "Present") ~ "Present"
  )) |>
  mutate(Angle = case_when(
    str_ends(cell, "0") ~ "0",
    str_ends(cell, "4") ~ "4",
    str_ends(cell, "8") ~ "8"
  )) |>
  mutate(
    Noise = factor(Noise, levels = c("Absent", "Present")),
    Angle = factor(Angle, levels = c("0", "4", "8"))
  )

# The mixed-model (univariate) analysis of these same data: Angle is A, Noise is B.
within_aov <- aov(Score ~ Angle * Noise + Error(Subject / (Angle * Noise)),
                  data = within_long)
summary(within_aov)
HideShow

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

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

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

Error: Subject:Angle:Noise
            Df Sum Sq Mean Sq F value   Pr(>F)    
Angle:Noise  2 105120   52560   45.31 9.42e-08 ***
Residuals   18  20880    1160                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> A = 289,920 / 2 / 144,960 / F = 40.72;  A x S = 64,080 / 18 / 3,560
#> B = 285,660 / 1 / 285,660 / F = 33.77;  B x S = 76,140 /  9 / 8,460
#> A x B = 105,120 / 2 / 52,560 / F = 45.31;  A x B x S = 20,880 / 18 / 1,160
#> — matches Table 12.5 (p. 650). The subjects stratum gives SS_S = 292,140 and
#> MS_S = 32,460, the two extra values the book supplies on p. 779.

Equation 12.6, repeated on p. 779, is ω̂2=dfeffect(MSeffect−MSeffect×S)/(SSeffect+SSeffect×S+SSS+MSS)\hat{\omega}^2 = df_{\text{effect}}(MS_{\text{effect}} - MS_{\text{effect} \times S}) / (SS_{\text{effect}} + SS_{\text{effect} \times S} + SS_{S} + MS_{S}). Pulling the pieces out of the fitted object gives the book’s three values.

HideShow
within_sum <- summary(within_aov)

# Subjects stratum, whose single line is the subjects effect.
SS_S <- within_sum$`Error: Subject`[[1]][1, "Sum Sq"]
MS_S <- within_sum$`Error: Subject`[[1]][1, "Mean Sq"]
c(SS_S = SS_S, MS_S = MS_S)
HideShow
  SS_S   MS_S 
292140  32460 
HideShow
#> 292,140 and 32,460 — matches the values stated on p. 779.

# One stratum per within-subjects effect, each with its own effect x S error line.
omega_squared_within <- function(stratum, df_effect) {
  tab <- within_sum[[stratum]][[1]]
  eff <- 1L                       # the effect is the first row of its stratum
  err <- nrow(tab)                # the effect x S term is the Residuals row
  df_effect * (tab[eff, "Mean Sq"] - tab[err, "Mean Sq"]) /
    (tab[eff, "Sum Sq"] + tab[err, "Sum Sq"] + SS_S + MS_S)
}

c(
  Angle_A       = omega_squared_within("Error: Subject:Angle", df_effect = 2),
  Noise_B       = omega_squared_within("Error: Subject:Noise", df_effect = 1),
  Angle_x_Noise = omega_squared_within("Error: Subject:Angle:Noise", df_effect = 2)
)
HideShow
      Angle_A       Noise_B Angle_x_Noise 
    0.4167403     0.4038462     0.2281403 
HideShow
#> .42, .40, and .23 — matches the omega squared values on p. 779.
In DMAR: the sphericity-adjusted tests in one table

The mixed-model FF values above assume sphericity, which is exactly the assumption the multivariate approach of this chapter avoids. aov() does not report the Greenhouse–Geisser or Huynh–Feldt corrections, so a reader comparing the two approaches has to compute ε̂\hat{\varepsilon} separately. The DMAR function anova_within_two_way() reports the uncorrected test and the three adjusted versions together, along with partial η2\eta^2, from the same long data frame.

HideShow
anova_within_two_way(
  data     = as.data.frame(within_long),
  outcome  = "Score",
  factor_A = "Angle",
  factor_B = "Noise",
  subject  = "Subject"
)
effect adjustment F_value df_1 df_2 p_value epsilon eta_squared_partial
A none 40.719 2 18 < 0.0001 NA 0.819
A Greenhouse-Geisser 40.719 1.923 17.309 < 0.0001 0.962 0.819
A Huynh-Feldt 40.719 2 18 < 0.0001 1.000 0.819
A lower_bound 40.719 1 9 0.0001 0.500 0.819
B none 33.766 1 9 0.0003 NA 0.790
B Greenhouse-Geisser 33.766 1 9 0.0003 1.000 0.790
B Huynh-Feldt 33.766 1 9 0.0003 1.000 0.790
B lower_bound 33.766 1 9 0.0003 1.000 0.790
A:B none 45.310 2 18 < 0.0001 NA 0.834
A:B Greenhouse-Geisser 45.310 1.808 16.272 < 0.0001 0.904 0.834
A:B Huynh-Feldt 45.310 2 18 < 0.0001 1.000 0.834
A:B lower_bound 45.310 1 9 < 0.0001 0.500 0.834
HideShow
#> The "none" rows give F = 40.719 (A), 33.766 (B), and 45.310 (A:B), the same
#> values as the aov() output above and as Table 12.5 (p. 650). The adjusted
#> rows are what aov() does not provide.

The contrast with the multivariate tests of Section 14.3 is the point of the chapter: for the Noise main effect, which has 1 numerator degree of freedom, the two approaches agree exactly (F=33.77F = 33.77). For the Angle main effect and the interaction, which have 2, they do not (31.5931.59 versus 40.7240.72, and 44.9144.91 versus 45.3145.31), because the multivariate approach buys its freedom from the sphericity assumption with a different error structure.

With the effect sizes in hand, we follow up the significant omnibus tests with contrasts and simple effects.

14.4.1 — Further Investigation of Main Effects

Because the Angle main effect was significant and has three levels, we may want to test specific comparisons of its marginal means. In Section 14.3, we already created a D2D_2 variable that represents the quadratic trend of the Angle main effect.

We can test it individually by comparing it to a null model (where the intercept is 0).

HideShow
# Test the quadratic trend of Angle (D2)
D2_Model_Mean <- lm(D2 ~ 1, data=chapter_14_table_4)
D2_Model_Null <- lm(D2 ~ 0, data=chapter_14_table_4)
anova(D2_Model_Null, D2_Model_Mean)
HideShow
Analysis of Variance Table

Model 1: D2 ~ 0
Model 2: D2 ~ 1
  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1     10 100800                           
2      9  77760  1     23040 2.6667 0.1369
HideShow
#> F = 2.67 — matches book p. 779.

# The ingredients the book reports for this contrast on p. 779.
c(Dbar = mean(chapter_14_table_4$D2), s2 = var(chapter_14_table_4$D2))
HideShow
Dbar   s2 
 -48 8640 
HideShow
#> Dbar = -48 and s^2 = 8,640 — match p. 779, and 10(-48)^2 / 8,640 = 2.67.

# Critical value for a single planned comparison, 1 and n - 1 df.
qf(p = 1 - .05, df1 = 1, df2 = nrow(chapter_14_table_4) - 1)
HideShow
[1] 5.117355
HideShow
#> 5.12 — matches the critical value on p. 780, so the quadratic trend is
#> not statistically significant.

The observed FF of 2.67 is not statistically significant, and it is the same FF the mixed-model approach of Chapter 12 produces for the quadratic angle trend when a separate error term is used (p. 779).

14.4.2 — Further Investigation of an Interaction—Simple Effects

Because we found a significant Angle ×\times Noise interaction, the next logical step is to test simple effects. First, we will test the simple effect of Noise at each individual level of Angle (0, 4, and 8 degrees).

To do this, we create three new DD variables (D6D_6, D7D_7, and D8D_8), each representing the difference between Noise Present and Noise Absent at a specific angle.

HideShow
# Simple effects of Noise at specific Angles
chapter_14_table_4$D6 <- chapter_14_table_4$Present0 - chapter_14_table_4$Absent0
chapter_14_table_4$D7 <- chapter_14_table_4$Present4 - chapter_14_table_4$Absent4
chapter_14_table_4$D8 <- chapter_14_table_4$Present8 - chapter_14_table_4$Absent8 

# Test each simple effect of Noise
anova(lm(D6 ~ 0, data=chapter_14_table_4), lm(D6 ~ 1, data=chapter_14_table_4))
HideShow
Analysis of Variance Table

Model 1: D6 ~ 0
Model 2: D6 ~ 1
  Res.Df   RSS Df Sum of Sq      F Pr(>F)
1     10 61200                           
2      9 52200  1      9000 1.5517 0.2443
HideShow
#> F = 1.55 — matches book p. 781.
anova(lm(D7 ~ 0, data=chapter_14_table_4), lm(D7 ~ 1, data=chapter_14_table_4))
HideShow
Analysis of Variance Table

Model 1: D7 ~ 0
Model 2: D7 ~ 1
  Res.Df    RSS Df Sum of Sq      F   Pr(>F)   
1     10 327600                                
2      9 102600  1    225000 19.737 0.001617 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 19.74 — matches book p. 781.
anova(lm(D8 ~ 0, data=chapter_14_table_4), lm(D8 ~ 1, data=chapter_14_table_4))
HideShow
Analysis of Variance Table

Model 1: D8 ~ 0
Model 2: D8 ~ 1
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
1     10 586800                                  
2      9  39240  1    547560 125.59 1.376e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 125.59 — matches book p. 781.

The output matches the text: the effect of Noise at 0 degrees (F=1.55F = 1.55) is not significant, but the effect of Noise intensifies at 4 degrees (F=19.74F = 19.74) and 8 degrees (F=125.59F = 125.59), all three on p. 781.

Next, we test the simple effect of Angle at each individual level of Noise. Because Angle has three levels, we must form two DD variables for each noise condition. We will use linear and quadratic coefficients again, but this time we will not average across the Noise conditions.

HideShow
# Simple effect of Angle when Noise is absent
chapter_14_table_4$D9 <- -1*chapter_14_table_4$Absent0 + 0*chapter_14_table_4$Absent4 + 1*chapter_14_table_4$Absent8
chapter_14_table_4$D10 <- 1*chapter_14_table_4$Absent0 - 2*chapter_14_table_4$Absent4 + 1*chapter_14_table_4$Absent8

# Simple effect of Angle when Noise is present
chapter_14_table_4$D11 <- -1*chapter_14_table_4$Present0 + 0*chapter_14_table_4$Present4 + 1*chapter_14_table_4$Present8
chapter_14_table_4$D12 <- 1*chapter_14_table_4$Present0 - 2*chapter_14_table_4$Present4 + 1*chapter_14_table_4$Present8

We test these simple effects simultaneously using a multivariate approach with the Anova() function from the car package.

HideShow
# Test D9 and D10 simultaneously (Angle effect | Noise Absent)
MANOVA_D9D10_Full <- lm(cbind(D9, D10) ~ 1, data=chapter_14_table_4)
Anova(MANOVA_D9D10_Full, type="III")
HideShow

Type III MANOVA Tests: Pillai test statistic
            Df test stat approx F num Df den Df  Pr(>F)  
(Intercept)  1   0.64407   7.2381      2      8 0.01605 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> approx F = 7.238 with 2 and 8 df, p = .016 — matches book p. 781.

# Test D11 and D12 simultaneously (Angle effect | Noise Present)
MANOVA_D11D12_Full <- lm(cbind(D11, D12) ~ 1, data=chapter_14_table_4)
Anova(MANOVA_D11D12_Full, type="III")
HideShow

Type III MANOVA Tests: Pillai test statistic
            Df test stat approx F num Df den Df    Pr(>F)    
(Intercept)  1   0.91849   45.072      2      8 4.415e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> approx F = 45.072 with 2 and 8 df, p = .00004 — matches book p. 781.

These results confirm the textbook’s findings: there is a significant simple effect of Angle when Noise is absent (F=7.24F = 7.24) and a highly significant simple effect of Angle when Noise is present (F=45.07F = 45.07), both on p. 781.

Having found a significant simple effect of Angle in each noise condition, the book goes one step further and tests the two DD variables for Noise Absent individually, which is how the nature of that simple effect is identified.

HideShow
# The individual cell mean comparisons within Noise Absent.
anova(lm(D9 ~ 0, data=chapter_14_table_4), lm(D9 ~ 1, data=chapter_14_table_4))
HideShow
Analysis of Variance Table

Model 1: D9 ~ 0
Model 2: D9 ~ 1
  Res.Df   RSS Df Sum of Sq      F   Pr(>F)   
1     10 75600                                
2      9 32040  1     43560 12.236 0.006745 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 12.24 for the linear trend of Angle when Noise is absent — matches p. 782.
anova(lm(D10 ~ 0, data=chapter_14_table_4), lm(D10 ~ 1, data=chapter_14_table_4))
HideShow
Analysis of Variance Table

Model 1: D10 ~ 0
Model 2: D10 ~ 1
  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1     10 162000                           
2      9 153000  1      9000 0.5294 0.4854
HideShow
#> F = 0.53 for the quadratic trend of Angle when Noise is absent — matches p. 782.
14.4.3 — Interaction Contrasts

An alternative to testing simple effects is to test interaction contrasts. The omnibus interaction is represented collectively by D4D_4 and D5D_5 (which we created in Section 14.3).

  • D4D_4 represents the interaction of Noise with the linear trend of Angle.

  • D5D_5 represents the interaction of Noise with the quadratic trend of Angle.

We can test these 1-degree-of-freedom interaction contrasts individually to see exactly what is driving the omnibus interaction.

HideShow
# Test Interaction Contrast: Noise x Linear trend of Angle (D4)
anova(lm(D4 ~ 0, data=chapter_14_table_4), lm(D4 ~ 1, data=chapter_14_table_4))
HideShow
Analysis of Variance Table

Model 1: D4 ~ 0
Model 2: D4 ~ 1
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
1     10 460800                                  
2      9  44640  1    416160 83.903 7.391e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 83.90 — matches book p. 782.

# Test Interaction Contrast: Noise x Quadratic trend of Angle (D5)
anova(lm(D5 ~ 0, data=chapter_14_table_4), lm(D5 ~ 1, data=chapter_14_table_4))
HideShow
Analysis of Variance Table

Model 1: D5 ~ 0
Model 2: D5 ~ 1
  Res.Df    RSS Df Sum of Sq  F Pr(>F)
1     10 129600                       
2      9 116640  1     12960  1 0.3434
HideShow
#> F = 1.00 — matches book p. 782.

As the text reports on p. 782, the interaction contrast for D4D_4 is highly significant (F=83.90F = 83.90), while D5D_5 is not (F=1.00F = 1.00). This indicates that the Noise effect grows stronger in a linear fashion as the angle deviates further from 0 degrees.

14.5 — Confidence Intervals for Contrasts

Just as in the one-way within-subjects design, we can form confidence intervals for contrasts in the two-way design using the general formula:

D‾±(CV)(seD‾)\bar{D} \pm (\sqrt{CV})(se_{\bar{D}})

Where CVCV is the critical value (which changes depending on whether the contrast is uncorrected, a planned Bonferroni, or a post hoc Roy-Bose/Scheffé) and seD‾se_{\bar{D}} is the standard error of the mean of the DD variable.

Because most statistical software only outputs uncorrected confidence intervals by default, we often need to calculate the adjusted critical values ourselves to control the familywise alpha level. Below we define the parameters of the design as the book does (n=10n = 10; Angle is AA with a=3a = 3 levels; Noise is BB with b=2b = 2 levels) and calculate the critical values for uncorrected, Bonferroni-adjusted, and post hoc tests.

Critical values for main-effect contrasts

Uncorrected critical values. With a per-comparison alpha level, the critical value for a single DD variable is read from the FF distribution with 1 and n−1n - 1 degrees of freedom (p. 780).

HideShow
n <- nrow(chapter_14_table_4)
a <- 3  # Angle, the A factor
b <- 2  # Noise, the B factor
alpha_FW <- .05

# A single planned comparison of either factor's marginal means.
CV_Single_Comparison <- qf(p = 1 - alpha_FW, df1 = 1, df2 = n - 1)
CV_Single_Comparison
HideShow
[1] 5.117355
HideShow
#> 5.12 — the critical value used on pp. 780 and 782.

Bonferroni adjusted critical values.

If a set of CC planned comparisons is tested, each contrast is tested at αFW/C\alpha_{FW} / C (p. 780). The Angle factor has a−1=2a - 1 = 2 degrees of freedom, so testing both its linear and quadratic trends as planned comparisons means C=2C = 2; the Noise factor has only b−1=1b - 1 = 1 degree of freedom, so C=1C = 1 there.

HideShow
# Number of planned contrasts within each factor (family)
C_for_A_Factor <- 2
C_for_B_Factor <- 1

CV_A_Factor_Bonferroni <- qf(p = 1 - alpha_FW/C_for_A_Factor, df1 = 1, df2 = n - 1)
CV_B_Factor_Bonferroni <- qf(p = 1 - alpha_FW/C_for_B_Factor, df1 = 1, df2 = n - 1)

CV_A_Factor_Bonferroni
HideShow
[1] 7.209283
HideShow
CV_B_Factor_Bonferroni
HideShow
[1] 5.117355

Dividing the familywise alpha level by the number of planned contrasts raises the critical value for the Angle family from 5.12 to 7.21. With a single planned contrast (C=1C = 1), as for Noise, αFW/C\alpha_{FW}/C is just .05.05, so the Bonferroni and uncorrected critical values coincide.

Roy–Bose (multivariate Scheffé) critical values.

For post hoc complex comparisons in a multivariate design, the text gives the Roy–Bose critical value in Equation 14.31 for contrasts of the AA marginal means and Equation 14.32 for contrasts of the BB marginal means (p. 780). This is the most conservative adjustment.

HideShow
CV_A_Factor_Scheffe <- (n-1)*(a-1)*qf(p=1-alpha_FW, df1=a-1, df2=n-a+1)/(n-a+1)
CV_B_Factor_Scheffe <- (n-1)*(b-1)*qf(p=1-alpha_FW, df1=b-1, df2=n-b+1)/(n-b+1)

CV_A_Factor_Scheffe   # Angle: Equation 14.31
HideShow
[1] 10.03268
HideShow
CV_B_Factor_Scheffe   # Noise: Equation 14.32
HideShow
[1] 5.117355

Tested post hoc, the quadratic trend of Angle would be compared against 10.03 rather than 5.12, so the conclusion of Section 14.4.1 does not change. For the Noise factor, which contributes a single DD variable, the Roy–Bose value reduces to the uncorrected 5.12, as it must.

Critical values for interaction contrasts

The general form for these critical values applies to interactions as well, using the interaction degrees of freedom dfeffect=(a−1)(b−1)df_{effect} = (a-1)(b-1), which is the general expression of Equation 14.34 (p. 782).

HideShow
# Omnibus degrees of freedom for the interaction
df_interaction <- (a-1)*(b-1)

# A single planned interaction contrast is still a 1 df test.
qf(p = 1 - alpha_FW, df1 = 1, df2 = n - 1)
HideShow
[1] 5.117355
HideShow
#> 5.12 — the value the book uses for D4 and D5 on p. 782.

# Bonferroni, with C = (a - 1)(b - 1) = 2 planned interaction contrasts
C_Interaction_Contrasts <- df_interaction
CV_Interaction_Bonferroni <- qf(p=1-alpha_FW/C_Interaction_Contrasts, df1=1, df2=n-1)
CV_Interaction_Bonferroni
HideShow
[1] 7.209283
HideShow
# Roy-Bose (Scheffe) Post Hoc Interaction CV (Equations 14.33 and 14.34)
CV_Interaction_Scheffe <- (n-1)*df_interaction*qf(p=1-alpha_FW, df1=df_interaction, df2=n-df_interaction)/(n-df_interaction)
CV_Interaction_Scheffe
HideShow
[1] 10.03268

The observed FF of 83.90 for D4D_4 exceeds even the post hoc critical value of 10.03, while the observed FF of 1.00 for D5D_5 falls short of the uncorrected 5.12 — which is exactly what the book concludes on p. 782.

Reproducing Table 14.6: estimates and standard errors

Now that we have the mathematical framework for our critical values, we need the sample estimates (D‾\bar{D}) and the standard errors (seD‾se_{\bar{D}}). The textbook explores four specific contrasts in Table 14.6 (p. 784):

  • D1: Angle Linear (Main Effect)

  • D9: Angle Linear (Simple Effect: Noise Absent)

  • D11: Angle Linear (Simple Effect: Noise Present)

  • Interaction Contrast: The difference between the two simple effects (D11 - D9)

By fitting intercept-only models in R, we can extract these values. The default confint() method provides the uncorrected 95% confidence intervals, which is what the book’s Table 14.6 reports: in all four cases 95% confidence pertains to a single comparison rather than a collection of them.

HideShow
# Create the specific Interaction Contrast variable from Table 14.6
chapter_14_table_4$NA_NP_0_8 <- chapter_14_table_4$D11 - chapter_14_table_4$D9

# Fit intercept-only models for each contrast
model_D1 <- lm(D1 ~ 1, data=chapter_14_table_4)
model_D9 <- lm(D9 ~ 1, data=chapter_14_table_4)
model_D11 <- lm(D11 ~ 1, data=chapter_14_table_4)
model_Interaction <- lm(NA_NP_0_8 ~ 1, data=chapter_14_table_4)

# Combine Estimates, Standard Errors, and Uncorrected 95% Confidence Intervals
results_table <- data.frame(
  Contrast = c("D1 (Angle Linear Main)", "D9 (Angle Linear | Noise Absent)",
               "D11 (Angle Linear | Noise Present)", "Interaction (D11 - D9)"),
  Estimate = c(coef(model_D1), coef(model_D9), coef(model_D11), coef(model_Interaction)),
  Std_Error = c(summary(model_D1)$coefficients[1, 2], summary(model_D9)$coefficients[1, 2],
                summary(model_D11)$coefficients[1, 2], summary(model_Interaction)$coefficients[1, 2]),
  Lower_95_Uncorrected = c(confint(model_D1)[1], confint(model_D9)[1], confint(model_D11)[1], confint(model_Interaction)[1]),
  Upper_95_Uncorrected = c(confint(model_D1)[2], confint(model_D9)[2], confint(model_D11)[2], confint(model_Interaction)[2])
)

results_table |>
  gt() |>
  fmt_number(columns = -Contrast, decimals = 3) |>
  cols_label(
    Std_Error            = "Std. Error",
    Lower_95_Uncorrected = "Lower 95%",
    Upper_95_Uncorrected = "Upper 95%"
  ) |>
  tab_header(title = md("Confidence intervals for four contrasts in the reaction time data")) |>
  cols_align(align = "center", columns = -Contrast)
Confidence intervals for four contrasts in the reaction time data
Contrast Estimate Std. Error Lower 95% Upper 95%
D1 (Angle Linear Main) 168.000 20.591 121.419 214.581
D9 (Angle Linear | Noise Absent) 66.000 18.868 23.318 108.682
D11 (Angle Linear | Noise Present) 270.000 27.203 208.463 331.537
Interaction (D11 - D9) 204.000 22.271 153.619 254.381
HideShow
#> D1:        168.000, se 20.591, [121.419, 214.581] — matches Table 14.6 (p. 784).
#> D9:         66.000, se 18.868, [ 23.318, 108.682] — matches Table 14.6 (p. 784).
#> D11:       270.000, se 27.203, [208.463, 331.537] — matches Table 14.6 (p. 784).
#> NA_NP_0_8: 204.000, se 22.271, [153.619, 254.381] — matches Table 14.6 (p. 784).

As the book points out (p. 784), the mean of the interaction contrast is exactly the difference between the means of D11D_{11} and D9D_9: 270−66=204270 - 66 = 204. To widen any of these intervals for multiple comparisons, multiply the standard error by the square root of one of the critical values computed above instead of by the tt quantile confint() uses.

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

14.6.1 — Split-Plot Design with Two Levels of the Within-Subjects Factor

A split-plot design (often referred to as a mixed ANOVA) contains both a between-subjects factor and a within-subjects factor.

To illustrate the multivariate approach to this design, we will revisit the perceptual psychology example from Chapter 12: * Between-Subjects Factor (A): Age (Young vs. Old) * Within-Subjects Factor (B): Angle (0° and 8°)

To keep things simple initially, we are only looking at two levels of the within-subjects factor (0° and 8°). Let’s load and format the data of Table 14.7 (p. 786).

HideShow
data(chapter_14_table_7)

# Spell out the Age factor level by level, then set the level order.
chapter_14_table_7 <- chapter_14_table_7 |>
  mutate(Age = case_when(
    Group == 1 ~ "Young",
    Group == 2 ~ "Old"
  )) |>
  mutate(Age = factor(Age, levels = c("Young", "Old")))

head(chapter_14_table_7)
HideShow
  Angle0 Angle8 Group   Age
1    450    630     1 Young
2    390    540     1 Young
3    570    660     1 Young
4    450    720     1 Young
5    510    630     1 Young
6    360    450     1 Young
HideShow
# Cell means, to check the data against the book.
chapter_14_table_7 |>
  group_by(Age) |>
  summarize(Angle0 = mean(Angle0), Angle8 = mean(Angle8))
HideShow
# A tibble: 2 × 3
  Age   Angle0 Angle8
  <fct>  <dbl>  <dbl>
1 Young    477    645
2 Old      543    792
HideShow
#> Young 477 and 645; Old 543 and 792 — matches the Mean rows of Table 14.7 (p. 786).

In any two-factor design, we have three omnibus effects to test:

  1. The main effect of Age (Between-Subjects)

  2. The main effect of Angle (Within-Subjects)

  3. The Age ×\times Angle interaction (Within-Subjects)

14.6.2 — Main Effect of Between-Subjects Factor

To test the main effect of our between-subjects factor (Age), we need to average over the within-subjects factor. We do this by creating a new transformed variable, MM, which is simply the average of the 0° and 8° scores for each participant (Equation 14.37, p. 787).

Mij=(Y1ij+Y2ij)/2M_{ij} = (Y_{1ij} + Y_{2ij}) / 2 Once we compute MM for every participant, testing the main effect of Age is identical to conducting a standard one-way between-subjects ANOVA with MM as the dependent variable, which is Equation 14.40 (p. 787).

HideShow
# Create the M variable (Average of the two angles)
chapter_14_table_7$M <- (chapter_14_table_7$Angle0 + chapter_14_table_7$Angle8) / 2

# Group means on M, the marginal means the test compares.
tapply(chapter_14_table_7$M, chapter_14_table_7$Age, mean)
HideShow
Young   Old 
561.0 667.5 
HideShow
#> 561 and 667.5 — matches the Mean rows of Table 14.8 (p. 788).

# Test the main effect of Age using a one-way ANOVA on M
anova_age_main <- aov(M ~ Age, data = chapter_14_table_7)
summary(anova_age_main)
HideShow
            Df Sum Sq Mean Sq F value  Pr(>F)   
Age          1  56711   56711   9.242 0.00704 **
Residuals   18 110452    6136                   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Residual SS = 110,452.5, the denominator sum the book reports on p. 788, and
#> F = 9.242 with 1 and 18 df, p = .007 — matches book p. 788.

The output gives us an FF value of 9.24 and a pp value of .007. The main effect of Age is statistically significant. Averaging across the angles, older participants have significantly slower reaction times than younger participants.

The same one-way ANOVA on MM as an APA-style table, with sums of squares, df, F, p, and partial η2\eta^2. (apaTables::apa.aov.table() produces only plain text that reads no better than base R in HTML, so the table is built with gt, which formats it properly.)

HideShow
age_tbl <- broom::tidy(anova_age_main)
ss_res  <- age_tbl$sumsq[age_tbl$term == "Residuals"]   # error SS, for eta^2
age_tbl |>
  transmute(
    Source = if_else(term == "Age", "Age", "Within (S/A)"),
    SS = sumsq, df = df, MS = meansq,
    Fstat = statistic, p = p.value,
    # Partial eta-squared: the effect's share of effect-plus-error variance.
    peta  = if_else(term == "Residuals", NA_real_, sumsq / (sumsq + ss_res))
  ) |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("Analysis of variance for the Age main effect (marginal mean *M*)")) |>
  cols_align(align = "center", columns = -Source)
Analysis of variance for the Age main effect (marginal mean M)
Source SS df MS F p Partial η2
Age 56,711.25 1 56,711.25 9.24 0.0070 0.339
Within (S/A) 110,452.50 18 6,136.25


14.6.3 — Within-Subjects Effects

The remaining two effects (Angle main effect and Age ×\times Angle interaction) both involve the difference between the 0° and 8° conditions. To test these, we create another transformed variable, DD, representing the difference score for each participant (Equation 14.41, p. 788).

Dij=Y2ij−Y1ijD_{ij} = Y_{2ij} - Y_{1ij}

HideShow
# Create the D variable (Difference between 8° and 0°)
chapter_14_table_7$D <- chapter_14_table_7$Angle8 - chapter_14_table_7$Angle0

# Displaying M and D to mirror Table 14.8
chapter_14_table_7[, c("Age", "M", "D")]
HideShow
     Age   M   D
1  Young 540 180
2  Young 465 150
3  Young 615  90
4  Young 585 270
5  Young 570 120
6  Young 405  90
7  Young 615 210
8  Young 645 270
9  Young 585 150
10 Young 585 150
11   Old 555 270
12   Old 705 210
13   Old 570 240
14   Old 705 150
15   Old 600 360
16   Old 735 270
17   Old 750 240
18   Old 600 240
19   Old 795 210
20   Old 660 300
HideShow
# Group means on D.
tapply(chapter_14_table_7$D, chapter_14_table_7$Age, mean)
HideShow
Young   Old 
  168   249 
HideShow
#> 168 and 249 — matches the Mean rows of Table 14.8 (p. 788).

Notice that every participant has a positive DD score, meaning everyone was slower at 8° than at 0°. Also notice that the DD scores seem generally larger for the Old group than the Young group.

14.6.4 — Test of the Interaction

The Age ×\times Angle interaction tests whether the effect of Angle (our DD variable) differs depending on Age. If there is no interaction, the mean DD score should be the same for both Young and Old participants.

We can test this by running a standard one-way ANOVA on the DD variable.

HideShow
# Test the interaction by running an ANOVA on the difference score (D)
# This is Equation 14.44 (p. 789).
anova_interaction <- aov(D ~ Age, data = chapter_14_table_7)
summary(anova_interaction)
HideShow
            Df Sum Sq Mean Sq F value  Pr(>F)   
Age          1  32805   32805   8.807 0.00825 **
Residuals   18  67050    3725                   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Residual SS = 67,050, the denominator sum reported on p. 790, and F = 8.807
#> with 1 and 18 df, p = .008 — matches book p. 790.

The FF value is 8.81 with a pp value of .008. The interaction is statistically significant. The angle effect is significantly stronger for older participants (D‾2=249\bar{D}_2 = 249) than for younger ones (D‾1=168\bar{D}_1 = 168), as the book notes on p. 790.

14.6.5 — Within-Subjects Main Effect

The final test is the main effect of Angle. This tests whether the grand mean of DD (D‾\bar{D}) is significantly different from zero, averaging across Age.

The book proves that the FF statistic for this main effect can be calculated by comparing the sum of squares for the angle main effect (ND‾2N\bar{D}^2, Equation 14.47, p. 791) to the error term from our full model (which happens to be the exact same error term used in the interaction test above).

Let’s compute this exactly as Equation 14.48 (p. 792) defines it:

HideShow
# Calculate N, a, and grand mean of D
N <- nrow(chapter_14_table_7)
a <- length(levels(chapter_14_table_7$Age))
D_bar <- mean(chapter_14_table_7$D)

# Extract the Sum of Squared Errors from our previous interaction model
# This is the denominator sum of squares: sum((Dij - Dj_bar)^2)
SS_error <- sum(resid(anova_interaction)^2)
df_error <- N - a
MS_error <- SS_error / df_error

# Calculate the Sum of Squares for the Angle Main Effect
SS_angle <- N * (D_bar^2)

# Compute the F-statistic
F_angle <- SS_angle / MS_error

# Compute the p-value
p_angle <- pf(F_angle, df1 = 1, df2 = df_error, lower.tail = FALSE)

# Display results
cat("Sum of Squares (Angle):", SS_angle,
    "\nF-statistic:", F_angle,
    "\np-value:", p_angle, "\n")
HideShow
Sum of Squares (Angle): 869445 
F-statistic: 233.4081 
p-value: 9.479516e-12 
HideShow
#> Dbar = 208.5 and SS = 869,445 — match p. 791; F = 233.41 with 1 and 18 df
#> — matches book p. 792.

The by-hand calculation gives us an FF value of 233.41, matching the text. Participants responded significantly more slowly in the 8° condition compared to the 0° condition.

Notice a structural detail here: the error term for the within-subjects main effect is identical to the error term for the interaction. Both tests use the full-model variance of the DD scores as their denominator, because both use Equation 14.42 as the full model (p. 792).

While the by-hand calculation makes the algebra visible, we can bypass it entirely in practice. Because the Angle main effect tests if the grand mean of DD is zero, we can extract this directly from the (Intercept) of a linear model predicting DD.

However, by default, R uses dummy coding, meaning the intercept tests the mean of the reference group (e.g., Young participants). To test the grand mean, we must change the Age factor to use sum-to-zero contrasts (effect coding).

HideShow
# Change the contrast coding for Age to sum-to-zero
contrasts(chapter_14_table_7$Age) <- contr.sum

# Fit the linear model predicting the Difference score (D) by Age
model_D <- lm(D ~ Age, data = chapter_14_table_7)

# Use car's Anova() (loaded above) to get Type III Sums of Squares
Anova(model_D, type = 3)
HideShow
Anova Table (Type III tests)

Response: D
            Sum Sq Df  F value   Pr(>F)    
(Intercept) 869445  1 233.4081 9.48e-12 ***
Age          32805  1   8.8067 0.008246 ** 
Residuals    67050 18                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> (Intercept) SS = 869,445 — matches book p. 791; F = 233.41 — matches p. 792.
#> Age F = 8.81 — matches book p. 790.

In the output above, the (Intercept) row gives us an FF value of 233.41, which matches the by-hand calculation for the Angle main effect. Additionally, the Age row gives us an FF value of 8.81, which matches the earlier test for the Age ×\times Angle interaction.

This single lm(D ~ Age) model therefore carries both within-subjects effects: its intercept is the grand mean of DD (the Angle main effect) and its Age coefficient is the between-group difference in DD (the Age ×\times Angle interaction). A publication-quality table makes those two pieces easy to read. With modelsummary (the estimate with its standard error beneath, fit statistics at the foot):

HideShow
modelsummary(
  list("D = Angle8 - Angle0" = model_D),
  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
)
D = Angle8 - Angle0
(Intercept) 208.500
(13.647)
Age1 -40.500
(13.647)
Num.Obs. 20
AIC 225.1
BIC 228.1
Log.Lik. -109.553
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

The same model as a gtsummary tbl_regression() table, with the intercept shown so the Angle main effect is visible:

HideShow
tbl_regression(model_D, intercept = TRUE) |>
  modify_caption("**Regression of the difference score *D* on Age**")
Regression of the difference score D on Age
Characteristic Beta 95% CI p-value
(Intercept) 209 180, 237 <0.001
Age


    Young -41 -69, -12 0.008
    Old — —
Abbreviation: CI = Confidence Interval
In DMAR: all three split-plot effects in one table

We assembled the three split-plot effects above by hand: an ANOVA on the marginal mean MM for the between-subjects factor, an ANOVA on the difference score DD for the interaction, and an intercept (or by-hand) test for the within-subjects main effect. The DMAR function manova_split_plot() packages this as a single call: it takes the wide data, the names of the within-subjects columns, and the name of the between-subjects factor, and returns the four classical multivariate test statistics (Wilks’s Lambda, Pillai’s trace, Hotelling-Lawley, and Roy’s largest root) for the between-subjects effect (A), the within-subjects effect (B), and their interaction, all in one table.

HideShow
# DMAR is loaded above. Build the wide two-level split-plot data, spelling
# out the between-subjects factor level by level.
mix <- chapter_14_table_7 |>
  as_tibble() |>
  mutate(Age = case_when(
    Group == 1 ~ "Young",
    Group == 2 ~ "Old"
  )) |>
  mutate(Age = factor(Age, levels = c("Young", "Old")))

split_plot_tests <- manova_split_plot(
  data    = mix,
  within  = c("Angle0", "Angle8"),
  between = "Age",
  ss_type = 3
)

# The returned data frame carries the sums-of-squares type as a final row
# rather than as an attribute, so we keep only the rows that are tests.
subset(split_plot_tests, effect != "sum_of_squares_type")
effect statistic_name statistic_value F_approx df_1 df_2 p_value
A Pillai 0.339 9.242 1 18 0.0070
A Wilks 0.661 9.242 1 18 0.0070
A Hotelling-Lawley 0.513 9.242 1 18 0.0070
A Roy 0.513 9.242 1 18 0.0070
B Pillai 0.928 233.408 1 18 < 0.0001
B Wilks 0.072 233.408 1 18 < 0.0001
B Hotelling-Lawley 12.967 233.408 1 18 < 0.0001
B Roy 12.967 233.408 1 18 < 0.0001
interaction Pillai 0.329 8.807 1 18 0.0082
interaction Wilks 0.671 8.807 1 18 0.0082
interaction Hotelling-Lawley 0.489 8.807 1 18 0.0082
interaction Roy 0.489 8.807 1 18 0.0082

Sum of squares: Type III

HideShow
#> A (Age) F = 9.24 matches book p. 788; B (Angle) F = 233.41 matches
#> p. 792 (Equation 14.48); interaction F = 8.81 matches p. 790.

Because the within-subjects factor here has only two levels, s=1s = 1 and the four multivariate statistics all yield the same FF. The A rows reproduce the Age main effect (F=9.24F = 9.24, book p. 788), the B rows reproduce the Angle main effect of Equation 14.48 (F=233.41F = 233.41, p. 792, the value of the by-hand computation above), and the interaction rows reproduce the Age ×\times Angle interaction (F=8.81F = 8.81, p. 790). With equal group sizes, as here, the Type III test that ss_type = 3 asks for and the Type II test agree; with unequal sizes, the Type III test is the test of the unweighted mean of the difference scores, which the book prefers (Chapter 14, note 6, p. 854).

14.6.7 — General a×ba \times b Split-Plot Design

The principles we just used for a design with two within-subjects levels apply when there are more levels, but the analysis becomes truly multivariate. When we only had 0° and 8° conditions, we could get away with a single difference variable (DD). Now we reinstate the 4° condition so that our Angle factor has three levels, giving a design with a=2a = 2 levels of the between-subjects factor and b=3b = 3 levels of the within-subjects factor.

Because our within-subjects factor now has b=3b = 3 levels, we will need to form b−1b - 1 (or 2) DD variables to capture the within-subjects effects, requiring us to test them simultaneously using matrices.

Let’s load the data of Table 14.9 (p. 794).

HideShow
data(chapter_14_table_9)

# Spell out the Age factor level by level, then set the level order.
chapter_14_table_9 <- chapter_14_table_9 |>
  mutate(Age = case_when(
    Group == 1 ~ "Young",
    Group == 2 ~ "Old"
  )) |>
  mutate(Age = factor(Age, levels = c("Young", "Old")))

head(chapter_14_table_9)
HideShow
  Angle0 Angle4 Angle8 Group   Age
1    450    510    630     1 Young
2    390    480    540     1 Young
3    570    630    660     1 Young
4    450    660    720     1 Young
5    510    660    630     1 Young
6    360    450    450     1 Young
HideShow
# Cell means, to check the data against the book.
chapter_14_table_9 |>
  group_by(Age) |>
  summarize(across(Angle0:Angle8, mean))
HideShow
# A tibble: 2 × 4
  Age   Angle0 Angle4 Angle8
  <fct>  <dbl>  <dbl>  <dbl>
1 Young    477    585    645
2 Old      543    654    792
HideShow
#> Young 477, 585, 645; Old 543, 654, 792 — matches the Mean rows of
#> Table 14.9 (p. 794).
14.6.8 — Between-Subjects Main Effect

Just like before, to test the main effect of Age, we collapse across the repeated measures. Regardless of how many within-subjects levels there are, we always form exactly one MM variable representing each participant’s overall mean score:

Mij=(Y1ij+Y2ij+Y3ij)/3M_{ij} = (Y_{1ij} + Y_{2ij} + Y_{3ij}) / 3

HideShow
# Compute M (Mean across all three angles); Equation 14.49, p. 793.
chapter_14_table_9$M <- (chapter_14_table_9$Angle0 + chapter_14_table_9$Angle4 + chapter_14_table_9$Angle8) / 3

# Group means and grand mean on M.
c(tapply(chapter_14_table_9$M, chapter_14_table_9$Age, mean),
  Grand = mean(chapter_14_table_9$M))
HideShow
Young   Old Grand 
  569   663   616 
HideShow
#> 569, 663, and 616 — matches the Group Mean and Grand Mean rows of
#> Table 14.10 (p. 795).

# Test the Age Main Effect using a one-way ANOVA on M
anova_age_main_3 <- aov(M ~ Age, data = chapter_14_table_9)
summary(anova_age_main_3)
HideShow
            Df Sum Sq Mean Sq F value Pr(>F)  
Age          1  44180   44180   7.276 0.0147 *
Residuals   18 109300    6072                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 7.276 with 1 and 18 df, p = .0147 — matches book p. 794.

The output gives us an FF value of 7.28 and a pp value of .0147, indicating a statistically significant main effect of Age. This is the same FF value the mixed-model (univariate) approach of Chapter 12 produces, as the book notes on p. 795. Because testing the between-subjects effect involves averaging over the within-subjects factor (bypassing sphericity concerns), the multivariate and univariate approaches are mathematically identical here.

14.6.9 — Within-Subjects Effects

To test the within-subjects effects (Angle main effect and Age ×\times Angle interaction), we must form b−1b - 1 difference variables. Since Angle is a quantitative factor with 3 levels, it is highly logical to use orthogonal polynomial contrasts:

  • D1 (Linear Trend): −1(0∘)+0(4∘)+1(8∘)-1(0^\circ) + 0(4^\circ) + 1(8^\circ)

  • D2 (Quadratic Trend): 1(0∘)−2(4∘)+1(8∘)1(0^\circ) - 2(4^\circ) + 1(8^\circ)

HideShow
# Create D1 (Linear) and D2 (Quadratic)
chapter_14_table_9$D1 <- -1*chapter_14_table_9$Angle0 + 0*chapter_14_table_9$Angle4 + 1*chapter_14_table_9$Angle8
chapter_14_table_9$D2 <-  1*chapter_14_table_9$Angle0 - 2*chapter_14_table_9$Angle4 + 1*chapter_14_table_9$Angle8

# Display M, D1, and D2 to mirror Table 14.10
head(chapter_14_table_9[, c("Age", "M", "D1", "D2")])
HideShow
    Age   M  D1   D2
1 Young 530 180   60
2 Young 470 150  -30
3 Young 620  90  -30
4 Young 610 270 -150
5 Young 600 120 -180
6 Young 420  90  -90
HideShow
# Group means and grand means on the two D variables.
rbind(
  tapply(chapter_14_table_9$D1, chapter_14_table_9$Age, mean),
  tapply(chapter_14_table_9$D2, chapter_14_table_9$Age, mean)
)
HideShow
     Young Old
[1,]   168 249
[2,]   -48  27
HideShow
c(D1_grand = mean(chapter_14_table_9$D1), D2_grand = mean(chapter_14_table_9$D2))
HideShow
D1_grand D2_grand 
   208.5    -10.5 
HideShow
#> D1: 168 (Young), 249 (Old), grand 208.5; D2: -48, 27, grand -10.5
#> — matches Table 14.10 (p. 795).
14.6.10 — Within-Subjects Main Effect

The null hypothesis for the Angle main effect states that the grand means of both D1D1 and D2D2 equal zero simultaneously. Because we have multiple DD variables, we can no longer use simple sums of squares; we must compute matrices representing the Sum of Squares and Cross-Products (SSCP).

We need two matrices:E(F)E(F) (Full Model Matrix):

  1. The error matrix capturing how much participants deviate from their own group means on D1D1 and D2D2.

  2. E(R)E(R) (Restricted Model Matrix): The error matrix capturing how much participants deviate from the grand mean assumption (where the true grand mean is hypothesized to be zero).

The code below constructs these matrices directly from the definitions on pp. 797–798.

HideShow
# Extract Group Means and Grand Means for D1 and D2
D1_grand <- mean(chapter_14_table_9$D1)
D2_grand <- mean(chapter_14_table_9$D2)

# Calculate the Full Model Error Matrix E(F)
# e(F) = Participant Score - Group Mean
e1_F <- chapter_14_table_9$D1 - ave(chapter_14_table_9$D1, chapter_14_table_9$Age)
e2_F <- chapter_14_table_9$D2 - ave(chapter_14_table_9$D2, chapter_14_table_9$Age)

# Crossprod creates the SSCP matrix: Sum of squares on diagonal, cross-products off-diagonal
E_F <- crossprod(cbind(e1_F, e2_F))
rownames(E_F) <- colnames(E_F) <- c("D1", "D2")

# Full Model Matrix E(F)
print(E_F)
HideShow
      D1     D2
D1 67050  -9090
D2 -9090 125370
HideShow
#> 67,050 and 125,370 on the diagonal, -9,090 off it — matches E(F) on p. 797.

# Calculate the Restricted Model Matrix E(R)
# The text establishes a shortcut formula: E(R) = E(F) + N * (Grand Mean Matrix)
N <- nrow(chapter_14_table_9)
E_R <- matrix(c(
  E_F[1,1] + N * (D1_grand^2),             # E11(R)
  E_F[1,2] + N * (D1_grand * D2_grand),    # E12(R)
  E_F[2,1] + N * (D1_grand * D2_grand),    # E21(R)
  E_F[2,2] + N * (D2_grand^2)              # E22(R)
), nrow=2)
rownames(E_R) <- colnames(E_R) <- c("D1", "D2")

# Restricted Model Matrix E(R)
print(E_R)
HideShow
       D1     D2
D1 936495 -52875
D2 -52875 127575
HideShow
#> 936,495 and 127,575 on the diagonal, -52,875 off it — matches E(R) on p. 798.

Both matrices match the text. To conduct the statistical test, we compare the “volume” of these matrices using their determinants. The formula for the test statistic (Equation 14.54, p. 798) is:

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

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

cat("Determinant of E(F):", format(det_EF, scientific=FALSE), "\n")
HideShow
Determinant of E(F): 8323430400 
HideShow
cat("Determinant of E(R):", format(det_ER, scientific=FALSE), "\n")
HideShow
Determinant of E(R): 116677584000 
HideShow
# Compute the F-statistic
a <- length(levels(chapter_14_table_9$Age)) # 2 levels of Age
b <- 3 # 3 angles

df_num <- b - 1
df_den <- N - a - b + 2

F_angle_multiv <- ((det_ER - det_EF) / df_num) / (det_EF / df_den)
p_angle_multiv <- pf(F_angle_multiv, df1 = df_num, df2 = df_den, lower.tail = FALSE)

cat(
  "\nAngle Main Effect (Multivariate F):\n",
  "F(", df_num, ", ", df_den, ") = ", F_angle_multiv, "\n",
  "p-value = ", p_angle_multiv, "\n",
  sep = ""
)
HideShow

Angle Main Effect (Multivariate F):
F(2, 17) = 110.6527
p-value = 1.791335e-10
HideShow
#> |E(F)| = 8,323,430,400 and |E(R)| = 116,677,584,000 — match p. 798.
#> F = 110.65 with 2 and 17 df, p < .0001 — matches book p. 798.

By dividing the determinants, we arrive at an FF value of 110.65 with 2 and 17 degrees of freedom (p<.0001p < .0001). Thus, the main effect of Angle is highly statistically significant when evaluated via the multivariate matrix approach.

14.6.11 — Test of the Interaction

The final omnibus effect is the interaction between Age and Angle. Like the main effect, this test involves comparing full and restricted models. The full models (E(F)E(F)) are identical to the ones we used for the within-subjects main effect, because they simply represent how much each participant deviates from their own specific group mean on D1D1 and D2D2.

The restricted models (E(R)E(R)), however, change. The interaction null hypothesis states that there are no group differences on the within-subjects differences. This means our restricted model simply predicts that every participant’s score on a DD variable is equal to the grand mean of that variable:

D1ij=μ1+ε1ijD_{1ij} = \mu_1 + \varepsilon_{1ij}

D2ij=μ2+ε2ijD_{2ij} = \mu_2 + \varepsilon_{2ij}

Let’s compute the new E(R)E(R) matrix for the interaction and compare it to the E(F)E(F) matrix we already computed.

HideShow
# Calculate the Restricted Model Errors for the Interaction
# e(R) = Participant Score - Grand Mean
e1_R_int <- chapter_14_table_9$D1 - D1_grand
e2_R_int <- chapter_14_table_9$D2 - D2_grand

# Calculate the Restricted Model Matrix E(R) for Interaction
E_R_int <- crossprod(cbind(e1_R_int, e2_R_int))
rownames(E_R_int) <- colnames(E_R_int) <- c("D1", "D2")

# Restricted Model Matrix E(R) for Interaction
print(E_R_int)
HideShow
      D1     D2
D1 99855  21285
D2 21285 153495
HideShow
#> 99,855 and 153,495 on the diagonal, 21,285 off it — matches the E(R) for the
#> interaction on p. 799.

This matrix differs from the E(R)E(R) used for the main effect, because each participant’s error is taken from the grand mean of the DD variable rather than from the group mean minus the grand mean (p. 799).

The special case F test (a=2a = 2)

Because our between-subjects factor (Age) only has two levels (a=2a = 2), we can use a simplified formula to calculate the FF statistic directly from the determinants of our two matrices (Equation 14.58, p. 800):

F=(|E(R)|−|E(F)|)/(b−1)|E(F)|/(N−b)F = \frac{(|E(R)| - |E(F)|) / (b - 1)}{|E(F)| / (N - b)}

HideShow
# Calculate Determinant of the new E(R)
det_ER_int <- det(E_R_int)

cat(
  "Determinant of E(F): ", format(det_EF, scientific = FALSE), "\n",
  "Determinant of E(R): ", format(det_ER_int, scientific = FALSE), "\n",
  sep = ""
)
HideShow
Determinant of E(F): 8323430400
Determinant of E(R): 14874192000
HideShow
# Compute the F-statistic for the interaction (a = 2 special case)
F_int_special <- ((det_ER_int - det_EF) / (b - 1)) / (det_EF / (N - b))
p_int_special <- pf(F_int_special, df1 = b - 1, df2 = N - b, lower.tail = FALSE)

cat(
  "\nInteraction Effect F-test (a = 2):\n",
  "F(", b - 1, ", ", N - b, ") = ", F_int_special, "\n",
  "p-value = ", p_int_special, "\n",
  sep = ""
)
HideShow

Interaction Effect F-test (a = 2):
F(2, 17) = 6.689727
p-value = 0.007192605
HideShow
#> |E(R)| = 14,874,192,000 — matches p. 801.
#> F = 6.69 with 2 and 17 df, p = .0072 — matches book p. 801.

The output yields an FF value of 6.69 with a pp value of .0072, indicating a significant Age ×\times Angle interaction.

General Multivariate Statistics (Wilks’s Lambda and Pillai–Bartlett)

When a design has more than two levels for the between-subjects factor (a>2a > 2), the simple determinant ratio breaks down, and we must rely on general multivariate test statistics. The book restricts its discussion to two of the four: Wilks’s Lambda (Λ\Lambda) and the Pillai–Bartlett trace (VV).

  1. Wilks’s Lambda (Λ\Lambda)

Wilks’s Lambda is the ratio of the full model’s determinant to the restricted model’s determinant, Λ=|E(F)|/|E(R)|\Lambda = |E(F)| / |E(R)| (Equation 14.60, p. 801). Values closer to 0 indicate larger effects, while values closer to 1 indicate smaller ones.

HideShow
# Calculate Wilks' Lambda
wilks_lambda <- det_EF / det_ER_int
cat("Wilks' Lambda:", wilks_lambda, "\n")
HideShow
Wilks' Lambda: 0.5595887 
  1. Pillai–Bartlett Trace (VV)

This statistic is based on subtracting the full matrix from the restricted matrix to get a Hypothesis matrix (H=E(R)−E(F)H = E(R) - E(F)). We then multiply HH by the inverse of the Total matrix (T=E(R)T = E(R)). The trace (sum of the diagonal elements) of this resulting matrix is Pillai’s VV.

HideShow
# Calculate Pillai-Bartlett Trace
H_matrix <- E_R_int - E_F
T_matrix <- E_R_int

# H multiplied by the inverse of T
HT_inv <- H_matrix %*% solve(T_matrix)

# H * T^-1 Matrix
print(HT_inv)
HideShow
          D1        D2
D1 0.2950662 0.1569726
D2 0.2732095 0.1453450
HideShow
#> .2951, .1570, .2732, .1453 — matches the matrix on p. 803.

# The trace is the sum of the diagonal elements
pillai_V <- sum(diag(HT_inv))
cat("\nPillai-Bartlett Trace (V):", pillai_V, "\n")
HideShow

Pillai-Bartlett Trace (V): 0.4404113 
HideShow
#> V = 0.4404 — matches book p. 804, where Equation 14.63 converts it to the
#> same F of 6.69 with 2 and 17 df.

Built-in Functions

We can bypass the matrix algebra using R’s built-in manova() function. Because the interaction hypothesis states that there are no group differences on the within-subjects differences, running a one-way MANOVA predicting our difference variables (D1D1 and D2D2) by the between-subjects factor (Age) tests the interaction.

HideShow
# Fit the MANOVA model predicting the difference scores by Age
interaction_manova <- manova(cbind(D1, D2) ~ Age, data = chapter_14_table_9)

# Request Wilks' Lambda
summary(interaction_manova, test = "Wilks")
HideShow
          Df   Wilks approx F num Df den Df   Pr(>F)   
Age        1 0.55959   6.6897      2     17 0.007193 **
Residuals 18                                           
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Wilks = 0.55959 and approx F = 6.69 with 2 and 17 df, p = .0072
#> — matches the by-hand values above and book p. 801.

# Request Pillai-Bartlett Trace
summary(interaction_manova, test = "Pillai")
HideShow
          Df  Pillai approx F num Df den Df   Pr(>F)   
Age        1 0.44041   6.6897      2     17 0.007193 **
Residuals 18                                           
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Pillai = 0.44041 — matches V = 0.4404 on p. 804, with the same F of 6.69.

Notice how the manova() summary outputs match our by-hand calculations exactly.

Because our design only has two levels for the between-subjects factor, the parameter ss (the smaller of a−1a-1 and b−1b-1) equals 1. Whenever s=1s = 1, all four multivariate test statistics (Wilks’s Lambda, Pillai–Bartlett, Hotelling–Lawley, and Roy’s greatest characteristic root) necessarily agree, which the book establishes on p. 804. This is why the specialized FF test above captures the interaction without the approximations that larger designs require.

14.7 — Measures of Effect

Even though we just used the multivariate (MANOVA) approach to test our within-subjects effects, when it comes to calculating effect sizes, the text recommends reverting to the mixed-model (univariate) formulation of omega squared (ω̂2\hat{\omega}^2).

This is because the mixed-model approach treats individual differences between subjects (SSS/ASS_{S/A}) as a meaningful source of total variance, ensuring our effect sizes reflect the reality of the repeated measures design.

The formulas for the split-plot design are identical to those from Chapter 12, repeated as Equations 12.22 through 12.24 on p. 805:

Main Effect of Between-Subjects Factor (A): ω̂A2=SSA−(a−1)MSS/ASSA+SSS/A+MSS/A\hat{\omega}^2_A = \frac{SS_A - (a-1)MS_{S/A}}{SS_A + SS_{S/A} + MS_{S/A}}

Main Effect of Within-Subjects Factor (B): ω̂B2=(b−1)(MSB−MSB×S/A)SSB+SSB×S/A+SSS/A+MSS/A\hat{\omega}^2_B = \frac{(b-1)(MS_B - MS_{B \times S/A})}{SS_B + SS_{B \times S/A} + SS_{S/A} + MS_{S/A}}

Interaction (AB): ω̂AB2=(a−1)(b−1)(MSAB−MSB×S/A)SSAB+SSB×S/A+SSS/A+MSS/A\hat{\omega}^2_{AB} = \frac{(a-1)(b-1)(MS_{AB} - MS_{B \times S/A})}{SS_{AB} + SS_{B \times S/A} + SS_{S/A} + MS_{S/A}}

While multivariate software doesn’t always output these mixed-model components directly, we can extract them in R by fitting a traditional univariate repeated measures ANOVA model.

HideShow
# Reshape the data to "long" format for univariate ANOVA
chapter_14_long <- reshape(
  as.data.frame(chapter_14_table_9),
  varying = c("Angle0", "Angle4", "Angle8"),
  v.names = "Score",
  timevar = "Angle",
  times = c(0, 4, 8),
  direction = "long"
)
chapter_14_long$Angle <- factor(chapter_14_long$Angle)
chapter_14_long$Participant <- factor(chapter_14_long$id)

# Run the mixed-model ANOVA
univariate_aov <- aov(Score ~ Age * Angle + Error(Participant/Angle), data = chapter_14_long)

# Save the summary object so we can extract values from it
aov_summary <- summary(univariate_aov)

# Extract the components dynamically
# The summary object is a list. [[1]] is the Between-Subjects part, [[2]] is the Within-Subjects part.

# Between-Subjects components (from Error: Participant)
# Row 1 is Age, Row 2 is Residuals (S/A)
SS_A  <- aov_summary$`Error: Participant`[[1]][1, "Sum Sq"]
SS_SA <- aov_summary$`Error: Participant`[[1]][2, "Sum Sq"]
MS_SA <- aov_summary$`Error: Participant`[[1]][2, "Mean Sq"]

# Within-Subjects components (from Error: Participant:Angle)
# Row 1 is Angle, Row 2 is Age:Angle, Row 3 is Residuals (BxS/A)
SS_B   <- aov_summary$`Error: Participant:Angle`[[1]][1, "Sum Sq"]
MS_B   <- aov_summary$`Error: Participant:Angle`[[1]][1, "Mean Sq"]
SS_AB  <- aov_summary$`Error: Participant:Angle`[[1]][2, "Sum Sq"]
MS_AB  <- aov_summary$`Error: Participant:Angle`[[1]][2, "Mean Sq"]
SS_BSA <- aov_summary$`Error: Participant:Angle`[[1]][3, "Sum Sq"]
MS_BSA <- aov_summary$`Error: Participant:Angle`[[1]][3, "Mean Sq"]

# Calculate Omega Squared Values
a <- length(levels(chapter_14_long$Age))   # Dynamically count levels of Age (2)
b <- length(levels(chapter_14_long$Angle)) # Dynamically count levels of Angle (3)

omega_sq_A  <- (SS_A - (a-1)*MS_SA) / (SS_A + SS_SA + MS_SA)
omega_sq_B  <- ((b-1)*(MS_B - MS_BSA)) / (SS_B + SS_BSA + SS_SA + MS_SA)
omega_sq_AB <- ((a-1)*(b-1)*(MS_AB - MS_BSA)) / (SS_AB + SS_BSA + SS_SA + MS_SA)

cat(
  "Omega Squared (Age): ", round(omega_sq_A, 2), "\n",
  "Omega Squared (Angle): ", round(omega_sq_B, 2), "\n",
  "Omega Squared (Age x Angle): ", round(omega_sq_AB, 2), "\n",
  sep = ""
)
HideShow
Omega Squared (Age): 0.24
Omega Squared (Angle): 0.52
Omega Squared (Age x Angle): 0.04
HideShow
#> .24, .52, and .04 — matches the omega squared values on p. 805.

As the text notes on p. 805, the Age (.24) and Angle (.52) main effects account for considerably more variance than the interaction (.04), but the interaction might still be the most theoretically interesting finding.

14.7.1 — Further Investigation of Main Effects

If we want to dig into the within-subjects main effect, we investigate specific DD variables.

For example, our D2D_2 variable represents the quadratic trend of the Angle factor. Let’s isolate the FF test for just the quadratic trend by looking specifically at the D2D_2 components of the E(F)E(F) and E(R)E(R) matrices we computed earlier in Section 14.6.10, which is exactly how the book proceeds on p. 806.

Recall Equation 14.48 for testing a specific DD variable:

F=ND‾2∑j=1a∑i=1n(Dij−D‾j)2/(N−a) F = \frac{N \bar{D}^2}{\sum_{j=1}^a \sum_{i=1}^n (D_{ij} - \bar{D}_j)^2 / (N - a)}

HideShow
# E_F and E_R from section 14.6.10 contain the Error components for D1 and D2
# The [2,2] elements correspond to D2 (the quadratic trend)
E_F_D2 <- E_F[2, 2]
E_R_D2 <- E_R[2, 2]

# The numerator is N * (Grand Mean of D2)^2, which is also E_R - E_F
num_D2 <- E_R_D2 - E_F_D2
cat("EF for D2:", E_F_D2, "\n")
HideShow
EF for D2: 125370 
HideShow
cat("ER for D2:", E_R_D2, "\n")
HideShow
ER for D2: 127575 
HideShow
cat("N * Dbar^2:", num_D2, "\n")
HideShow
N * Dbar^2: 2205 
HideShow
#> 125,370; 127,575; and 2,205 — all three match book p. 806.

# Calculate the F-statistic
df_num_D2 <- 1
df_den_D2 <- N - a

F_D2 <- num_D2 / (E_F_D2 / df_den_D2)
cat("\nF-statistic for Quadratic Trend (D2):", F_D2, "\n")
HideShow

F-statistic for Quadratic Trend (D2): 0.3165829 
HideShow
#> F = 0.32 with 1 and 18 df — matches book p. 806.

# Critical values: per comparison, then the post hoc Roy-Bose value of
# Equation 14.64 (p. 806).
qf(p = 1 - .05, df1 = 1, df2 = N - a)
HideShow
[1] 4.413873
HideShow
#> 4.41 — matches the critical value quoted on p. 807.
(N - a) * (b - 1) * qf(p = 1 - .05, df1 = b - 1, df2 = N - a - b + 2) /
  (N - a - b + 2)
HideShow
[1] 7.605594
HideShow
#> 7.60 — matches the post hoc critical value computed on p. 807.

The FF value is 0.32. Against either critical value it is far from significant, confirming there is no meaningful quadratic trend in the data.

We can bypass the by-hand arithmetic entirely with base R’s linear modeling. When software performs a multivariate test, it is simultaneously running univariate ANOVAs on each individual DD variable; the book notes on p. 807 that this is how statistical packages report the univariate FF of 233.41 for D1D_1 and 0.32 for D2D_2 alongside the multivariate FF of 110.65.

To see these in R, we can wrap our multivariate linear model in summary.aov(). However, there is a crucial distinction to keep in mind:

  1. To test the Interaction (Age ×\times Angle components): We look at the Age effect output by summary.aov().

  2. To test the Within-Subjects Main Effect (Angle components): We must look at the Intercept of these models, because testing if the grand mean of a difference score equals zero is exactly what an intercept test evaluates.

Let’s illustrate this. We will fit the linear model and explicitly ask for the Intercept test to find our 0.32 F-value.

HideShow
# Sum-to-zero coding for Age, so that the Intercept is the unweighted grand
# mean of each D variable rather than the mean of the first group. This is set
# on the Age column itself, visibly, because it changes what the output means.
contrasts(chapter_14_table_9$Age) <- contr.sum

# Fit the multivariate linear model predicting D1 and D2
multivariate_lm <- lm(cbind(D1, D2) ~ Age, data = chapter_14_table_9)

# View the univariate ANOVA for D2 (Quadratic Trend)
# We use summary() to see the t-test for the Intercept.
# Remember: F = t^2 for tests with 1 numerator degree of freedom!
summary(multivariate_lm)$`Response D2`
HideShow

Call:
lm(formula = D2 ~ Age, data = chapter_14_table_9)

Residuals:
   Min     1Q Median     3Q    Max 
-132.0  -64.5   18.0   63.0  138.0 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)  
(Intercept)   -10.50      18.66  -0.563   0.5806  
Age1          -37.50      18.66  -2.009   0.0597 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 83.46 on 18 degrees of freedom
Multiple R-squared:  0.1832,    Adjusted R-squared:  0.1379 
F-statistic: 4.038 on 1 and 18 DF,  p-value: 0.05972
HideShow
# The intercept t, squared, is the F for the quadratic trend.
summary(multivariate_lm)$`Response D2`$coefficients["(Intercept)", "t value"]^2
HideShow
[1] 0.3165829
HideShow
#> 0.32 — matches book p. 806.

In the output for Response D2, the (Intercept) row has a tt value of about −0.563-0.563, and squaring it returns the 0.32 we computed from the matrices.

If we wanted to test the univariate simple effects for the interaction instead, we would just run:

HideShow
# This will output the ANOVA tables showing the Age effect on D1 and D2
summary.aov(multivariate_lm)
HideShow
 Response D1 :
            Df Sum Sq Mean Sq F value   Pr(>F)   
Age          1  32805   32805  8.8067 0.008246 **
Residuals   18  67050    3725                    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 Response D2 :
            Df Sum Sq Mean Sq F value  Pr(>F)  
Age          1  28125   28125   4.038 0.05972 .
Residuals   18 125370    6965                  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> The Age line of Response D2 gives F = 4.038, p = .0597, the interaction
#> contrast the book reports on p. 814.

This breaks the omnibus multivariate models down into specific contrast tests without cross-multiplying any error matrices by hand.

14.7.2 — Further Investigation of an Interaction—Simple Effects

Because our Age ×\times Angle interaction was significant, we must break it down. We can test the between-subjects factor at fixed levels of the within-subjects factor (Age within a specific Angle), or the within-subjects factor at fixed levels of the between-subjects factor (Angle within a specific Age).

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

If we want to know whether Young and Old participants differ specifically at the 0° Angle, the within-subjects nature of the design drops out: only one score per participant is involved, so this is a one-way between-subjects ANOVA on the Angle0 column (p. 807). The book describes the procedure here rather than reporting a value for this particular test, so there is nothing to confirm against the printed page.

HideShow
# Simple effect of Age at 0 degrees
simple_effect_age_at_0 <- aov(Angle0 ~ Age, data = chapter_14_table_9)
summary(simple_effect_age_at_0)
HideShow
            Df Sum Sq Mean Sq F value Pr(>F)  
Age          1  21780   21780   3.161 0.0923 .
Residuals   18 124020    6890                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

As the book stresses on p. 808, this is a test on an original YY variable, not on a DD variable, and the error term it uses is MSS/A at BkMS_{S/A \text{ at } B_k} — the error term that does not require sphericity, and the one SAS, SPSS, and R all use by default.

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

This calculation is more complex in a multivariate framework. Let’s test the Angle effect only for the Younger participants. We treat this as a one-way within-subjects design using just the Young group.

Let’s compute the E(F)1E(F)_1 and E(R)1E(R)_1 matrices specifically for the Young participants.

HideShow
# Filter data for Young participants
young_data <- subset(chapter_14_table_9, Age == "Young")
n1 <- nrow(young_data)

# Get Means for Young participants
D1_mean_young <- mean(young_data$D1)
D2_mean_young <- mean(young_data$D2)

# Calculate E(F)_1 (Deviations from Young means)
e1_F_young <- young_data$D1 - D1_mean_young
e2_F_young <- young_data$D2 - D2_mean_young
E_F_1 <- crossprod(cbind(e1_F_young, e2_F_young))

# Calculate E(R)_1 (Deviations from zero, since null is no effect)
# Mathematically: E(R)_1 = E(F)_1 + n1 * (Mean Vector * Mean Vector^T)
E_R_1 <- matrix(c(
  E_F_1[1,1] + n1 * (D1_mean_young^2),
  E_F_1[1,2] + n1 * (D1_mean_young * D2_mean_young),
  E_F_1[2,1] + n1 * (D1_mean_young * D2_mean_young),
  E_F_1[2,2] + n1 * (D2_mean_young^2)
), nrow=2)

# E(F)_1 for Young Participants
print(E_F_1)
HideShow
           e1_F_young e2_F_young
e1_F_young      38160       3240
e2_F_young       3240      77760
HideShow
#> 38,160 and 77,760 on the diagonal, 3,240 off it — matches E(F)_1 on p. 809.

# E(R)_1 for Young Participants
print(E_R_1)
HideShow
       [,1]   [,2]
[1,] 320400 -77400
[2,] -77400 100800
HideShow
#> 320,400 and 100,800 on the diagonal, -77,400 off it — matches E(R)_1 on p. 809.

Both matrices match the book. The book also points out (p. 809) that the overall E(F)E(F) is the sum of the separate within-group matrices, which is worth checking because it is what makes the pooled error term below possible.

HideShow
old_data <- subset(chapter_14_table_9, Age == "Old")
E_F_2 <- crossprod(cbind(old_data$D1 - mean(old_data$D1),
                         old_data$D2 - mean(old_data$D2)))
print(E_F_2)
HideShow
       [,1]   [,2]
[1,]  28890 -12330
[2,] -12330  47610
HideShow
#> 28,890 and 47,610 on the diagonal, -12,330 off it — matches E(F)_2 on p. 809.

# E(F) = E(F)_1 + E(F)_2
E_F_1 + E_F_2
HideShow
           e1_F_young e2_F_young
e1_F_young      67050      -9090
e2_F_young      -9090     125370
HideShow
#> 67,050 and 125,370 on the diagonal, -9,090 off it: the E(F) of Section
#> 14.6.10, as the book states on p. 809.

Now we calculate the FF test. There are two approaches to do so.

  1. Separate Error Term (Equation 14.65, p. 809)

F=(|E(R)1|−|E(F)1|)/(b−1)|E(F)1|/(n1−b+1) F = \frac{(|E(R)_1| - |E(F)_1|) / (b - 1)}{|E(F)_1| / (n_1 - b + 1)}

HideShow
det_EF1 <- det(E_F_1)
det_ER1 <- det(E_R_1)

c(det_E_F_1 = det_EF1, det_E_R_1 = det_ER1)
HideShow
  det_E_F_1   det_E_R_1 
 2956824000 26305560000 
HideShow
#> 2,956,824,000 and 26,305,560,000 — match the determinants on p. 809.

F_sep <- ((det_ER1 - det_EF1) / (b - 1)) / (det_EF1 / (n1 - b + 1))
p_sep <- pf(F_sep, df1 = b - 1, df2 = n1 - b + 1, lower.tail = FALSE)

cat("F-test (Separate Error Term): F = ", F_sep, ", p = ", p_sep, "\n")
HideShow
F-test (Separate Error Term): F =  31.58624 , p =  0.000159629 
HideShow
#> F = 31.59 with 2 and 8 df, p = .0002 — matches book p. 809.

The result (F=31.59F = 31.59, p=.0002p = .0002) shows a highly significant Angle effect for the Young group.

  1. Pooled Error Term (Alternative)

If we assume the covariance matrices are equal in the population (Homogeneity of Covariance), we gain statistical power by using the overall E(F)E(F) matrix – calculated from all participants – as our error term.

The formula for the pooled FF statistic (Equation 14.66, p. 810) substitutes our targeted hypothesis matrix into the overall error space:

F=(|E(F)+E(R)j−E(F)j|−|E(F)|)/(b−1)|E(F)|/(N−a−b+2) F = \frac{(|E(F) + E(R)_j - E(F)_j| - |E(F)|) / (b - 1)}{|E(F)| / (N - a - b + 2)}

HideShow
# E_F and det_EF are the full-sample matrix and determinant from Section 14.6.10.

# The text defines a specific matrix addition/subtraction:
Pooled_Hypothesis_Matrix <- E_F + E_R_1 - E_F_1

print(Pooled_Hypothesis_Matrix)
HideShow
       D1     D2
D1 349290 -89730
D2 -89730 148410
HideShow
#> 349,290 and 148,410 on the diagonal, -89,730 off it — matches p. 810.

det_pooled_hyp <- det(Pooled_Hypothesis_Matrix)
cat("Determinant of |E(F) + E(R)1 - E(F)1|:", format(det_pooled_hyp, scientific=FALSE), "\n")
HideShow
Determinant of |E(F) + E(R)1 - E(F)1|: 43786656000 
HideShow
#> 43,786,656,000 — matches book p. 810.

# Calculate the F-statistic using the overall det_EF computed in 14.6.10
F_pooled <- ((det_pooled_hyp - det_EF) / (b - 1)) / (det_EF / (N - a - b + 2))
p_pooled <- pf(F_pooled, df1 = b - 1, df2 = N - a - b + 2, lower.tail = FALSE)

cat("F-test (Pooled Error Term): F = ", F_pooled, ", p = ", p_pooled, "\n")
HideShow
F-test (Pooled Error Term): F =  36.21553 , p =  7.433013e-07 
HideShow
#> F = 36.22 with 2 and 17 df, p < .0001 — matches book p. 810.

Using the pooled error term gives us F=36.22F = 36.22 with p<.0001p < .0001, which is somewhat more powerful because of the additional denominator degrees of freedom (17 instead of 8). However, as the textbook warns on pp. 810–811, the pooled test is not robust to violations of the homogeneity of covariance matrices assumption, and Box’s MM test is of little practical help in deciding. With samples of perhaps 40 or more per level of AA, the separate error term is preferable because the extra degrees of freedom from pooling are then inconsequential.

14.7.5 — Cell Mean Comparisons

Because we found a significant overall Angle effect for the younger participants, it makes sense to drill down even further. Let’s test a specific contrast (the quadratic trend) strictly for the younger participants.

This test is essentially a one-way within-subjects contrast. However, just like in the previous section, we must choose between a separate error term (using only the data from the younger participants) and a pooled error term (using error data across all participants).

Method 1: separate error term

The FF statistic for testing a specific DD variable at a specific level of AA (AjA_j) using a separate error term is Equation 14.67 (p. 812): F=njD‾2j2sD2j2F = \frac{n_j \bar{D}_{2j}^2}{s_{D2j}^2}

Let’s calculate this in R using the young_data we created earlier.

HideShow
# Get the sample size, mean, and variance of D2 for Young participants
n1 <- nrow(young_data)
Dbar_21 <- mean(young_data$D2)
s2_D21 <- var(young_data$D2)

cat("Mean of D2 (Young):", Dbar_21, "\n",
    "Variance of D2 (Young):", s2_D21, "\n")
HideShow
Mean of D2 (Young): -48 
 Variance of D2 (Young): 8640 
HideShow
#> -48 and 8,640 — match book p. 812.

# Calculate the F-statistic
F_cell_sep <- (n1 * Dbar_21^2) / s2_D21
p_cell_sep <- pf(F_cell_sep, df1 = 1, df2 = n1 - 1, lower.tail = FALSE)

cat("\nF-statistic (Separate Error):", round(F_cell_sep, 2), "\n")
HideShow

F-statistic (Separate Error): 2.67 
HideShow
cat("p-value:", round(p_cell_sep, 4), "\n")
HideShow
p-value: 0.1369 
HideShow
#> F = 2.67 with 1 and 9 df — matches book p. 812.

# The book also reads these numbers off the diagonals of E(F)_1 and E(R)_1:
# the numerator is the difference of the [2, 2] elements and the denominator
# divides the E(F)_1 element by n1 - 1.
c(numerator = E_R_1[2, 2] - E_F_1[2, 2], denominator = E_F_1[2, 2] / (n1 - 1))
HideShow
  numerator denominator 
      23040        8640 
HideShow
#> 23,040 and 8,640 — match book p. 812, and their ratio is again 2.67.

Testing whether the mean of a difference score equals zero for a single group is the definition of a one-sample tt-test, so the same result is available directly.

HideShow
t.test(
  x           = young_data$D2,
  mu          = 0,
  alternative = "two.sided",
  conf.level  = 0.95
)
HideShow

    One Sample t-test

data:  young_data$D2
t = -1.633, df = 9, p-value = 0.1369
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 -114.49357   18.49357
sample estimates:
mean of x 
      -48 
HideShow
#> t = -1.633, and (-1.633)^2 = 2.67 — matches the F on p. 812.
Method 2: pooled error term

If we assume homogeneity of variance across the age groups, we can pool the variance of D2D_2 across both groups. We substitute the separate variance with the pooled variance, sD2p2s_{D2p}^2 (also known as the mean square within for the DD variable, MSS/A(D)MS_{S/A(D)}). This is Equation 14.68 (p. 812).

F=njD‾2j2sD2p2 F = \frac{n_j \bar{D}_{2j}^2}{s_{D2p}^2}

HideShow
# The Older participants' variance on D2 (old_data was built above)
s2_D22 <- var(old_data$D2)

# Calculate pooled variance (unweighted average, since n is equal)
s2_D2p <- (s2_D21 + s2_D22) / 2
cat("Variance of D2 (Old):", s2_D22, "\n")
HideShow
Variance of D2 (Old): 5290 
HideShow
cat("Pooled Variance of D2:", s2_D2p, "\n")
HideShow
Pooled Variance of D2: 6965 
HideShow
#> 5,290 and 6,965 — match book p. 812.

# The same pooled variance is the [2, 2] element of E(F) divided by N - a.
E_F[2, 2] / (N - a)
HideShow
[1] 6965
HideShow
#> 6,965 — the equivalence the book points out on p. 812.

# Calculate the F-statistic
F_cell_pool <- (n1 * Dbar_21^2) / s2_D2p
# Denominator df is N - a (20 - 2 = 18)
p_cell_pool <- pf(F_cell_pool, df1 = 1, df2 = N - a, lower.tail = FALSE)

cat(
  "\nF-statistic (Pooled Error):", round(F_cell_pool, 2), "\n",
  "p-value:", round(p_cell_pool, 4), "\n"
)
HideShow

F-statistic (Pooled Error): 3.31 
 p-value: 0.0856 
HideShow
#> F = 3.31 with 1 and 18 df — matches book p. 812.

Using the pooled error gives us an FF value of 3.31. As discussed previously, deciding which critical value to use for these tests depends on whether they were planned (Bonferroni) or post hoc, in which case the Roy–Bose values of Equations 14.69 and 14.70 (p. 813) apply, the first for the separate error term and the second for the pooled one.

14.7.6 — Interaction Contrasts

Instead of looking at the simple effect of the quadratic trend within one group, we can evaluate if the quadratic trend is significantly different between the younger and older participants with an interaction contrast.

Because an interaction contrast effectively reduces the within-subjects factor down to a single DD variable (the quadratic trend difference), the within-subjects nature of the design vanishes! We are left comparing two independent groups on a single score.

The formula from Chapter 4 for testing a specific between-group comparison applies directly, which the book gives as Equation 14.73 (p. 814):

F=ψ̂2MSS/A(D)∑j=1a(cj2/nj) F = \frac{\hat{\psi}^2}{MS_{S/A}(D) \sum_{j=1}^a (c_j^2/n_j)}

Let’s define our contrast (ψ̂\hat{\psi}) as the difference between the mean D2D_2 score for younger participants and the mean D2D_2 score for older participants (c1=1c_1 = 1, c2=−1c_2 = -1).

HideShow
# Get the mean D2 score for Older participants
Dbar_22 <- mean(old_data$D2)

# Calculate the contrast (psi_hat)
psi_hat <- Dbar_21 - Dbar_22
cat("Contrast (Psi Hat):", psi_hat, "\n")
HideShow
Contrast (Psi Hat): -75 
HideShow
#> -48 - 27 = -75 — matches book p. 814.

MS_SA_D <- s2_D2p # We already calculated MS_S/A(D) as the pooled variance (s2_D2p)


# Calculate the F-statistic
# Contrast weights: c1 = 1, c2 = -1. n1 = 10, n2 = 10.
sum_cj2_nj <- (1^2 / 10) + ((-1)^2 / 10)

F_interaction_contrast <- (psi_hat^2) / (MS_SA_D * sum_cj2_nj)
p_interaction_contrast <- pf(F_interaction_contrast, df1 = 1, df2 = N - a, lower.tail = FALSE)

cat(
  "\nF-statistic (Interaction Contrast):", round(F_interaction_contrast, 2), "\n",
  "p-value:", round(p_interaction_contrast, 4), "\n"
)
HideShow

F-statistic (Interaction Contrast): 4.04 
 p-value: 0.0597 
HideShow
#> F = 4.04 with 1 and 18 df, p = .0597 — matches book p. 814.
The ANOVA shortcut

The text notes that testing an interaction contrast when AA has two levels is identical to running a standard one-way ANOVA (or independent samples tt-test) on the DD variable (p. 814). We can show this by running aov() on the D2D_2 column using Age as the predictor:

HideShow
# Run a standard univariate ANOVA on the D2 variable
interaction_contrast_aov <- aov(D2 ~ Age, data = chapter_14_table_9)
summary(interaction_contrast_aov)
HideShow
            Df Sum Sq Mean Sq F value Pr(>F)  
Age          1  28125   28125   4.038 0.0597 .
Residuals   18 125370    6965                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 4.038 with 1 and 18 df, p = .0597 — matches book p. 814, and the
#> residual mean square of 6,965 is MS_S/A(D) again.

Here the FF value is 4.04, the same as the contrast computation above, with p=.0597p = .0597. Treating the difference score as an ordinary dependent variable removes the need for the algebra altogether. For a post hoc test the critical value would come from Equation 14.75 (p. 814), which is the a=2a = 2 form of the Roy–Bose value.

14.8 — Confidence Intervals for Contrasts

Now that we have covered hypothesis testing in split-plot designs using the multivariate approach, we turn to forming confidence intervals. The general form of a confidence interval here is identical to what we have seen in previous chapters:

ψ̂±(CV)(seψ̂)\hat{\psi} \pm (\sqrt{CV})(se_{\hat{\psi}})

Where: * ψ̂\hat{\psi} is the estimated value of the contrast. * CVCV is the appropriate critical value (often an FF or t2t^2 value). * seψ̂se_{\hat{\psi}} is the standard error of the contrast.

The complexities in a split-plot design arise because we can base our contrast on different types of variables: an M variable (marginal means), a D variable (difference scores), or a Y variable (a single column/level of the within-subjects factor).

Depending on the research question, we might want to form confidence intervals for: 1. A contrast among levels of the between-subjects marginal mean.

  1. A contrast among levels of the within-subjects marginal mean.

  2. A contrast among levels of the within-subjects factor at a specific level of the between-subjects factor (Simple effect of within).

  3. A contrast among levels of the between-subjects factor at a specific level of the within-subjects factor (Simple effect of between).

  4. An interaction contrast.

Let’s reproduce the five specific confidence intervals the book shows in Table 14.12 (p. 816) and discusses one at a time on pp. 817–819. All five assume a per-comparison alpha level of .05.

First, we need to set up the proper dependent variables. The text operationalizes the quadratic trend with coefficients of −0.5-0.5, 1.01.0, and −0.5-0.5 (p. 818), which is the scaling its reported estimates use.

HideShow
# Define the specific Quadratic D variable used in Table 14.12
# Coefficients: 0 degrees (-0.5), 4 degrees (1.0), 8 degrees (-0.5)
chapter_14_table_9$D_quad <-
  -0.5 * chapter_14_table_9$Angle0 +
   1.0 * chapter_14_table_9$Angle4 -
   0.5 * chapter_14_table_9$Angle8

# Put "Old" first so that every two-group contrast below is Old minus Young,
# the direction in which the book reports these intervals. Re-creating the
# factor resets its contrasts, so the sum-to-zero coding is set again.
chapter_14_table_9$Age <- factor(chapter_14_table_9$Age, levels = c("Old", "Young"))
contrasts(chapter_14_table_9$Age) <- contr.sum
  1. Levels of Between-Subjects Marginal Means

Question: What is the age difference in reaction time, averaging over all angles?

Variable: MM (The mean across the three angles for each participant).

Because we are looking at the MM variable, we have effectively collapsed our data into a simple between-subjects design. We can run a standard independent samples tt-test, which is Equation 4.40 applied to MM (p. 817).

HideShow
# Between-Subjects Marginal Mean (Age diff on M)
ci_1 <- t.test(M ~ Age, data = chapter_14_table_9,
               var.equal = TRUE, alternative = "two.sided", conf.level = 0.95)

cat(
  "Estimate:", round(ci_1$estimate[1] - ci_1$estimate[2], 2), "\n",
  "Standard Error:", round(ci_1$stderr, 2), "\n",
  "t-value:", round(abs(ci_1$statistic), 2), "\n",
  "95% CI: [", round(ci_1$conf.int[1], 2), ",",
  round(ci_1$conf.int[2], 2), "]\n"
)
HideShow
Estimate: 94 
 Standard Error: 34.85 
 t-value: 2.7 
 95% CI: [ 20.79 , 167.21 ]
HideShow
#> Estimate 94, t = 2.70, 95% CI [20.79, 167.21] — matches book p. 817.

The estimate is 94 (663−569=94663 - 569 = 94). The tt value squared (2.702=7.292.70^2 = 7.29) agrees within rounding error with the FF value of 7.28 from our Age main effect test, which is the first of the two verification checks the book recommends on p. 817.

  1. Levels of Within-Subjects Marginal Means

Question: What is the quadratic trend for the angle factor, averaging over age?

Variable: DquadD_{quad} (Evaluated against a population mean of 0).

Averaging over groups, we are testing whether the grand mean of this difference score is zero. The error term for that test is not the total variance of DquadD_{quad}: as Equation 14.48 shows, it is the within-group variance, because the full model for a DD variable in a split-plot design keeps the between-subjects effect in it. With sum-to-zero coding, the intercept of lm(D_quad ~ Age) is the unweighted grand mean and its standard error is MSS/A(D)/N\sqrt{MS_{S/A(D)}/N}, so confint() gives the interval directly, with N−a=18N - a = 18 degrees of freedom.

HideShow
# Within-Subjects Marginal Mean (Quadratic trend on D_quad), pooled error
model_D_quad <- lm(D_quad ~ Age, data = chapter_14_table_9)

summary(model_D_quad)$coefficients["(Intercept)", ]
HideShow
  Estimate Std. Error    t value   Pr(>|t|) 
 5.2500000  9.3307288  0.5626570  0.5806094 
HideShow
confint(model_D_quad)["(Intercept)", ]
HideShow
    2.5 %    97.5 % 
-14.35313  24.85313 
HideShow
#> Estimate 5.25, se 9.33, t = 0.56, 95% CI [-14.35, 24.85] — matches book p. 818.

# The marginal means of Angle that produce the estimate of 5.25.
colMeans(chapter_14_table_9[, c("Angle0", "Angle4", "Angle8")])
HideShow
Angle0 Angle4 Angle8 
 510.0  619.5  718.5 
HideShow
#> 510, 619.5, and 718.5 — matches the marginal means on p. 818, and
#> -0.5(510) + 1(619.5) - 0.5(718.5) = 5.25.

The interval [−14.35,24.85][-14.35, 24.85] contains 0, consistent with the nonsignificant t=0.56t = 0.56, whose square is the FF of 0.32 we reported for the marginal quadratic trend. A one-sample tt-test on D_quad would use the total variance instead of the within-group variance and so would not reproduce the book’s interval.

  1. Within-Subjects Factor at a Specified Level of Between-Subjects Factor

Question: What is the quadratic trend specifically for younger participants?

Variable: DquadD_{quad} (Evaluated only for the “Young” group, but using a pooled error term).

As the book explains on p. 818, the standard error here can be based on the younger participants alone or on all participants if homogeneity of variance is assumed; Table 14.12 reports the version that uses all participants. We extract the pooled mean square within (MSWMS_W) from the same linear model as above.

HideShow
# Simple effect of within (Quadratic angle for Young, pooled error)
# Extract data for just the young group
young_D_quad <- subset(chapter_14_table_9, Age == "Young")$D_quad

# Get pooled variance from a linear model
lm_pooled <- lm(D_quad ~ Age, data = chapter_14_table_9)
MSW_pooled <- anova(lm_pooled)["Residuals", "Mean Sq"]

# Calculate SE and CI directly, to enforce the pooled error
estimate_3 <- mean(young_D_quad)
n_young <- length(young_D_quad)
se_3 <- sqrt(MSW_pooled / n_young)
t_val_3 <- estimate_3 / se_3
df_pooled <- lm_pooled$df.residual
tcrit <- qt(0.975, df = df_pooled)

cat(
  "Estimate:", round(estimate_3, 2), "\n",
  "Standard Error:", round(se_3, 2), "\n",
  "t-value:", round(t_val_3, 2), "\n",
  "95% CI: [", round(estimate_3 - tcrit * se_3, 2), ",",
  round(estimate_3 + tcrit * se_3, 2), "]\n"
)
HideShow
Estimate: 24 
 Standard Error: 13.2 
 t-value: 1.82 
 95% CI: [ -3.72 , 51.72 ]
HideShow
#> Estimate 24, t = 1.82, 95% CI [-3.72, 51.72] — matches book p. 818, and
#> 1.82^2 is the F of 3.31 reported for this effect on p. 812.
  1. Between-Subjects Factor at a Specified Level of Within-Subjects Factor

Question: What is the age difference specifically at the 8° angle?

Variable: YY (The raw Angle8 column).

Because we are only looking at one specific angle condition, the within-subjects nature of the design drops out entirely. We test this using a standard independent samples tt-test on that single column.

HideShow
# Simple effect of between (Age diff at 8 degrees)
ci_4 <- t.test(Angle8 ~ Age, data = chapter_14_table_9,
               var.equal = TRUE, alternative = "two.sided", conf.level = 0.95)

cat(
  "Estimate:", round(ci_4$estimate[1] - ci_4$estimate[2], 2), "\n",
  "Standard Error:", round(ci_4$stderr, 2), "\n",
  "t-value:", round(abs(ci_4$statistic), 2), "\n",
  "95% CI: [", round(ci_4$conf.int[1], 2), ",",
  round(ci_4$conf.int[2], 2), "]\n"
)
HideShow
Estimate: 147 
 Standard Error: 38.07 
 t-value: 3.86 
 95% CI: [ 67.03 , 226.97 ]
HideShow
#> Estimate 147 (792 - 645), 95% CI [67.03, 226.97] — matches book p. 818.

Interpretation: we are 95% confident that at 8°, older adults take between 67.03 ms and 226.97 ms longer to react than younger adults. The estimate of 147 is the difference between the mean values of 792 and 645 in Table 14.9, which is the book’s second verification check — the contrast estimate is the intended linear combination of cell means.

  1. Interaction Contrast

Question: Is the linear trend for angle different for older vs. younger participants?

Variable: D1D_1 (The linear difference score, tested across the Age groups).

An interaction contrast effectively reduces the within-subjects repeated measures down to a single difference score (D1D_1). We then compare the two independent groups on this score.

HideShow
# 5. Interaction Contrast (Age diff in linear trend D1)
ci_5 <- t.test(D1 ~ Age, data = chapter_14_table_9,
               var.equal = TRUE, alternative = "two.sided", conf.level = 0.95)

cat(
  "Estimate:", round(ci_5$estimate[1] - ci_5$estimate[2], 2), "\n",
  "Standard Error:", round(ci_5$stderr, 2), "\n",
  "t-value:", round(abs(ci_5$statistic), 2), "\n",
  "95% CI: [", round(ci_5$conf.int[1], 2), ",",
  round(ci_5$conf.int[2], 2), "]\n"
)
HideShow
Estimate: 81 
 Standard Error: 27.29 
 t-value: 2.97 
 95% CI: [ 23.66 , 138.34 ]
HideShow
#> Estimate 81 (249 - 168), 95% CI [23.66, 138.34] — matches book p. 819.

Interpretation: the interval [23.66,138.34][23.66, 138.34] does not contain zero, confirming a significant interaction. Increasing the angle from 0° to 8° causes a significantly steeper increase in reaction time for older participants than it does for younger participants, by somewhere between about 24 ms and 138 ms.

14.11 — Longitudinal Randomized Designs

Designs combining a between-subjects factor and a within-subjects factor are incredibly common. A frequent special case is the longitudinal randomized design, where the between-subjects factor is a randomly assigned treatment condition (e.g., Treatment vs. Control) and the within-subjects factor is time.

Crucially, in these designs, the first time point is often a baseline (pretest) measure taken before the intervention begins.

The book’s example is a study of 100 participants, 44 assigned to an active treatment and 56 to a control group, measured at a baseline and two post-intervention occasions (p. 821). Table 14.13 gives the sample means, which are all of the raw data the book reports for this example, so we cannot reproduce its test statistics from the printed page. What we can do is build a data set that has exactly those group means, carry out each analysis the section describes on it, and state the book’s own results beside them. The standard deviations and correlations below are illustrative, not the book’s, and the text is explicit (p. 821) that those are what determine whether the mean pattern is statistically significant.

HideShow
# MASS (mvrnorm) and car (Manova) are loaded above.
set.seed(113)

# Means from Table 14.13 (p. 821)
mu_Control   <- c(98.71, 97.90, 99.49)
mu_Treatment <- c(98.14, 105.78, 107.48)

# An illustrative covariance matrix: SD = 22 at each occasion, r = .5 between
# occasions. The book reports no standard deviations for this example; this
# spread was chosen so that the mean pattern of Table 14.13 is about as hard
# to detect here as it is in the book's own data.
sigma <- matrix(c(484, 242, 242,
                  242, 484, 242,
                  242, 242, 484), nrow = 3)

# Generate data, then shift each group so that its sample means are exactly
# the means printed in Table 14.13.
n_Control   <- 56
n_Treatment <- 44

match_means <- function(Y, mu) sweep(sweep(Y, 2, colMeans(Y)), 2, mu, "+")

data_Control   <- match_means(mvrnorm(n_Control,   mu_Control,   sigma), mu_Control)
data_Treatment <- match_means(mvrnorm(n_Treatment, mu_Treatment, sigma), mu_Treatment)

# Combine into a single data frame, spelling out the condition level by level.
df_longitudinal <- data.frame(
  Condition = factor(rep(c("Control", "Treatment"), c(n_Control, n_Treatment)),
                     levels = c("Control", "Treatment")),
  Time1 = c(data_Control[, 1], data_Treatment[, 1]), # Baseline
  Time2 = c(data_Control[, 2], data_Treatment[, 2]), # Post-intervention 1
  Time3 = c(data_Control[, 3], data_Treatment[, 3])  # Post-intervention 2
)

head(df_longitudinal)
HideShow
  Condition     Time1     Time2     Time3
1   Control 103.69661 102.91241  93.54411
2   Control  88.08470  81.45296  63.69278
3   Control  72.41065  77.80831 116.77315
4   Control 131.64773 125.59953 119.81621
5   Control 119.83545  91.78545 125.83002
6   Control 137.76032 135.18206 127.75664
HideShow
# The cell means now reproduce Table 14.13 exactly.
df_longitudinal |>
  group_by(Condition) |>
  summarize(across(Time1:Time3, mean))
HideShow
# A tibble: 2 × 4
  Condition Time1 Time2 Time3
  <fct>     <dbl> <dbl> <dbl>
1 Control    98.7  97.9  99.5
2 Treatment  98.1 106.  107. 
HideShow
#> Control 98.71, 97.90, 99.49; Treatment 98.14, 105.78, 107.48
#> — matches Table 14.13 (p. 821).
The “naive” approach: a 2 x 3 repeated measures analysis

Because the data look just like the split-plot designs we analyzed earlier in the chapter, our first instinct might be to run a 2 (Condition) ×\times 3 (Time) analysis treating baseline simply as level 1 of the Time factor. By the logic of Section 14.6, the Condition ×\times Time interaction is a MANOVA comparing the groups on the two gain scores from baseline, which the book states explicitly on p. 822.

HideShow
# D variables are gain scores from baseline: this MANOVA IS the interaction test.
df_longitudinal$Gain1 <- df_longitudinal$Time2 - df_longitudinal$Time1
df_longitudinal$Gain2 <- df_longitudinal$Time3 - df_longitudinal$Time1

rm_interaction <- manova(cbind(Gain1, Gain2) ~ Condition, data = df_longitudinal)
summary(rm_interaction)
HideShow
          Df   Pillai approx F num Df den Df  Pr(>F)  
Condition  1 0.049074   2.5029      2     97 0.08712 .
Residuals 98                                          
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

For the book’s own data this test gives F(2,97)=2.516F(2, 97) = 2.516 with p=.086p = .086 (Table 14.14, p. 821), and none of the three omnibus effects reaches the .05 level: Condition is F(1,98)=1.824F(1, 98) = 1.824, p=.180p = .180, and Time is F(2,97)=2.583F(2, 97) = 2.583, p=.081p = .081. Testing the simple effects at each post-intervention occasion does not help either — the book reports pp values of .095 and .084 (p. 822) — and the linear component of the interaction misses as well, at p=.066p = .066 (p. 822). The researcher is left unable to conclude that the treatment worked. The illustrative data above behave the same way: the interaction test does not reach the .05 level, even though the treatment group’s means rise by more than 9 points while the control group’s barely move.

Let’s look at why this happens and what we should do instead.

The better approach: MANCOVA (and ANCOVA)

As we learned in Chapter 9 for pretest-posttest designs, analyzing the data using Analysis of Covariance (ANCOVA) is almost always superior to using repeated measures ANOVA or analyzing simple gain scores.

Because we have two post-intervention measures here (Time 2 and Time 3), we generalize ANCOVA to Multivariate Analysis of Covariance (MANCOVA).

Random assignment balances baseline scores in expectation, although sample means can differ by chance. When baseline predicts the post-test outcomes, adjusting for it can reduce residual variation.

Here is how we run a MANCOVA in R, predicting the post-intervention scores from Condition, while covarying Baseline:

HideShow
# Fit the multivariate linear model using Time1 as a covariate
mancova_model <- lm(cbind(Time2, Time3) ~ Condition + Time1, data = df_longitudinal)

# Run the MANOVA on the model
Manova(mancova_model)
HideShow

Type II MANOVA Tests: Pillai test statistic
          Df test stat approx F num Df den Df    Pr(>F)    
Condition  1  0.063026   3.2288      2     96   0.04395 *  
Time1      1  0.302107  20.7785      2     96 3.176e-08 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

For the book’s data, the MANCOVA test of the Condition effect gives F=3.110F = 3.110 with p=.049p = .049 (p. 823) — statistically significant where the 2 ×\times 3 analysis of the same data was not. The same reversal happens with the illustrative data above, for the same reason: covarying baseline removes variance from the post-test scores that the gain-score analysis leaves in the error term. The exact FF here is not the book’s, because the book reports only the means for this example, and these standard deviations and correlations are ours.

The adjusted condition effect compares the groups on their post-test outcomes at a common baseline score.

We have bypassed the underpowered repeated measures analysis and reached a conclusion the data can support, using the same participants and the same measurements.

Follow-up tests: univariate ANCOVAs

If the omnibus MANCOVA is significant, we can test whether the groups differ at specific measurement occasions using standard univariate ANCOVAs.

HideShow
# Test group difference at Time 2, covarying Baseline (Time 1)
ancova_time2 <- lm(Time2 ~ Condition + Time1, data = df_longitudinal)
car::Anova(ancova_time2, type = "III") # Type III recommended for ANCOVA with unbalanced designs
HideShow
Anova Table (Type III tests)

Response: Time2
            Sum Sq Df F value    Pr(>F)    
(Intercept)   8702  1 20.2651 1.877e-05 ***
Condition     1646  1  3.8321   0.05315 .  
Time1        10853  1 25.2730 2.276e-06 ***
Residuals    41655 97                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
# Test group difference at Time 3, covarying Baseline (Time 1)
ancova_time3 <- lm(Time3 ~ Condition + Time1, data = df_longitudinal)
car::Anova(ancova_time3, type = "III")
HideShow
Anova Table (Type III tests)

Response: Time3
            Sum Sq Df F value    Pr(>F)    
(Intercept)   9444  1 28.0040 7.513e-07 ***
Condition     1689  1  5.0095    0.0275 *  
Time1        10693  1 31.7071 1.745e-07 ***
Residuals    32711 97                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

By accounting for the baseline variance, these ANCOVAs provide more power and precision than the simple effects tests derived from the 2 ×\times 3 analysis, for the reason Equation 9.49 gives: they use the correlation between baseline and each post-intervention measure, which the simple effects tests ignore.

The row to read in each table is Condition. For the book’s data these two ANCOVAs give F=4.691F = 4.691 with p=.033p = .033 at the first post-intervention occasion and F=4.141F = 4.141 with p=.045p = .045 at the second (p. 823) — both significant, where the corresponding simple effects tests in the 2 ×\times 3 analysis gave p=.095p = .095 and p=.084p = .084. That is not a contradiction but the power difference at work.

The two follow-up ANCOVAs are easiest to read side by side. With modelsummary, each model occupies its own column with fit statistics at the foot:

HideShow
modelsummary(
  list("Time 2 (covary baseline)" = ancova_time2,
       "Time 3 (covary baseline)" = ancova_time3),
  estimate  = "{estimate}",
  statistic = "({std.error})",   # standard errors in parentheses, APA style
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  stars     = TRUE,
  output    = "gt"
)
Time 2 (covary baseline) Time 3 (covary baseline)
(Intercept) 47.136 49.102
(10.471) (9.279)
ConditionTreatment 8.173 8.281
(4.175) (3.700)
Time1 0.514 0.510
(0.102) (0.091)
Num.Obs. 100 100
AIC 895.0 870.8
BIC 905.4 881.2
Log.Lik. -443.494 -431.409
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

The same comparison as a gtsummary table, each model under its own spanning header:

HideShow
t_time2 <- tbl_regression(ancova_time2, intercept = TRUE)
t_time3 <- tbl_regression(ancova_time3, intercept = TRUE)
tbl_merge(list(t_time2, t_time3),
          tab_spanner = c("**Time 2**", "**Time 3**"))
Characteristic
Time 2
Time 3
Beta 95% CI p-value Beta 95% CI p-value
(Intercept) 47 26, 68 <0.001 49 31, 68 <0.001
Condition





    Control — —
— —
    Treatment 8.2 -0.11, 16 0.053 8.3 0.94, 16 0.027
Time1 0.51 0.31, 0.72 <0.001 0.51 0.33, 0.69 <0.001
Abbreviation: CI = Confidence Interval
An alternative formulation: MANCOVA on gain scores

Some researchers prefer to analyze the data in a way that makes “change” more explicit.

The book notes (p. 823) that running a MANCOVA predicting the raw post-test scores while covarying baseline is mathematically identical to running a MANCOVA predicting the gain scores while covarying baseline. That identity does not depend on the particular data, so it is something we can demonstrate exactly here.

HideShow
# The gain scores from baseline, created above for the interaction test.

# Fit MANCOVA on the Gain scores, covarying Baseline
mancova_gain_model <- lm(cbind(Gain1, Gain2) ~ Condition + Time1, data = df_longitudinal)

# Results
Manova(mancova_gain_model)
HideShow

Type II MANOVA Tests: Pillai test statistic
          Df test stat approx F num Df den Df    Pr(>F)    
Condition  1  0.063026   3.2288      2     96   0.04395 *  
Time1      1  0.282237  18.8745      2     96 1.222e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The Condition row is identical to the one in the MANCOVA on the raw post-tests. Base R will state the comparison as a model comparison, which isolates the Condition test and makes the equality explicit:

HideShow
# The Condition effect as a comparison of full and restricted models.
mancova_reduced      <- lm(cbind(Time2, Time3) ~ Time1, data = df_longitudinal)
mancova_gain_reduced <- lm(cbind(Gain1, Gain2) ~ Time1, data = df_longitudinal)

post_test_route <- anova(mancova_reduced, mancova_model, test = "Pillai")
gain_score_route <- anova(mancova_gain_reduced, mancova_gain_model, test = "Pillai")

post_test_route
HideShow
Analysis of Variance Table

Model 1: cbind(Time2, Time3) ~ Time1
Model 2: cbind(Time2, Time3) ~ Condition + Time1
  Res.Df Df Gen.var.   Pillai approx F num Df den Df  Pr(>F)  
1     98      362.75                                          
2     97 -1   354.75 0.063026   3.2288      2     96 0.04395 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
gain_score_route
HideShow
Analysis of Variance Table

Model 1: cbind(Gain1, Gain2) ~ Time1
Model 2: cbind(Gain1, Gain2) ~ Condition + Time1
  Res.Df Df Gen.var.   Pillai approx F num Df den Df  Pr(>F)  
1     98      362.75                                          
2     97 -1   354.75 0.063026   3.2288      2     96 0.04395 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
# The two routes give the same test, to numerical precision.
all.equal(post_test_route[["approx F"]], gain_score_route[["approx F"]])
HideShow
[1] TRUE

The two analyses give the same Pillai statistic, the same FF, and the same pp value, exactly as the book says they must (p. 823). Some researchers prefer the gain-score form because it makes the question about change explicit, and because it lends itself to testing change within each group separately.

14.12 — Power Analysis and Sample Size Planning

In this section, we transition to sample size planning for the multivariate approach to within-subjects and mixed designs. When sphericity is violated (as is common in longitudinal data), traditional univariate power formulas break down.

While the textbook relies on SAS’s proc glmpower to evaluate these matrices analytically, we can leverage R’s computational flexibility to automate this via Monte Carlo simulation. This approach allows us to define any means and covariance structure, simulate thousands of experiments in seconds, and empirically calculate statistical power (the proportion of simulations that correctly reject the null hypothesis).

14.12.1 — Designs with Two Within-Subjects Factors

Let’s test the 2×32 \times 3 within-subjects design. The textbook asks: if we want power of .80 (α=.05\alpha = .05) to detect the AA main effect, the BB main effect, and the A×BA \times B interaction, given the cell means of Table 14.15, the correlation matrix of Table 14.16, and a population standard deviation of 20 in each cell, how many participants do we need?

The GLMPOWER output summarized on p. 825 gives these required total sample sizes for the multivariate test: * Factor A: 54 participants * Factor B: 20 participants * A ×\times B Interaction: 27 participants

Let’s write a simulation function to check that N=27N = 27 yields approximately .80 power for the interaction.

HideShow
# MASS (mvrnorm) is loaded above.

# Define Population Parameters: the cell means of Table 14.15 (p. 824), in the
# order A1B1, A1B2, A1B3, A2B1, A2B2, A2B3, and the correlations of
# Table 14.16 (p. 825).
mu_2x3 <- c(100, 118, 109, 114, 118, 116)
sd_2x3 <- 20
cor_matrix_2x3 <- matrix(c(
  1.0, 0.6, 0.6, 0.4, 0.3, 0.3,
  0.6, 1.0, 0.6, 0.3, 0.4, 0.3,
  0.6, 0.6, 1.0, 0.3, 0.3, 0.4,
  0.4, 0.3, 0.3, 1.0, 0.6, 0.6,
  0.3, 0.4, 0.3, 0.6, 1.0, 0.6,
  0.3, 0.3, 0.4, 0.6, 0.6, 1.0
), nrow=6, byrow=TRUE)

# Convert correlation matrix to covariance matrix
sigma_2x3 <- cor_matrix_2x3 * (sd_2x3^2)

# Simulation Function for 2x3 Within-Subjects Interaction
sim_power_interaction <- function(n, iterations = 2000) {
  p_values <- numeric(iterations)
  
  for(i in 1:iterations) {
    # Generate data for n participants
    Y <- mvrnorm(n, mu = mu_2x3, Sigma = sigma_2x3)
    
    # To test the AxB interaction via the multivariate approach, 
    # we create interaction D-variables (Difference of Differences)
    # A difference (A1 - A2) across the B contrasts (B1-B2, B2-B3)
    D1 <- (Y[,1] - Y[,4]) - (Y[,2] - Y[,5]) # A(1-2) at B(1-2)
    D2 <- (Y[,2] - Y[,5]) - (Y[,3] - Y[,6]) # A(1-2) at B(2-3)
    
    # MANOVA testing if the grand mean of these D variables is 0
    # The intercept p-value is the interaction test!
    fit <- manova(cbind(D1, D2) ~ 1)
    
    # Extract Pillai's trace p-value for the intercept
    p_values[i] <- summary(fit, intercept = TRUE)$stats["(Intercept)", "Pr(>F)"]
  }
  
  # Power is the proportion of significant tests
  return(mean(p_values < 0.05))
}

# Test the power for N = 27, the book's answer for the interaction.
set.seed(113)
power_N27 <- sim_power_interaction(n = 27)
cat("Simulated Power for AxB Interaction at N = 27:", power_N27, "\n")
HideShow
Simulated Power for AxB Interaction at N = 27: 0.8055 

The simulation returns a power of 80.6% at N=27N = 27, which is the sample size the book’s analytic calculation gives for power of .80 (p. 825). Two routes, two sets of assumptions about how the computation is done, one answer.

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

Now we look at a mixed design: 2 groups (between-subjects) measured on 4 occasions (within-subjects), with the cell means of Table 14.18 and the correlations of Table 14.19 (both p. 828) and a population standard deviation of 10. The GLMPOWER output on p. 829 reports that the multivariate test of the omnibus interaction needs a total NN of 212, while a test of the condition by linear trend interaction needs only 174.

Let’s simulate the power for the linear trend contrast at N=174N = 174 (which means n=87n = 87 per group). We can do this efficiently in R by applying the contrast weights directly to the simulated data.

HideShow
# Define Parameters: cell means from Table 14.18 and correlations from
# Table 14.19 (both p. 828).
mu_cond1 <- c(104, 108, 110, 112)
mu_cond2 <- c(100, 102, 102, 104)
sd_2x4 <- 10

cor_matrix_2x4 <- matrix(c(
  1.00, 0.60, 0.54, 0.49,
  0.60, 1.00, 0.60, 0.54,
  0.54, 0.60, 1.00, 0.60,
  0.49, 0.54, 0.60, 1.00
), nrow=4, byrow=TRUE)

sigma_2x4 <- cor_matrix_2x4 * (sd_2x4^2)

# Linear Contrast Simulation
sim_linear_trend_power <- function(n_per_group, iterations = 2000) {
  p_values <- numeric(iterations)
  linear_weights <- c(-3, -1, 1, 3) # Appendix Table A.10, as on p. 829
  
  for(i in 1:iterations) {
    # Generate data
    Y1 <- mvrnorm(n_per_group, mu = mu_cond1, Sigma = sigma_2x4)
    Y2 <- mvrnorm(n_per_group, mu = mu_cond2, Sigma = sigma_2x4)
    
    # Apply linear contrast to each subject's scores
    # This reduces the 4 timepoints down to a single "Linear Slope" score
    slope1 <- Y1 %*% linear_weights 
    slope2 <- Y2 %*% linear_weights
    
    # Test if the groups differ on this slope (Interaction Contrast!)
    fit <- t.test(slope1, slope2, var.equal = TRUE)
    p_values[i] <- fit$p.value
  }
  
  return(mean(p_values < 0.05))
}

# Test power for Total N = 174 (n = 87 per group)
set.seed(113)
power_linear <- sim_linear_trend_power(n_per_group = 87)
cat("Simulated Power for Linear Trend Interaction at Total N=174:", power_linear, "\n")
HideShow
Simulated Power for Linear Trend Interaction at Total N=174: 0.8005 

The simulation returns a power of 80% at a total NN of 174, the sample size the book’s calculation gives for power of .80 (p. 829). This returns us to a recurring theme in experimental design: specificity buys statistical power.

Testing a broad omnibus interaction requires a larger sample (N=212N = 212) because the test has to look for any possible pattern of differences across the four occasions. By collapsing those occasions into a single linear slope with contrast weights, we focus all the power on one targeted question: do the linear trajectories differ? That focused test reaches .80 power with 38 fewer participants.

Comparing analysis approaches: repeated measures versus MANCOVA

The chapter closes with a demonstration of statistical efficiency. For a longitudinal randomized design (baseline plus three post-tests) with the population means of Table 14.21, a standard 2×42 \times 4 analysis treating baseline as a level of time has power of only .413 to detect the group by time interaction, while a MANCOVA on the three post-tests with baseline as the covariate has power of about .63 (both on p. 831).

Let’s reproduce that comparison by simulating the design with exactly 50 participants (n=25n = 25 per group) and calculating the empirical power of both analyses head to head.

HideShow
# Parameters for Longitudinal Design: population means from Table 14.21 and
# the correlation matrix on p. 830.
mu_ctrl <- c(50, 51, 51, 52)
mu_trt  <- c(50, 56, 58, 56)
sd_long <- 10

cor_long <- matrix(c(
  1.00, 0.40, 0.35, 0.30,
  0.40, 1.00, 0.40, 0.35,
  0.35, 0.40, 1.00, 0.40,
  0.30, 0.35, 0.40, 1.00
), nrow=4, byrow=TRUE)

sigma_long <- cor_long * (sd_long^2)

# Head-to-Head Simulation
sim_mancova_vs_rm <- function(n_per_group=25, iterations = 2000) {
  p_val_rm <- numeric(iterations)
  p_val_mancova <- numeric(iterations)
  
  Condition <- factor(rep(c("Control", "Treatment"), each = n_per_group))
  
  for(i in 1:iterations) {
    Y_ctrl <- mvrnorm(n_per_group, mu = mu_ctrl, Sigma = sigma_long)
    Y_trt  <- mvrnorm(n_per_group, mu = mu_trt, Sigma = sigma_long)
    Y_all  <- rbind(Y_ctrl, Y_trt)
    
    # Model 1: Repeated Measures ANOVA (Multivariate approach)
    # Tested by comparing groups on D variables from baseline
    D1 <- Y_all[,2] - Y_all[,1]
    D2 <- Y_all[,3] - Y_all[,1]
    D3 <- Y_all[,4] - Y_all[,1]
    fit_rm <- manova(cbind(D1, D2, D3) ~ Condition)
    p_val_rm[i] <- summary(fit_rm)$stats["Condition", "Pr(>F)"]
    
    # Model 2: MANCOVA 
    # Predict Post-tests from Condition, covarying Baseline (Y[,1])
    Y2 <- Y_all[,2]; Y3 <- Y_all[,3]; Y4 <- Y_all[,4]; Y1 <- Y_all[,1]
    fit_mancova <- manova(cbind(Y2, Y3, Y4) ~ Condition + Y1)
    p_val_mancova[i] <- summary(fit_mancova)$stats["Condition", "Pr(>F)"]
  }
  
  return(c(
    Power_Repeated_Measures = mean(p_val_rm < 0.05),
    Power_MANCOVA = mean(p_val_mancova < 0.05)
  ))
}

# Run the comparison; the book's values are .413 and about .63.
set.seed(113)
power_comparison <- sim_mancova_vs_rm()
print(power_comparison)
HideShow
Power_Repeated_Measures           Power_MANCOVA 
                 0.4060                  0.6265 

The simulation estimates power as 0.406 for the interaction and 0.626 for MANCOVA. The interaction compares changes from baseline. MANCOVA compares post-test means at a common baseline and assumes the same baseline slope in both groups for each outcome. For Table 14.21, base R can also evaluate the noncentral FF probabilities analytically, averaging over chance baseline imbalance for MANCOVA. The resulting powers are .4130 and .6355, respectively, consistent with the book’s GLIMMPSE discussion on p. 831.

Neither value is a comfortable place to run a study from, which is the book’s point in using this example: the MANCOVA is the better analysis of the two, and a sample of 50 is still too small for either.

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

Chapter 15: An Introduction to Mixed-Effects Models: Within-Subjects Designs

Open the separate reading

Code
Results
On this page

What these notes cover

Chapter 15 introduces mixed-effects (multilevel) models for within-subjects data. Compared with the traditional univariate ANOVA of Chapter 11, the mixed-effects approach:

  • Handles missing observations at any time point (no listwise deletion).
  • Allows the variance-covariance structure of the within-subjects factor to be modeled rather than assumed (compound symmetry, unstructured, AR(1), and so on).
  • Estimates fixed effects by restricted maximum likelihood (REML) and reports the random part of the model as variances and covariances rather than as per-person effects.

Every analysis below is worked first in base R or in the package a reader is likeliest to already know — aov(), lm(), anova(), lme4::lmer(), nlme::gls() — with the corresponding DMAR call shown alongside it, labelled.

The book’s results come from SAS PROC MIXED. Where R and PROC MIXED differ it is almost always in the denominator degrees of freedom, which the two programs determine by different rules; the parameter estimates, the variance components, and the FF statistics themselves agree, and those are the quantities confirmed against the book below.

Chapter 1 covers the R groundwork these notes take for granted: installing packages from CRAN, loading them, and the way the book’s data sets are named. This chapter draws on one of them — chapter_15_table_1, the hypothetical McCarthy data of Table 15.1.

HideShow
# Load all of the packages used.
library(tidyverse)      # data wrangling and plotting (dplyr, ggplot2, and friends)
library(DMAR)           # design, measurement, and analysis
library(AMCP)           # the textbook's data sets
library(broom.mixed)    # tidy mixed-model output into data frames
library(lme4)           # fit mixed-effects models
library(lmerTest)       # degrees of freedom and p-values for lmer fixed effects
library(nlme)           # mixed models with flexible covariance structures (gls/lme)
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables
library(sjPlot)         # tab_model(): mixed-model tables, including the ICC

15.5 — Within-Subjects Designs

15.5.2 — Models for Longitudinal Data

The data are McCarthy scores for 12 children, each measured at 30, 36, 42, and 48 months. The book stores them one column per time point (Table 15.1), and chapter_15_table_1 in AMCP carries that layout unchanged.

HideShow
data(chapter_15_table_1)
mcc_wide <- chapter_15_table_1 |>
  as_tibble() |>
  mutate(subject = factor(row_number()))
mcc_wide
HideShow
# A tibble: 12 × 5
   Months30 Months36 Months42 Months48 subject
      <int>    <int>    <int>    <int> <fct>  
 1      108       96      110      122 1      
 2      103      117      127      133 2      
 3       96      107      106      107 3      
 4       84       85       92       99 4      
 5      118      125      125      116 5      
 6      110      107       96       91 6      
 7      129      128      123      128 7      
 8       90       84      101      113 8      
 9       84      104      100       88 9      
10       96      100      103      105 10     
11      105      114      105      112 11     
12      113      117      132      130 12     
HideShow
#> the 12 x 4 block of scores matches Table 15.1, book p. 863

# The marginal means printed in the last column and the last row of Table 15.1.
rowMeans(chapter_15_table_1)
HideShow
 [1] 109 120 104  90 121 101 127  97  94 101 109 123
HideShow
#> 109 120 104 90 121 101 127 97 94 101 109 123 — the subject marginal means
#> of Table 15.1, book p. 863

colMeans(chapter_15_table_1)
HideShow
Months30 Months36 Months42 Months48 
     103      107      110      112 
HideShow
#> 103 107 110 112 — the occasion means of Table 15.1, book p. 863

mean(as.matrix(chapter_15_table_1))
HideShow
[1] 108
HideShow
#> 108 — the grand mean of Table 15.1, book p. 863

The mixed-effects functions need one row per observation, so the next step is the reshape. Time is carried two ways: Months, a four-level factor for the cell-means (ANOVA) models, and month_c, the number of months since the first wave, for the growth models. Section 15.6.8 recodes month as 0, 6, 12, and 18 for exactly this purpose (book p. 882): putting zero at the first wave makes the growth-model intercept the population mean at 30 months. The level labels are read out of the column names rather than assigned positionally, so factor() is left to do nothing but fix the order of the levels.

HideShow
mcc_long <- mcc_wide |>
  pivot_longer(starts_with("Months"), names_to = "wave", values_to = "Score") |>
  mutate(
    months  = as.integer(str_remove(wave, "Months")),  # 30, 36, 42, 48
    month_c = months - 30,                             # months since the first wave
    Months  = factor(months, levels = c(30, 36, 42, 48))
  ) |>
  select(subject, Months, months, month_c, Score)
mcc_long
HideShow
# A tibble: 48 × 5
   subject Months months month_c Score
   <fct>   <fct>   <int>   <dbl> <int>
 1 1       30         30       0   108
 2 1       36         36       6    96
 3 1       42         42      12   110
 4 1       48         48      18   122
 5 2       30         30       0   103
 6 2       36         36       6   117
 7 2       42         42      12   127
 8 2       48         48      18   133
 9 3       30         30       0    96
10 3       36         36       6   107
# ℹ 38 more rows

Two pairs of children share the same marginal mean — subjects 1 and 11 at 109, and subjects 6 and 10 at 101. The book notes this on p. 878, where it explains why only ten distinct fitted trajectories appear in Figure 15.3.

HideShow
rowMeans(chapter_15_table_1) |> table() |> (\(x) x[x > 1])()
HideShow

101 109 
  2   2 
HideShow
#> 101 and 109 each occur twice — the two tied pairs noted on book p. 878

15.5.3 — Review of the ANOVA Mixed-Model Approach

Before any mixed-effects model, the book reviews the Chapter 11 analysis of these same data: the omnibus FF for the within-subjects factor is 𝑀𝑆A/𝑀𝑆A×S\mathit{MS}_{A}/\mathit{MS}_{A \times S}, which in base R is the within-subject stratum of aov() with an Error(subject) term.

HideShow
aov_fit <- aov(Score ~ Months + Error(subject), data = mcc_long)
summary(aov_fit)
HideShow

Error: subject
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals 11   6624   602.2               

Error: Within
          Df Sum Sq Mean Sq F value Pr(>F)  
Months     3    552  184.00   3.027 0.0432 *
Residuals 33   2006   60.79                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Months: SS 552, df 3, MS 184.00, F = 3.03, p = .0432 — matches book p. 863,
#> and the "timecat" line of Table 15.2, book p. 871
#> Residuals: SS 2006, df 33, MS 60.79 — the "Error" line of Table 15.2, p. 871
#> subject stratum: SS 6624, df 11, MS 602.18 — the "id" line of Table 15.2,
#> book p. 871

The same omnibus test written as an APA-style table, with sums of squares, df, FF, pp, and partial η2\eta^2. The table is built with gt, which formats properly in HTML.

HideShow
within_tbl <- summary(aov_fit)[["Error: Within"]][[1L]]
ss_res     <- within_tbl["Residuals", "Sum Sq"]   # error SS, for partial eta^2

tibble(
  Source = rownames(within_tbl),
  SS     = within_tbl[["Sum Sq"]],
  df     = within_tbl[["Df"]],
  MS     = within_tbl[["Mean Sq"]],
  Fstat  = within_tbl[["F value"]],
  p      = within_tbl[["Pr(>F)"]]
) |>
  mutate(
    # Partial eta-squared: the effect's share of effect-plus-error variance.
    peta = if_else(Source == "Residuals", NA_real_, SS / (SS + ss_res))
  ) |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("**Within-subjects analysis of variance** for McCarthy score")) |>
  cols_align(align = "center", columns = -Source)
Within-subjects analysis of variance for McCarthy score
Source SS df MS F p Partial η2
Months 552.00 3 184.00 3.03 0.0432 0.216
Residuals 2,006.00 33 60.79


15.6 — Mixed-Effects Models

15.6.2 — An Example of Maximum Likelihood Estimation

The chapter motivates maximum likelihood with four observed scores (3.0, 4.1, 4.3, 4.6) drawn from a normal distribution with known standard deviation 1. For any candidate mean μ\mu, the likelihood of the sample is the product of the four normal densities. Graphing that product over a range of μ\mu shows it peaks at the sample mean, which is the maximum likelihood estimate.

HideShow
obs <- c(3.0, 4.1, 4.3, 4.6)        # the four observed scores, book p. 865
mu  <- seq(2, 6, length.out = 400)  # candidate values for the mean

# Likelihood is the product of the four normal densities (sigma = 1) at each mu.
lik <- vapply(mu, function(m) prod(dnorm(obs, mean = m, sd = 1)), numeric(1))
lik_df <- data.frame(mu = mu, likelihood = lik)
mle    <- mean(obs)                 # the value of mu that maximizes the likelihood
mle
HideShow
[1] 4
HideShow
#> 4.0 — matches the maximum likelihood estimate on book p. 866

ggplot(lik_df, aes(mu, likelihood)) +
  geom_line(color = "black", linewidth = 1) +
  geom_vline(xintercept = mle, color = "#0C2340",
             linetype = "dashed", linewidth = 0.7) +
  annotate("text", x = mle + 0.3, y = max(lik_df$likelihood),
           label = sprintf("hat(italic('μ')) == '%.1f'", mle), parse = TRUE,
           color = "#0C2340", hjust = 0, vjust = 0.5, size = 3.3) +
  labs(title = "Figure 15.1. Likelihood as a function of the mean",
       x = expression("Candidate population mean"~italic("μ")),
       y = "Likelihood")
Figure 15.1. Likelihood of the sample data as a function of the population mean \(\mu\).

Figure 15.1. Likelihood of the sample data as a function of the population mean μ\mu.

HideShow
#> reproduces Figure 15.1, book p. 867

15.6.4 — Numerical Example

The ANOVA approach first (Table 15.2)

Table 15.2 is the PROC GLM analysis of these data, which treats subjects as just another fixed classification. In base R that is an ordinary two-factor lm() with no interaction, and anova() gives the same partition.

HideShow
fit_glm <- lm(Score ~ subject + Months, data = mcc_long)
anova(fit_glm)
HideShow
Analysis of Variance Table

Response: Score
          Df Sum Sq Mean Sq F value    Pr(>F)    
subject   11   6624  602.18  9.9063 1.314e-07 ***
Months     3    552  184.00  3.0269   0.04322 *  
Residuals 33   2006   60.79                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> subject: SS 6624, df 11, MS 602.18, F = 9.91 — matches Table 15.2, book p. 871
#> Months:  SS  552, df  3, MS 184.00, F = 3.03, p = .0432 — Table 15.2, p. 871
#> Residuals: SS 2006, df 33, MS 60.79 — Table 15.2, p. 871

# The overall "Model" line and the fit summary SAS prints above the source table.
summary(fit_glm)$r.squared
HideShow
[1] 0.7815291
HideShow
#> 0.781529 — the R-Square of Table 15.2, book p. 871

sigma(fit_glm)
HideShow
[1] 7.796658
HideShow
#> 7.796658 — the Root MSE of Table 15.2, book p. 871
The mixed-effects approach (Table 15.3)

A single random intercept for subject imposes a compound-symmetry structure on the four repeated scores: every pair of time points is assumed to have the same covariance. This is the mixed-effects equivalent of the traditional univariate within-subjects ANOVA just fit.

HideShow
fit_cs <- lmer(Score ~ Months + (1 | subject), data = mcc_long)
summary(fit_cs)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Score ~ Months + (1 | subject)
   Data: mcc_long

REML criterion at convergence: 340.8

Scaled residuals: 
     Min       1Q   Median       3Q      Max 
-1.88627 -0.44709 -0.09063  0.53924  1.70501 

Random effects:
 Groups   Name        Variance Std.Dev.
 subject  (Intercept) 135.35   11.634  
 Residual              60.79    7.797  
Number of obs: 48, groups:  subject, 12

Fixed effects:
            Estimate Std. Error      df t value Pr(>|t|)    
(Intercept)  103.000      4.043  18.117  25.477 1.22e-15 ***
Months36       4.000      3.183  33.000   1.257  0.21769    
Months42       7.000      3.183  33.000   2.199  0.03498 *  
Months48       9.000      3.183  33.000   2.828  0.00791 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
         (Intr) Mnth36 Mnth42
Months36 -0.394              
Months42 -0.394  0.500       
Months48 -0.394  0.500  0.500
HideShow
anova(fit_cs)
HideShow
Type III Analysis of Variance Table with Satterthwaite's method
       Sum Sq Mean Sq NumDF DenDF F value  Pr(>F)  
Months    552     184     3    33  3.0269 0.04322 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> subject variance 135.35, residual variance 60.79 — the two "Covariance
#> Parameter Estimates" of Table 15.3, book p. 874
#> Months: F = 3.03 on 3 and 33 df, p = .0432 — the "Type 3 Tests of Fixed
#> Effects" line of Table 15.3, book p. 874 (and identical to the ANOVA above)

The fixed-effect estimates in Table 15.3 are expressed against the last time point, because PROC GLM and PROC MIXED fix the effect of the final level at zero. R’s default treatment contrasts use the first level instead, so to read the book’s −9-9, −5-5, −2-2 straight off the output, make 48 months the reference level.

HideShow
mcc_ref48 <- mcc_long |> mutate(Months = relevel(Months, ref = "48"))
summary(lmer(Score ~ Months + (1 | subject), data = mcc_ref48))$coefficients
HideShow
            Estimate Std. Error      df    t value     Pr(>|t|)
(Intercept)      112   4.042858 18.1174 27.7031773 2.763710e-16
Months30          -9   3.182972 33.0000 -2.8275458 7.911329e-03
Months36          -5   3.182972 33.0000 -1.5708588 1.257555e-01
Months42          -2   3.182972 33.0000 -0.6283435 5.341039e-01
HideShow
#> Intercept 112.00 (SE 4.0429, t = 27.70); contrasts -9, -5, -2, each with
#> SE 3.1830 and t of -2.83, -1.57, -0.63 — match Table 15.3, book p. 874.
#> (The denominator df differ: lmerTest reports Satterthwaite values, PROC
#> MIXED the containment values of 11 and 33.)

The book stresses that how the random part is specified changes the test of the fixed part. Dropping the random intercept altogether treats the 48 scores as if they came from a between-subjects design.

HideShow
anova(lm(Score ~ Months, data = mcc_long))
HideShow
Analysis of Variance Table

Response: Score
          Df Sum Sq Mean Sq F value Pr(>F)
Months     3    552  184.00  0.9381 0.4304
Residuals 44   8630  196.14               
HideShow
#> F = 0.94 — matches the value the book reports on p. 875 for the model with
#> the random effect omitted. Its residual variance, 196.14, is the total
#> variance the compound-symmetry model splits into 135.35 + 60.7879, the sum
#> the book computes on p. 910.
Confidence intervals on the variance components

confint() on the fitted lmer object gives profile-likelihood intervals, on the standard-deviation scale.

HideShow
confint(fit_cs, method = "profile", signames = FALSE)
HideShow
                            2.5 %     97.5 %
sd_(Intercept)|subject  7.3238254  18.257258
sigma                   6.0237150   9.587055
(Intercept)            95.0042559 110.995745
Months36               -2.1358536  10.135854
Months42                0.8641464  13.135854
Months48                2.8641464  15.135854

For intervals on the variances themselves, DMAR implements the Burdick–Graybill modified-large-sample method, the generalizability-theory standard, computed from the two mean squares of the balanced ANOVA. It returns an interval for each component and for the intraclass correlation, on the variance scale rather than the standard-deviation scale of confint().

HideShow
classical <- summary(aov_fit)
between   <- classical[[1L]][[1L]]    # the subject stratum
within_s  <- classical[[2L]][[1L]]    # the within-subject stratum

variance_components_mls(
  ms_between = between[["Mean Sq"]][1],
  ms_within  = within_s[["Mean Sq"]][nrow(within_s)],
  df_between = between[["Df"]][1],
  df_within  = within_s[["Df"]][nrow(within_s)],
  n          = nlevels(mcc_long$Months),   # observations per subject
  conf_level = 0.95
)
term value
sigma2_between 135.348
sigma2_between_ci_lower 59.443
sigma2_between_ci_upper 418.430
sigma2_within 60.788
sigma2_within_ci_lower 39.547
sigma2_within_ci_upper 105.320
icc 0.690
icc_ci_lower 0.361
icc_ci_upper 0.914

Confidence level: 95%

HideShow
#> sigma2_between 135.348 and sigma2_within 60.788 agree with the 135.35 and
#> 60.7879 of Table 15.3, book p. 874; the intervals around them are DMAR's
#> addition, not something the book's table reports.
The intraclass correlation

Because the compound-symmetry model treats the repeated scores as nested within subjects, the proportion of variance attributable to subjects is an intraclass correlation, and it is also the common correlation the model imposes on every pair of time points. By hand it is the between-subject share of total variance.

HideShow
varcomps  <- VarCorr(fit_cs) |> as.data.frame()
v_between <- varcomps$vcov[varcomps$grp == "subject"]
v_within  <- varcomps$vcov[varcomps$grp == "Residual"]
v_between / (v_between + v_within)
HideShow
[1] 0.6900734
HideShow
#> 0.6901 — the common correlation the compound-symmetry model reports in the
#> estimated correlation matrix of Table 15.11, book p. 909

In DMAR, icc_lmer() reads the same quantity directly off the fitted lmer object and reports a confidence interval with it.

HideShow
icc_lmer(fit_cs, conf_level = 0.95)
term value
icc 0.690
sigma2_between 135.348
sigma2_within 60.788
total_variance 196.136
ci_lower 0.394
ci_upper 0.868
n_clusters 12
average_cluster_size 4

Confidence level: 95%

HideShow
#> icc 0.690 with sigma2_between 135.348 and sigma2_within 60.788 — the same
#> three numbers computed by hand just above. Its total_variance of 196.136 is
#> the 196.14 the book computes on p. 910.

The point estimate is the same 0.690 three times over, but the two DMAR calls report different 95% intervals for it (0.394 to 0.868 here, 0.361 to 0.914 from variance_components_mls() above). That is not a contradiction: the two functions invert different pivotal quantities — icc_lmer() the exact FF ratio of the two mean squares, variance_components_mls() the Burdick–Graybill modified-large-sample approximation. The book tabulates neither interval, so neither can be checked against it; what can be checked is the estimate, and that agrees.

sjPlot::tab_model() reports that ICC in a formatted model table, next to the fixed effects, the random-effect variances, and the sample sizes. The ICC row near the foot of the table is the 0.69 computed by hand and by icc_lmer() above.

HideShow
tab_model(fit_cs,
          show.icc    = TRUE,    # the intraclass correlation
          show.re.var = TRUE,    # random-effect variances
          dv.labels   = "McCarthy score")
  McCarthy score
Predictors Estimates CI p
(Intercept) 103.00 94.84 – 111.16 <0.001
Months [36] 4.00 -2.42 – 10.42 0.216
Months [42] 7.00 0.58 – 13.42 0.033
Months [48] 9.00 2.58 – 15.42 0.007
Random Effects
σ2 60.79
τ00 subject 135.35
ICC 0.69
N subject 12
Observations 48
Marginal R2 / Conditional R2 0.056 / 0.708

15.6.6 — Graphical Representation of Longitudinal Data

A trajectory plot of the raw data: one line per child, connecting that child’s four observed scores. There is a general tendency for scores to rise with age, but the trajectories are far from parallel, which is exactly the question the later models address — are those departures real individual differences, or merely error?

HideShow
ggplot(mcc_long, aes(months, Score, group = subject)) +
  geom_line(color = "black", alpha = 0.50, linewidth = 0.5) +
  geom_point(color = "black", alpha = 0.70, size = 1.4) +
  scale_x_continuous(breaks = c(30, 36, 42, 48)) +
  labs(title = "Figure 15.2. Observed individual trajectories of McCarthy scores",
       x = "Age (months)", y = "McCarthy score")
Figure 15.2. Observed individual trajectories of McCarthy scores.

Figure 15.2. Observed individual trajectories of McCarthy scores.

HideShow
#> reproduces Figure 15.2, book p. 877. Subject 7 is the trajectory that starts
#> near 130 (129, 128, 123, 128), and subjects 4 and 9 are the two that start
#> at 84 — the children the book uses to orient the reader on p. 876.

15.6.7 — Graphical Representation of the Random Intercept Model

The random-intercept model treats the four occasions as a categorical fixed effect and lets each child differ only in a single random intercept. The fitted (BLUP) trajectories are therefore parallel: every child follows the same average pattern of change, shifted up or down. Only ten distinct lines appear, because the two pairs of children identified earlier share a marginal mean.

HideShow
mcc_long$fit_cs <- predict(fit_cs)   # BLUPs: include the random intercept

tapply(mcc_long$fit_cs, mcc_long$Months, mean)
HideShow
 30  36  42  48 
103 107 110 112 
HideShow
#> 103 107 110 112 — averaging the BLUP trajectories recovers the fixed-effect
#> trajectory, and those are the four values the book reports on p. 879 for the
#> model with the random intercept omitted (a single trajectory). They coincide
#> because the random intercepts average to zero, not because the book is
#> describing this model's per-child predictions.

ggplot(mcc_long, aes(months, fit_cs, group = subject)) +
  geom_line(color = "black", alpha = 0.55, linewidth = 0.6) +
  scale_x_continuous(breaks = c(30, 36, 42, 48)) +
  labs(title = "Figure 15.3. Fitted trajectories, random-intercept model",
       x = "Age (months)", y = "Model-implied McCarthy score")
Figure 15.3. Fitted trajectory plot from the random-intercept model (parallel lines).

Figure 15.3. Fitted trajectory plot from the random-intercept model (parallel lines).

HideShow
#> reproduces Figure 15.3, book p. 879

The increase is not quite linear, as the book points out: each line rises 4 points from 30 to 36 months, 3 points from 36 to 42, and 2 points from 42 to 48.

HideShow
diff(tapply(mcc_long$fit_cs, mcc_long$Months, mean))
HideShow
36 42 48 
 4  3  2 
HideShow
#> 4, 3, 2 — the changes between adjacent occasions described on book p. 878

The restricted model drops the fixed time effect, keeping only the random intercept. Under this null, scores do not change over time, so every child’s fitted trajectory is a flat line at that child’s predicted level. The omnibus test of the time effect is the comparison of these flat lines against the rising parallel lines of Figure 15.3. The heights are shrunken slightly toward the grand mean of 108, because they are best linear unbiased predictions (BLUPs) rather than the raw subject means — a point the book makes in its footnote to Figure 15.4.

HideShow
fit_cs_restricted <- lmer(Score ~ 1 + (1 | subject), data = mcc_long)
mcc_long$fit_restricted <- predict(fit_cs_restricted)  # one flat BLUP level per child

range(mcc_long$fit_restricted)
HideShow
[1]  92.12394 124.75806
HideShow
range(rowMeans(chapter_15_table_1))
HideShow
[1]  90 127
HideShow
#> the BLUP levels run 92.1 to 124.8, inside the 90 to 127 range of the raw
#> subject means of Table 15.1 (book p. 863): shrinkage toward the grand mean

ggplot(mcc_long, aes(months, fit_restricted, group = subject)) +
  geom_line(color = "black", alpha = 0.55, linewidth = 0.6) +
  scale_x_continuous(breaks = c(30, 36, 42, 48)) +
  labs(title = "Figure 15.4. Fitted trajectories, restricted random-intercept model",
       x = "Age (months)", y = "Model-implied McCarthy score")
Figure 15.4. Fitted trajectory plot from the restricted random-intercept model (flat lines).

Figure 15.4. Fitted trajectory plot from the restricted random-intercept model (flat lines).

HideShow
#> reproduces Figure 15.4, book p. 880

15.6.10 — Numerical Example

The compound-symmetry model lets children differ only in their intercept. Adding a random slope for month_c lets each child also change at his or her own rate, and lets the intercept and slope covary. The fixed effects stay the four-level categorical Months (a cell-means specification), so this model and the random-intercept model differ only in their random part — exactly the comparison the book draws between Tables 15.3 and 15.4.

HideShow
fit_ris <- lmer(Score ~ Months + (1 + month_c | subject), data = mcc_long)
summary(fit_ris)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Score ~ Months + (1 + month_c | subject)
   Data: mcc_long

REML criterion at convergence: 336.4

Scaled residuals: 
     Min       1Q   Median       3Q      Max 
-1.81430 -0.47911 -0.05763  0.57397  1.53582 

Random effects:
 Groups   Name        Variance Std.Dev. Corr  
 subject  (Intercept) 168.0183 12.9622        
          month_c       0.3892  0.6239  -0.40 
 Residual              37.4365  6.1185        
Number of obs: 48, groups:  subject, 12

Fixed effects:
            Estimate Std. Error      df t value Pr(>|t|)    
(Intercept)  103.000      4.138  12.289  24.893 6.89e-12 ***
Months36       4.000      2.722  31.803   1.470   0.1515    
Months42       7.000      3.303  22.434   2.119   0.0454 *  
Months48       9.000      4.092  11.859   2.199   0.0485 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
         (Intr) Mnth36 Mnth42
Months36 -0.421              
Months42 -0.465  0.607       
Months48 -0.471  0.595  0.749
HideShow
anova(fit_ris)
HideShow
Type III Analysis of Variance Table with Satterthwaite's method
       Sum Sq Mean Sq NumDF  DenDF F value Pr(>F)
Months 200.07   66.69     3 16.356  1.7814 0.1903
HideShow
#> intercept variance 168.0183, slope variance 0.3892, residual 37.4365 —
#> the book's 168.02, 0.3892, and 37.4364, Table 15.4, book p. 886
#> Months: F = 1.78, no longer significant at .05 — matches the F of Table 15.4,
#> book p. 886

summary() reports the random part as standard deviations and a correlation. The book’s table reports variances and a covariance, which VarCorr() gives in data-frame form.

HideShow
vc_ris <- as.data.frame(VarCorr(fit_ris))
vc_ris
HideShow
       grp        var1    var2        vcov      sdcor
1  subject (Intercept)    <NA> 168.0182777 12.9621865
2  subject     month_c    <NA>   0.3891905  0.6238514
3  subject (Intercept) month_c  -3.2420907 -0.4009274
4 Residual        <NA>    <NA>  37.4365342  6.1185402
HideShow
#> the vcov column, at the book's precision, is 168.02, 0.3892, -3.2421,
#> 37.4365 — the four covariance parameters UN(1,1), UN(2,2), UN(2,1), and
#> Residual of Table 15.4, book p. 886, which prints 168.02, 0.3892, -3.2421,
#> and 37.4364

The covariance is easier to read as a correlation, which is how the book interprets it.

HideShow
vc_ris$vcov[3] / sqrt(vc_ris$vcov[1] * vc_ris$vcov[2])
HideShow
[1] -0.4009274
HideShow
#> -0.40 — the correlation between initial status and rate of change that the
#> book computes from Table 15.4 on p. 886

Allowing individual slopes absorbs variability that the random-intercept model charged to the fixed time effect, which is why the FF drops from 3.03 to 1.78. The two tests use different denominator degrees of freedom: lmerTest’s Satterthwaite value is about 16 here, while PROC MIXED’s containment method reports 22, so the pp values differ slightly even though the FF of 1.78 is the same.

HideShow
anova(fit_ris)[["DenDF"]]
HideShow
[1] 16.35622
HideShow
#> 16.36, against the 22 of Table 15.4 (book p. 886): the same F, a different
#> rule for the denominator df

The two random-effects models side by side, fit statistics at the foot, with modelsummary (each model in its own column):

HideShow
modelsummary(
  list("Random intercept" = fit_cs, "Random intercept + slope" = fit_ris),
  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
)
Random intercept Random intercept + slope
(Intercept) 103.000 103.000
(4.043) (4.138)
Months36 4.000 4.000
(3.183) (2.722)
Months42 7.000 7.000
(3.183) (3.303)
Months48 9.000 9.000
(3.183) (4.092)
SD (Intercept subject) 11.634 12.962
SD (month_c subject) 0.624
Cor (Intercept~month_c subject) -0.401
SD (Observations) 7.797 6.119
Num.Obs. 48 48
AIC 352.8 352.4
BIC 364.0 367.3
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

The same comparison as a gtsummary table, each model under its own spanning header:

HideShow
t_ri  <- tbl_regression(fit_cs,  intercept = TRUE)
t_ris <- tbl_regression(fit_ris, intercept = TRUE)
tbl_merge(list(t_ri, t_ris),
          tab_spanner = c("**Random intercept**", "**Random intercept + slope**"))
Characteristic
Random intercept
Random intercept + slope
Beta 95% CI p-value Beta 95% CI p-value
(Intercept) 103 95, 111 <0.001 103 94, 112 <0.001
Months





    30 — —
— —
    36 4.0 -2.5, 10 0.2 4.0 -1.5, 9.5 0.2
    42 7.0 0.52, 13 0.035 7.0 0.16, 14 0.045
    48 9.0 2.5, 15 0.008 9.0 0.07, 18 0.048
Abbreviation: CI = Confidence Interval

15.6.11 — Graphical Representation of a Model with Random Slope and Intercept

Adding a random slope for (centered) age lets each child change at his or her own rate, while the fixed effects remain the four-level categorical time. The fitted trajectories now fan out: they are no longer parallel, because the model allows individual differences in slope as well as intercept. The occasion means of the predictions are unchanged, so this model and the random-intercept model describe the same average change but differ in how individuals depart from it.

HideShow
mcc_long$fit_ris <- predict(fit_ris)   # BLUPs: intercept and slope

tapply(mcc_long$fit_ris, mcc_long$Months, mean)
HideShow
 30  36  42  48 
103 107 110 112 
HideShow
#> 103 107 110 112 — the same predicted occasion means the book gives for this
#> model on p. 887

ggplot(mcc_long, aes(months, fit_ris, group = subject)) +
  geom_line(color = "black", alpha = 0.55, linewidth = 0.6) +
  scale_x_continuous(breaks = c(30, 36, 42, 48)) +
  labs(title = "Figure 15.5. Fitted trajectories, random intercept and slope model",
       x = "Age (months)", y = "Model-implied McCarthy score")
Figure 15.5. Fitted trajectory plot from the random intercept and slope model.

Figure 15.5. Fitted trajectory plot from the random intercept and slope model.

HideShow
#> reproduces Figure 15.5, book p. 888

15.6.14 — Straight-Line Change Model

When time is treated as quantitative, a more parsimonious model parameterizes change as a linear slope that may vary across subjects. Each fixed effect (intercept, slope) is paired with a corresponding random effect, the structure the book calls a growth-curve model. Time is the centered month_c (0 at the first wave), so the intercept is the population mean at 30 months and the slope is points gained per month.

HideShow
fit_growth <- lmer(Score ~ month_c + (month_c | subject), data = mcc_long)
summary(fit_growth)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Score ~ month_c + (month_c | subject)
   Data: mcc_long

REML criterion at convergence: 349.1

Scaled residuals: 
     Min       1Q   Median       3Q      Max 
-1.79184 -0.43847  0.00417  0.64189  1.68327 

Random effects:
 Groups   Name        Variance Std.Dev. Corr  
 subject  (Intercept) 169.8529 13.0328        
          month_c       0.4038  0.6354  -0.41 
 Residual              34.8162  5.9005        
Number of obs: 48, groups:  subject, 12

Fixed effects:
            Estimate Std. Error       df t value Pr(>|t|)    
(Intercept) 103.5000     4.0231  11.0001  25.726 3.54e-11 ***
month_c       0.5000     0.2231  10.9998   2.241   0.0466 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
        (Intr)
month_c -0.475
HideShow
#> fixed effects: intercept 103.50 (SE 4.0231, t = 25.73) and slope 0.5000
#> (SE 0.2231, t = 2.24, p = .0466), both on 11 df — match the "Solution for
#> Fixed Effects" of Table 15.6, book p. 894

as.data.frame(VarCorr(fit_growth))
HideShow
       grp        var1    var2        vcov      sdcor
1  subject (Intercept)    <NA> 169.8528972 13.0327625
2  subject     month_c    <NA>   0.4037638  0.6354241
3  subject (Intercept) month_c  -3.3730646 -0.4073095
4 Residual        <NA>    <NA>  34.8161554  5.9005216
HideShow
#> the vcov column, at the book's precision, is 169.85, 0.4038, -3.3731,
#> 34.8162 — the UN(1,1), UN(2,2), UN(2,1), and Residual estimates of
#> Table 15.6, book p. 894, which prints 169.85, 0.4037, -3.3731, and 34.8167.
#> The slope variance and the residual differ from SAS in the fourth decimal,
#> a convergence tolerance rather than a different model. The -0.41 correlation
#> that summary() prints is implied by these estimates; the book's table prints
#> the covariance instead.

anova(fit_growth)
HideShow
Type III Analysis of Variance Table with Satterthwaite's method
        Sum Sq Mean Sq NumDF DenDF F value  Pr(>F)  
month_c  174.9   174.9     1    11  5.0236 0.04659 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F = 5.02 on 1 and 11 df, p = .0466 — the "Type 3 Tests of Fixed Effects"
#> line of Table 15.6, book p. 894, and the linear-trend contrast of
#> Table 15.5, book p. 891
Confidence intervals on the fixed effects

The book forms the 95% interval for the slope from the tt distribution on 11 df, whose critical value Appendix Table A.1 gives as 2.20, and reports 0.01 to 0.99.

HideShow
qt(0.975, df = 11)
HideShow
[1] 2.200985
HideShow
#> 2.201 — the critical value of 2.20 the book reads from Table A.1, p. 894

b  <- fixef(fit_growth)["month_c"]
se <- sqrt(vcov(fit_growth)["month_c", "month_c"])
b + c(lower = -1, upper = 1) * qt(0.975, df = 11) * se
HideShow
      lower       upper 
0.008999869 0.991000131 
HideShow
#> 0.009 to 0.991, the 0.01 to 0.99 interval reported on book p. 894

broom.mixed builds the same interval without the hand arithmetic, because it takes the degrees of freedom from the fitted model rather than assuming a normal approximation.

HideShow
generics::tidy(fit_growth, effects = "fixed", conf.int = TRUE, conf.method = "Wald")
HideShow
# A tibble: 2 × 9
  effect term     estimate std.error statistic    df  p.value conf.low conf.high
  <chr>  <chr>       <dbl>     <dbl>     <dbl> <dbl>    <dbl>    <dbl>     <dbl>
1 fixed  (Interc…  103.        4.02      25.7   11.0 3.54e-11 94.6       112.   
2 fixed  month_c     0.500     0.223      2.24  11.0 4.66e- 2  0.00900     0.991
HideShow
#> conf.low 0.009 and conf.high 0.991 for month_c — the same bounds as the hand
#> computation above, and the 0.01 to 0.99 of book p. 894

confint(..., method = "Wald") on a merMod object uses the normal critical value of 1.96 rather than the tt value of 2.20, so its interval is slightly narrower than the book’s. The point estimate and standard error are the same; only the multiplier differs.

HideShow
confint(fit_growth, method = "Wald")
HideShow
                  2.5 %      97.5 %
.sig01               NA          NA
.sig02               NA          NA
.sig03               NA          NA
.sigma               NA          NA
(Intercept) 95.61486478 111.3851352
month_c      0.06276735   0.9372326
HideShow
#> month_c: 0.063 to 0.937 — narrower than the book's 0.01 to 0.99 because the
#> multiplier is 1.96 rather than 2.20

15.6.15 — Graphical Representation of a Growth Curve Model

The straight-line change model treats age as quantitative: a fixed intercept and slope, each paired with a random effect, so every child’s trajectory is an actual straight line. The thin lines are the individual fitted trajectories; the heavy line estimates the population-average trajectory from the fixed effects.

HideShow
# Fitted lines over a fine age grid (linear in age, so any grid recovers the line).
grid <- expand.grid(subject = levels(mcc_long$subject), months = seq(30, 48, by = 1))
grid$month_c <- grid$months - 30
grid$fitted  <- predict(fit_growth, newdata = grid)              # includes random effects

pop <- data.frame(months = seq(30, 48, by = 1))
pop$month_c <- pop$months - 30
pop$fitted  <- predict(fit_growth, newdata = pop, re.form = NA)  # population-average line

ggplot(grid, aes(months, fitted, group = subject)) +
  geom_line(color = "black", alpha = 0.45, linewidth = 0.5) +
  geom_line(data = pop, aes(months, fitted), inherit.aes = FALSE,
            color = "#0C2340", linewidth = 1.4) +
  scale_x_continuous(breaks = c(30, 36, 42, 48)) +
  labs(title = "Figure 15.6. Fitted trajectories, straight-line change model",
       x = "Age (months)", y = "Model-implied McCarthy score")
Figure 15.6. Fitted trajectories from the straight-line change model. The heavy line estimates the population-average trajectory.

Figure 15.6. Fitted trajectories from the straight-line change model. The heavy line estimates the population-average trajectory.

HideShow
#> reproduces Figure 15.6, book p. 895. The population-average line runs from
#> 103.50 at 30 months to 112.50 at 48 months, a gain of 0.50 points per month.

The straight-line change model estimates not just an average slope but a variance of slopes across children. Treating the random slope as normally distributed, the curve below is the estimated population distribution of growth rates: centered at the average slope (the fixed effect, dashed line) with a spread given by the estimated slope standard deviation. Its width is the model’s claim about how much children differ in their rate of change.

HideShow
slope_mean <- as.numeric(fixef(fit_growth)["month_c"])
vc_growth  <- as.data.frame(VarCorr(fit_growth))
slope_sd   <- vc_growth$sdcor[vc_growth$grp  == "subject" &
                              vc_growth$var1 == "month_c" &
                              is.na(vc_growth$var2)]
c(mean = slope_mean, sd = slope_sd)
HideShow
     mean        sd 
0.5000000 0.6354241 
HideShow
#> mean 0.50 and sd 0.64: the slope variance of 0.4037 in Table 15.6 implies a
#> standard deviation of 0.64, as the book notes on p. 896

xx   <- seq(slope_mean - 3.5 * slope_sd, slope_mean + 3.5 * slope_sd,
            length.out = 400)
dens <- data.frame(slope = xx, density = dnorm(xx, slope_mean, slope_sd))

ggplot(dens, aes(slope, density)) +
  geom_area(fill = "#0C2340", alpha = 0.20) +
  geom_line(color = "black", linewidth = 0.9) +
  geom_vline(xintercept = slope_mean, color = "#0C2340",
             linetype = "dashed", linewidth = 0.7) +
  annotate("text", x = slope_mean + slope_sd / 2, y = max(dens$density),
           label = sprintf("Estimated mean = %.2f", slope_mean),
           color = "#0C2340", hjust = 0, vjust = 0.5, size = 3.3) +
  labs(title = "Figure 15.7. Estimated population distribution of slopes",
       subtitle = "Rate of change in McCarthy score per month (straight-line change model)",
       x = "Slope (McCarthy points per month)", y = "Density")
Figure 15.7. Estimated population distribution of slopes from the straight-line change model.

Figure 15.7. Estimated population distribution of slopes from the straight-line change model.

HideShow
#> reproduces Figure 15.7, book p. 896

15.7 — An Alternative Approach and Conceptualization

Instead of building the covariance from random effects, the book’s alternative is to model the residual covariance matrix directly.

The errors a cell-means model leaves behind (Tables 15.7 to 15.9)

The book motivates that move by looking at the errors left by a fixed cell-means model, which in base R are just the residuals of lm(Score ~ Months) laid back out one row per child.

HideShow
errors_wide <- matrix(residuals(lm(Score ~ Months, data = mcc_long)),
                      nrow = 12, byrow = TRUE,
                      dimnames = list(subject = 1:12, months = c(30, 36, 42, 48)))
round(errors_wide)
HideShow
       months
subject  30  36  42  48
     1    5 -11   0  10
     2    0  10  17  21
     3   -7   0  -4  -5
     4  -19 -22 -18 -13
     5   15  18  15   4
     6    7   0 -14 -21
     7   26  21  13  16
     8  -13 -23  -9   1
     9  -19  -3 -10 -24
     10  -7  -7  -7  -7
     11   2   7  -5   0
     12  10  10  22  18
HideShow
#> matches Table 15.7, book p. 903 (subject 1: 5, -11, 0, 10)

Those errors are correlated across occasions, which is the whole problem. Their covariance and correlation matrices are the book’s Tables 15.8 and 15.9, and because the cell-means model only removes column means, they are also the covariance and correlation matrices of the original scores.

HideShow
round(cov(chapter_15_table_1), 2)
HideShow
         Months30 Months36 Months42 Months48
Months30   188.00   154.36   127.36   121.18
Months36   154.36   200.55   143.64    97.45
Months42   127.36   143.64   178.00   168.09
Months48   121.18    97.45   168.09   218.00
HideShow
#> 188.00, 200.55, 178.00, 218.00 on the diagonal and 154.36, 127.36, 121.18,
#> 143.64, 97.45, 168.09 off it — matches Table 15.8, book p. 903

round(cor(chapter_15_table_1), 3)
HideShow
         Months30 Months36 Months42 Months48
Months30    1.000    0.795    0.696    0.599
Months36    0.795    1.000    0.760    0.466
Months42    0.696    0.760    1.000    0.853
Months48    0.599    0.466    0.853    1.000
HideShow
#> 0.795, 0.696, 0.599, 0.760, 0.466, 0.853 — matches Table 15.9, book p. 904
The unstructured model (Table 15.10)

nlme::gls() models that residual covariance matrix directly. An unstructured (UN) matrix frees every variance and every covariance, so it is the most general and the most data-hungry; with balanced data it reproduces the multivariate (Chapter 13) analysis.

HideShow
fit_un <- gls(Score ~ Months,
              data        = mcc_long,
              correlation = corSymm(form = ~ as.integer(Months) | subject),
              weights     = varIdent(form = ~ 1 | Months))
anova(fit_un)
HideShow
Denom. DF: 44 
            numDF  F-value p-value
(Intercept)     1 934.2918  <.0001
Months          3   2.7379  0.0547
HideShow
#> Months: F = 2.74 — matches the default PROC MIXED test of Table 15.10,
#> book p. 906. gls() uses residual (N - p = 44) denominator df, so its p value
#> differs from the book's; the F statistic is the quantity to compare.

round(getVarCov(fit_un), 2)
HideShow
Marginal variance covariance matrix
       [,1]   [,2]   [,3]   [,4]
[1,] 188.00 154.36 127.36 121.18
[2,] 154.36 200.55 143.64  97.46
[3,] 127.36 143.64 178.00 168.09
[4,] 121.18  97.46 168.09 218.00
  Standard Deviations: 13.711 14.162 13.342 14.765 
HideShow
#> 188.00, 154.36, 200.55, 127.36, 143.64, 178.00, 121.18, 97.46, 168.09,
#> 218.00 — the ten UN(i,j) covariance parameter estimates of Table 15.10,
#> book p. 906. The unstructured fit simply recovers the sample covariance
#> matrix of Table 15.8; every cell agrees to within 0.001 of it, which is why
#> the UN(4,2) entry rounds to 97.46 here and to the 97.45 the book prints.

15.7.1 — Additional Covariance Matrix Structures

Compound symmetry (Table 15.11)

Specifying compound symmetry directly, rather than through a random intercept, gives the same model by a different route — a point the book makes explicitly when it notes that the two produce identical information criteria.

HideShow
fit_cs_gls <- gls(Score ~ Months, data = mcc_long,
                  correlation = corCompSymm(form = ~ as.integer(Months) | subject))
coef(fit_cs_gls$modelStruct$corStruct, unconstrained = FALSE)   # the common correlation
HideShow
      Rho 
0.6900734 
HideShow
sigma(fit_cs_gls)^2                                             # the common variance
HideShow
[1] 196.1364
HideShow
anova(fit_cs_gls)
HideShow
Denom. DF: 44 
            numDF  F-value p-value
(Intercept)     1 929.7391  <.0001
Months          3   3.0269  0.0394
HideShow
#> correlation 0.6901 — the common off-diagonal correlation of Table 15.11,
#> book p. 909; F = 3.03, as in Table 15.11
#> variance 196.14 — the sum 135.35 + 60.7879 the book computes on p. 910

round(getVarCov(fit_cs_gls), 2)
HideShow
Marginal variance covariance matrix
       [,1]   [,2]   [,3]   [,4]
[1,] 196.14 135.35 135.35 135.35
[2,] 135.35 196.14 135.35 135.35
[3,] 135.35 135.35 196.14 135.35
[4,] 135.35 135.35 135.35 196.14
  Standard Deviations: 14.005 14.005 14.005 14.005 
HideShow
#> 196.14 on the diagonal and 135.35 everywhere off it — the covariance form of
#> the compound-symmetry model the book describes on book p. 910
A first-order autoregressive structure (Table 15.12)

Compound symmetry assumes every pair of time points correlates equally; in longitudinal data, closer occasions usually correlate more highly. A first-order autoregressive (AR1) structure captures that: adjacent occasions correlate ρ\rho, occasions two apart ρ2\rho^2, and so on.

HideShow
fit_ar1 <- gls(Score ~ Months, data = mcc_long,
               correlation = corAR1(form = ~ as.integer(Months) | subject))
rho <- coef(fit_ar1$modelStruct$corStruct, unconstrained = FALSE)
rho
HideShow
      Phi 
0.8064014 
HideShow
#> 0.8064 — matches the AR(1) estimate of Table 15.12, book p. 911

sigma(fit_ar1)^2
HideShow
[1] 199.4432
HideShow
#> 199.4432, against the 199.45 printed in Table 15.12 (book p. 911). The two
#> estimates differ by 0.007, about 0.003% — a difference between the two
#> programs' convergence tolerances, not between the models.

rho^(1:3)
HideShow
[1] 0.8064014 0.6502833 0.5243894
HideShow
#> 0.8064, 0.6503, 0.5244 — the lag-one, lag-two, and lag-three correlations
#> of the estimated correlation matrix in Table 15.12, book p. 911, which the
#> text rounds to .81, .65, and .52

anova(fit_ar1)
HideShow
Denom. DF: 44 
            numDF  F-value p-value
(Intercept)     1 921.6425  <.0001
Months          3   1.8041  0.1604
HideShow
#> Months: F = 1.80 — matches Table 15.12, book p. 911. As with the
#> unstructured fit, gls() reports a residual-df p value that differs from
#> PROC MIXED's.

15.7.3 — Overview of Broader Model Comparison

Several of these structures are non-nested (AR1 versus compound symmetry, for instance), so they cannot be ranked by a likelihood-ratio test. The book (Table 15.14) instead compares all five full models by information criteria, which penalize fit for the number of parameters.

The one thing to be careful about is which parameters get counted. PROC MIXED counts only the covariance parameters in its penalty, and uses the number of subjects for BIC and the REML residual degrees of freedom for the finite-sample correction. R’s AIC() and BIC() use different conventions, so they return different numbers for the same fit. Spelling the book’s conventions out reproduces Table 15.14 exactly.

HideShow
neg2logL <- function(fit) -2 * as.numeric(logLik(fit))

ic <- tibble(
  Model = c("Random intercept", "Random intercept and slope",
            "Unstructured", "Compound symmetry", "Autoregressive"),
  # REML -2 log likelihood; all five models share the same fixed effects.
  neg2logL = c(neg2logL(fit_cs), neg2logL(fit_ris),
               neg2logL(fit_un), neg2logL(fit_cs_gls), neg2logL(fit_ar1)),
  # Number of covariance parameters, which is what PROC MIXED penalizes.
  q = c(2, 4, 10, 2, 2)
) |>
  mutate(
    AIC  = neg2logL + 2 * q,
    # Finite-sample correction uses the REML residual df, N - (number of fixed effects).
    AICC = AIC + 2 * q * (q + 1) / ((nrow(mcc_long) - 4) - q - 1),
    # BIC uses the number of subjects, not the number of observations.
    BIC  = neg2logL + log(nlevels(mcc_long$subject)) * q
  )

ic |>
  gt() |>
  fmt_number(columns = neg2logL, decimals = 1) |>
  fmt_number(columns = c(AIC, AICC, BIC), decimals = 1) |>
  cols_label(neg2logL = md("&minus;2 log *L*"), q = md("*q*")) |>
  tab_header(title = md("**Information criteria** for the five full models")) |>
  cols_align(align = "center", columns = -Model)
Information criteria for the five full models
Model −2 log L q AIC AICC BIC
Random intercept 340.8 2 344.8 345.0 345.7
Random intercept and slope 336.4 4 344.4 345.4 346.3
Unstructured 325.1 10 345.1 351.8 350.0
Compound symmetry 340.8 2 344.8 345.0 345.7
Autoregressive 333.1 2 337.1 337.4 338.1
HideShow
#> AIC 344.8, 344.4, 345.1, 344.8, 337.1; AICC 345.0, 345.4, 351.8, 345.0,
#> 337.4; BIC 345.7, 346.3, 350.0, 345.7, 338.1 — all fifteen values match
#> Table 15.14, book p. 914

Two of the book’s observations fall straight out of the table. The random intercept and compound symmetry rows are identical, because they are two ways of writing the same model; and all three criteria pick the autoregressive model, which fits nearly as well as the unstructured one with eight fewer parameters.

In DMAR

compare_cov_structures() automates the family in one call. It fits eight structures — independence (IND), compound symmetry (CS) and its heterogeneous form (CSH), first-order autoregressive (AR1) and its heterogeneous form (ARH1), Toeplitz (TOEP) and heterogeneous Toeplitz (TOEPH), and unstructured (UN) — to the same fixed-effects model, and returns each model’s log-likelihood, AIC, BIC, parameter count, and a likelihood-ratio test against the most general (UN) model. That last column is a significance test for the nested comparisons, which the information criteria above do not provide. The comparison uses ML, since the fixed-effects part is held constant across structures, so its log-likelihoods are on a different scale from the REML values tabled above.

HideShow
compare_cov_structures(mcc_long, outcome = "Score",
                       subject = "subject", time = "Months")
structure log_lik AIC BIC n_par LRT_vs_UN_chisq LRT_vs_UN_df LRT_vs_UN_p fit_error
IND -192.712 395.424 404.780 5 45.776 9 < 0.0001 NA
CS -178.357 368.714 379.942 6 17.066 8 0.0294 NA
CSH -177.969 373.938 390.779 9 16.290 5 0.0061 NA
AR1 -174.202 360.404 371.631 6 8.755 8 0.3633 NA
ARH1 -173.982 365.964 382.805 9 8.315 5 0.1397 NA
TOEP -171.858 359.716 374.686 8 4.067 6 0.6676 NA
TOEPH -171.640 365.281 385.864 11 3.632 3 0.3040 NA
UN -169.824 367.649 393.846 14 NA NA NA NA
HideShow
#> CS vs UN: LRT = 17.07 on 8 df, p = .029. The richer UN model fits
#> significantly better than CS, but AR1 fits nearly as well as UN
#> (LRT vs UN p = .36) with eight fewer parameters — the same conclusion the
#> book draws from Table 15.14, book p. 914.

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 15: An Introduction to Mixed-Effects Models: Within-Subjects Designs (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

Chapter 16: An Introduction to Mixed-Effects Models: Nested Designs

Open the separate reading

Code
Results
On this page

Chapter 16 takes up data that are nested: clients within trainees, students within classrooms, classrooms within treatment conditions. Clustering of this kind induces dependence among observations that share a higher-level unit, and the mixed-effects model handles it by estimating the variance of the cluster effect rather than an effect for each cluster. Section 16.4 reviews the ANOVA approach of Chapter 10 on the clinical trainee data, Section 16.5 shows that the mixed-effects analysis reproduces it exactly when nn is equal and then takes over where ANOVA cannot go (unequal nn), and Section 16.6 adds predictors measured at two different levels of the hierarchy: teaching skill, a property of the classroom (level 2), and cognitive ability, a property of the student (level 1). Section 16.7 closes with sample size planning.

These notes build on the prior chapters’ R Code and Instructions, where operational aspects of R and the use of many functions are discussed; here we skip what has already been covered there, including how the AMCP data sets are named (see Chapter 1). This chapter uses two of them: chapter_16_table_1 (the clinical trainee severity ratings, the equal-nn example, which is the Table 10.9 data of Chapter 10) and chapter_16_table_4 (the inductive reasoning study, the unequal-nn example).

HideShow
# Load all of the packages used.
library(dplyr)          # data manipulation
library(ggplot2)        # figures
library(AMCP)           # the textbook's data sets
library(DMAR)           # design, measurement, and analysis
library(broom)          # tidy output from lm/aov into data frames
library(broom.mixed)    # tidy output from lmer into data frames
library(lme4)           # fit mixed-effects models
library(lmerTest)       # p-values and denominator df for lmer fixed effects
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables
library(sjPlot)         # tab_model(): mixed-model tables, including the ICC

16.4 — Review of the ANOVA Approach

The chapter opens with the hypothetical clinical trainee data of Table 10.9, repeated as Table 16.1. Three female and three male clinical psychology graduate trainees were randomly selected, each was randomly assigned four clients to interview, and each trainee assigned a severity rating to each client. Trainees are nested within gender: trainee is a random factor, gender a fixed one.

HideShow
data(chapter_16_table_1)
nest <- chapter_16_table_1 |>
  as_tibble() |>
  mutate(Gender = case_when(Gender == 1 ~ "Male",
                            Gender == 2 ~ "Female")) |>
  mutate(Gender  = factor(Gender, levels = c("Male", "Female")),
         Trainee = factor(Trainee))
nest
HideShow
# A tibble: 24 × 3
   Trainee Gender Severity
   <fct>   <fct>     <int>
 1 1       Male         49
 2 1       Male         40
 3 1       Male         31
 4 1       Male         40
 5 2       Male         42
 6 2       Male         48
 7 2       Male         52
 8 2       Male         58
 9 3       Male         42
10 3       Male         46
# ℹ 14 more rows
HideShow
#> The 24 severity ratings of Table 16.1 — matches book p. 935. Trainee is coded
#> 1 through 6 across both genders (book p. 939), so Trainee is already a unique
#> label for each of the six trainees and needs no further construction.

The book reports the ANOVA test first, so that the mixed-effects result can be compared against it. In base R the nested design is fit with an Error() stratum for trainee: gender is tested against the trainee-within-gender mean square, not against the within-trainee mean square.

HideShow
summary(aov(Severity ~ Gender + Error(Trainee), data = nest))
HideShow

Error: Trainee
          Df Sum Sq Mean Sq F value Pr(>F)  
Gender     1   1176    1176   9.966 0.0343 *
Residuals  4    472     118                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: Within
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals 18    820   45.56               
HideShow
#> F(1, 4) = 9.97, p = .0343 — matches book p. 939 and Table 16.3 (p. 943).
#> MS_B/A = 118 and MS_W = 45.5556 — matches book p. 945.

16.5 — Mixed-Effects Models Analysis for the Simple Nested Design

16.5.1 — Numerical Example: Equal nn

Before any inference, the book looks at the pattern of means (Table 16.2), because the whole logic of the analysis rests on treating the six trainee means as the scores that carry the gender comparison.

HideShow
nest |>
  group_by(Gender, Trainee) |>
  summarise(n = n(), Mean = mean(Severity), .groups = "drop")
HideShow
# A tibble: 6 × 4
  Gender Trainee     n  Mean
  <fct>  <fct>   <int> <dbl>
1 Male   1           4    40
2 Male   2           4    50
3 Male   3           4    48
4 Female 4           4    61
5 Female 5           4    54
6 Female 6           4    65
HideShow
#> Male trainees 40, 50, 48; female trainees 61, 54, 65 — matches Table 16.2
#> (book p. 941) and the text on book p. 940.

nest |>
  group_by(Gender) |>
  summarise(n = n(), Mean = mean(Severity))
HideShow
# A tibble: 2 × 3
  Gender     n  Mean
  <fct>  <int> <dbl>
1 Male      12    46
2 Female    12    60
HideShow
#> 46 for the 12 clients seen by males, 60 for the 12 seen by females —
#> matches book p. 940.

The book makes the point explicitly (p. 940) that with equal nn the mixed-effects pp value is exactly the pp value of a two-sample tt test on those six trainee means. That tt test is worth running, because it shows in one line what the mixed-effects machinery is doing: summarizing at the lowest level, then comparing at the higher one.

HideShow
trainee_means <- nest |>
  group_by(Gender, Trainee) |>
  summarise(Mean = mean(Severity), .groups = "drop")

# These are six independent trainee means, one per trainee, so the comparison is
# an unpaired, equal-variance two-sample test. (The formula method of t.test()
# does not accept a `paired` argument, so independence is stated here instead.)
t.test(
  Mean ~ Gender,
  data        = trainee_means,
  alternative = "two.sided",
  conf.level  = 0.95,
  var.equal   = TRUE
)
HideShow

    Two Sample t-test

data:  Mean by Gender
t = -3.1569, df = 4, p-value = 0.03429
alternative hypothesis: true difference in means between group Male and group Female is not equal to 0
95 percent confidence interval:
 -26.312733  -1.687267
sample estimates:
  mean in group Male mean in group Female 
                  46                   60 
HideShow
#> t = -3.157 on 4 df, p = .0343 — the same p value as the ANOVA above and as
#> the mixed-effects analysis below, exactly as the book states (p. 940).

Now the mixed-effects model itself: a fixed effect of gender and a random intercept for each trainee. This is the Equation 16.3 full model, and it is the analysis summarized in Table 16.3.

HideShow
fit_mix <- lmer(Severity ~ Gender + (1 | Trainee), data = nest)
summary(fit_mix)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Severity ~ Gender + (1 | Trainee)
   Data: nest

REML criterion at convergence: 155.2

Scaled residuals: 
    Min      1Q  Median      3Q     Max 
-1.8248 -0.4452 -0.1247  0.6843  1.4141 

Random effects:
 Groups   Name        Variance Std.Dev.
 Trainee  (Intercept) 18.11    4.256   
 Residual             45.56    6.749   
Number of obs: 24, groups:  Trainee, 6

Fixed effects:
             Estimate Std. Error     df t value Pr(>|t|)    
(Intercept)    46.000      3.136  4.000  14.669 0.000126 ***
GenderFemale   14.000      4.435  4.000   3.157 0.034286 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr)
GenderFemal -0.707
HideShow
#> Gender effect 14.0000 with SE 4.4347 on 4 df, t = 3.16, p = .0343 — matches
#> Table 16.3 (book p. 943). SAS codes female as the reference and so reports
#> this as -14.0000 with intercept 60 (the female mean); lmer codes male as the
#> reference, so its intercept is 46 (the male mean, book p. 940) and the sign
#> of the contrast is reversed. The SE, df, t, and p are identical.
#> Trainee variance 18.1111 and Residual 45.5556 — matches Table 16.3 (p. 943).
HideShow
anova(fit_mix, ddf = "Kenward-Roger")
HideShow
Type III Analysis of Variance Table with Kenward-Roger's method
       Sum Sq Mean Sq NumDF DenDF F value  Pr(>F)  
Gender 454.01  454.01     1     4  9.9661 0.03429 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> F(1, 4) = 9.97, p = .0343 — matches Table 16.3 (book p. 943) and the ANOVA
#> above. With equal n the two approaches give identical tests of the fixed
#> effect, which is the point of the section (book p. 944).

The book derives the trainee variance by hand from the expected mean squares rather than taking it from the output. Equation 16.6 says σ̂β2=(MSB/A−MSW)/n\hat\sigma^2_\beta = (MS_{B/A} - MS_W)/n, which is worth reproducing because it shows where the estimate comes from.

HideShow
MS_BA <- 118
MS_W  <- 45.5556
n_per <- 4
(MS_BA - MS_W) / n_per
HideShow
[1] 18.1111
HideShow
#> 18.1111 — matches book p. 945 and the Trainee variance in Table 16.3.

The two variances are additive, so the total variance within gender and the proportion of it due to trainee follow directly.

HideShow
vc <- as.data.frame(VarCorr(fit_mix))
sigma2_trainee  <- vc$vcov[vc$grp == "Trainee"]
sigma2_residual <- vc$vcov[vc$grp == "Residual"]
c(trainee  = sigma2_trainee,
  residual = sigma2_residual,
  total    = sigma2_trainee + sigma2_residual,
  icc      = sigma2_trainee / (sigma2_trainee + sigma2_residual))
HideShow
   trainee   residual      total        icc 
18.1111141 45.5555546 63.6666687  0.2844678 
HideShow
#> Total 63.6667 and an intraclass correlation of .2845 — matches book p. 945,
#> where 18.1111 / 63.6667 is reported as 28% of the variance due to trainee
#> and the remaining 72% due to client.

The book also forms a confidence interval for the gender difference from the estimate and its standard error, using the critical tt on 4 degrees of freedom. Done by hand, that is

HideShow
est <- fixef(fit_mix)["GenderFemale"]
se  <- sqrt(vcov(fit_mix)["GenderFemale", "GenderFemale"])
est + c(-1, 1) * qt(0.975, df = 4) * se
HideShow
[1]  1.687266 26.312734
HideShow
#> 1.69 to 26.31 for female minus male. The book works the same interval in the
#> opposite direction, -26.33 to -1.67 (p. 943), using the rounded critical
#> value 2.78; carrying the critical value to full precision moves the endpoints
#> by about .02. The interval excludes zero and is very wide, because the design
#> rests on only six trainees.
The same intraclass correlation, with an interval, in DMAR

The ratio computed above is a point estimate with nothing attached to it. DMAR’s icc_lmer() reads the same quantity off the fitted model and adds the interval and the cluster bookkeeping that the bare ratio leaves out.

HideShow
icc_lmer(fit_mix, conf_level = 0.95)
term value
icc 0.284
sigma2_between 18.111
sigma2_within 45.556
total_variance 63.667
ci_lower 0.000
ci_upper 0.747
n_clusters 6
average_cluster_size 4

Confidence level: 95%

HideShow
#> icc = 0.284 with sigma2_between = 18.111, sigma2_within = 45.556, and
#> total_variance = 63.667 — the same partition as the hand calculation above
#> and as book p. 945. The ci_lower and ci_upper rows are the addition: the
#> interval runs from essentially zero to about .75, which is the honest summary
#> of what six clusters of four observations support.

sjPlot::tab_model() collects the fixed effects, the random-effect variances, and the same ICC in one formatted table.

HideShow
tab_model(fit_mix,
          show.icc    = TRUE,    # the intraclass correlation
          show.re.var = TRUE,    # random-effect variances
          dv.labels   = "Severity")
  Severity
Predictors Estimates CI p
(Intercept) 46.00 39.46 – 52.54 <0.001
Gender [Female] 14.00 4.75 – 23.25 0.005
Random Effects
σ2 45.56
τ00 Trainee 18.11
ICC 0.28
N Trainee 6
Observations 24
Marginal R2 / Conditional R2 0.445 / 0.603

16.5.2 — Numerical Example: Unequal nn

The second example is the inductive reasoning study of Table 16.4. Three classrooms were randomly assigned to a treatment designed to teach inductive reasoning and three to a control, and 29 children in all were measured. Alongside the outcome (Inductive) the data carry two covariates that differ in level: Cognition, a cognitive ability score measured on each student (level 1), and Skill, the teacher’s rated teaching skill, measured on each classroom (level 2). Both are used in Section 16.6.

Rooms are coded 1, 2, 3 within each condition, so “Room 1” in the control condition is a different classroom from “Room 1” in the treatment condition; there are six classrooms in all (book p. 946). The nesting therefore has to be made explicit, by pasting condition and room together into a single grouping factor with six distinct labels. We also grand-mean-center cognitive ability here, because every analysis from Section 16.6.3 onward uses the centered score.

HideShow
data(chapter_16_table_4)
three <- chapter_16_table_4 |>
  as_tibble() |>
  mutate(Condition = case_when(Condition == 0 ~ "Control",
                               Condition == 1 ~ "Treatment")) |>
  mutate(
    Condition = factor(Condition, levels = c("Control", "Treatment")),
    Room      = factor(Room),
    # Six classrooms, six labels: "Control 1" is not "Treatment 1". This is the
    # grouping lmer would build internally from 1 | Condition:Room; writing it
    # out as its own column also lets the classical tools below read the nesting.
    Classroom = factor(paste(Condition, Room, sep = " ")),
    # Grand-mean-centered cognitive ability (book p. 961).
    CogCent   = Cognition - mean(Cognition)
  )
three
HideShow
# A tibble: 29 × 8
   Observation Room  Condition Cognition Skill Inductive Classroom CogCent
         <int> <fct> <fct>         <int> <int>     <int> <fct>       <dbl>
 1           1 1     Control          46     4        21 Control 1  -3.72 
 2           2 1     Control          52     4        26 Control 1   2.28 
 3           3 1     Control          60     4        33 Control 1  10.3  
 4           4 1     Control          44     4        22 Control 1  -5.72 
 5           5 2     Control          46     6        18 Control 2  -3.72 
 6           6 2     Control          48     6        25 Control 2  -1.72 
 7           7 2     Control          50     6        26 Control 2   0.276
 8           8 2     Control          54     6        24 Control 2   4.28 
 9           9 2     Control          50     6        21 Control 2   0.276
10          10 2     Control          48     6        25 Control 2  -1.72 
# ℹ 19 more rows
HideShow
#> The 29 rows of Table 16.4 — matches book p. 948.

mean(three$Cognition)
HideShow
[1] 49.72414
HideShow
#> 49.72 — matches book p. 961, the grand mean subtracted to form "cogcent".

The book establishes a context with the means of all three variables, by condition and by classroom (Table 16.5).

HideShow
three |>
  group_by(Condition) |>
  summarise(n = n(), Inductive = mean(Inductive),
            Cognition = mean(Cognition), Skill = mean(Skill))
HideShow
# A tibble: 2 × 5
  Condition     n Inductive Cognition Skill
  <fct>     <int>     <dbl>     <dbl> <dbl>
1 Control      15      27.3      50.3  6.47
2 Treatment    14      36.5      49.1  6.93
HideShow
#> Control 27.33 on 15 students, treatment 36.50 on 14 — matches Table 16.5
#> (book p. 949) and the text on book p. 947.

three |>
  group_by(Condition, Room) |>
  summarise(n = n(), Inductive = mean(Inductive),
            Cognition = mean(Cognition), Skill = mean(Skill),
            .groups = "drop")
HideShow
# A tibble: 6 × 6
  Condition Room      n Inductive Cognition Skill
  <fct>     <fct> <int>     <dbl>     <dbl> <dbl>
1 Control   1         4      25.5      50.5     4
2 Control   2         6      23.2      49.3     6
3 Control   3         5      33.8      51.2     9
4 Treatment 1         3      29        46       5
5 Treatment 2         5      39.8      51.2     8
6 Treatment 3         6      37.5      49       7
HideShow
#> Classroom means 25.50, 23.17, 33.80 (control) and 29.00, 39.80, 37.50
#> (treatment), on 4, 6, 5, 3, 5, and 6 students — matches Table 16.5
#> (book p. 949). The unequal classroom sizes are the reason the book turns to
#> the mixed-effects model: the ANOVA approach "is unable to handle unequal
#> sample sizes" (book p. 948).

The model is the same one as in Section 16.5.1 — a fixed condition effect and a random intercept for classrooms nested in condition — fit now to unbalanced data.

HideShow
fit_three <- lmer(Inductive ~ Condition + (1 | Classroom), data = three)
summary(fit_three)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Inductive ~ Condition + (1 | Classroom)
   Data: three

REML criterion at convergence: 171

Scaled residuals: 
     Min       1Q   Median       3Q      Max 
-1.39742 -0.74219  0.04089  0.67433  1.93550 

Random effects:
 Groups    Name        Variance Std.Dev.
 Classroom (Intercept) 26.63    5.160   
 Residual              20.26    4.501   
Number of obs: 29, groups:  Classroom, 6

Fixed effects:
                   Estimate Std. Error     df t value Pr(>|t|)   
(Intercept)          27.478      3.203  3.840   8.579  0.00121 **
ConditionTreatment    8.148      4.548  3.899   1.792  0.14955   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr)
CndtnTrtmnt -0.704
HideShow
#> Condition effect 8.1485 with SE 4.5484 — matches Table 16.6 (book p. 950),
#> which prints the standard error as 4.5483.
#> Classroom variance 26.627 and Residual 20.255 — matches Table 16.6 (p. 950).
#> lmer codes control as the reference, so its intercept 27.478 is the control
#> mean; SAS codes the treatment side as the reference and reports the intercept
#> as 35.6261 with COND 0 at -8.1485. The two agree: 27.478 + 8.148 = 35.626.

The book’s FF test uses containment degrees of freedom, which here equal 4: six classrooms less one, less the condition factor. The squared Wald tt referred to 4 denominator degrees of freedom reproduces Table 16.6 exactly.

HideShow
est <- fixef(fit_three)["ConditionTreatment"]
se  <- sqrt(vcov(fit_three)["ConditionTreatment", "ConditionTreatment"])
t_obs <- est / se
c(F_value = unname(t_obs^2), p_value = unname(2 * pt(-abs(t_obs), df = 4)))
HideShow
  F_value   p_value 
3.2095410 0.1476891 
HideShow
#> F(1, 4) = 3.21, p = .1477 — matches Table 16.6 (book p. 950). The data do not
#> allow us to reject the null hypothesis of no treatment effect.

lmerTest can choose the denominator degrees of freedom for us. Its default Satterthwaite method and the Kenward-Roger method both land essentially on the containment value here, though neither is forced to be an integer.

HideShow
anova(fit_three, ddf = "Kenward-Roger")
HideShow
Type III Analysis of Variance Table with Kenward-Roger's method
          Sum Sq Mean Sq NumDF  DenDF F value Pr(>F)
Condition 64.915  64.915     1 3.9882  3.2049 0.1481
HideShow
#> F = 3.20 on 1 and 3.99 denominator df, p = .148. Kenward-Roger also adjusts
#> the standard error, so its F differs from the book's 3.21 in the third digit;
#> the conclusion is the same.

The book then forms the confidence interval for the treatment effect from the same standard error and the critical tt on 4 degrees of freedom.

HideShow
est + c(-1, 1) * qt(0.975, df = 4) * se
HideShow
[1] -4.479798 20.776749
HideShow
#> -4.48 to 20.78, the book's -4.50 to 20.79 (p. 950) up to its rounding of the
#> critical value to 2.78. The treatment could be as beneficial as about 21
#> points or as detrimental as about 4.5; the interval contains zero, and it is
#> this wide because there are only six classrooms.
Profile-likelihood intervals on the variance components

In Section 16.5.1 the design was balanced, so the analytic modified-large-sample interval on the variance components applied (DMAR’s variance_components_mls(), used on these data in the Chapter 10 notes). That formula assumes a single common cell size nn, so it does not apply here: the classrooms hold different numbers of students, which is the whole reason the book analyzes these data with the mixed model. The lme4-native analog, valid for unequal nn, is a REML profile-likelihood interval taken from the fitted model.

HideShow
# Profile intervals come back on the standard-deviation scale; square them for
# variances. The .sig01 row is the Classroom SD, .sigma the residual SD.
ci_sd  <- confint(fit_three, parm = c(".sig01", ".sigma"), method = "profile")
ci_var <- ci_sd^2
rownames(ci_var) <- c("Classroom variance", "Residual variance")
ci_var
HideShow
                       2.5 %   97.5 %
Classroom variance  2.538059 78.90358
Residual variance  11.964581 38.65127
HideShow
#> The point estimates 26.627 and 20.255 (Table 16.6, book p. 950) fall inside
#> these 95% intervals. The classroom-variance interval is very wide, because
#> six classrooms carry little information about a variance.
Is the classroom clustering needed? A likelihood-ratio test

The book does not test the random classroom effect, but the question is a natural one, so we work it here as companion material. The comparison is the mixed model against an ordinary regression with no clustering at all, both fit by maximum likelihood so the likelihoods are comparable. Because the classroom variance sits on the boundary of its parameter space — it cannot be negative — the usual χ2(1)\chi^2(1) tail probability is halved.

HideShow
fit_no_room <- lm(Inductive ~ Condition, data = three)
fit_room    <- lmer(Inductive ~ Condition + (1 | Classroom), data = three,
                    REML = FALSE)

lr      <- as.numeric(2 * (logLik(fit_room) - logLik(fit_no_room)))
p_value <- pchisq(lr, df = 1, lower.tail = FALSE) / 2
tibble(LR_statistic = lr, p_value = p_value)
HideShow
# A tibble: 1 × 2
  LR_statistic p_value
         <dbl>   <dbl>
1         6.62 0.00503

lmerTest::ranova() performs the same single-term deletion directly from the REML fit. Its likelihood ratio is computed on the REML scale and its pp value is not halved, so the two numbers differ; both say the same thing.

HideShow
ranova(fit_three)
HideShow
ANOVA-like table for random-effects: Single term deletions

Model:
Inductive ~ Condition + (1 | Classroom)
                npar  logLik    AIC    LRT Df Pr(>Chisq)   
<none>             4 -85.522 179.04                        
(1 | Classroom)    3 -90.024 186.05 9.0041  1   0.002694 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Both routes say the classrooms differ from one another beyond chance, which is consistent with the sizable classroom variance (26.627) in Table 16.6 and confirms that the clustering should be modeled rather than ignored.

Where the variability sits: a descriptive nested decomposition

Classical ANOVA is not the basis for inference here — the book is explicit that it does not apply with unequal nn (p. 948) — but the nested sums of squares still describe where the variability sits. With Room a factor, aov() reads the nesting correctly: condition on 1 degree of freedom and rooms-within-condition on 4. (Had Room been left numeric it would have entered as a single regression slope on 1 degree of freedom, which is wrong.) We lay it out with gt, and report no FF or pp, because under unequal nn those would not be the tests the book uses.

HideShow
fit_aov <- aov(Inductive ~ Condition + Condition:Room, data = three)
broom::tidy(fit_aov) |>
  mutate(term = recode(term, "Condition:Room" = "Room (within Condition)")) |>
  transmute(Source = term, SS = sumsq, df = df, MS = meansq) |>
  gt() |>
  fmt_number(columns = c(SS, MS), decimals = 2) |>
  tab_header(
    title    = md("**Table 1**. Nested decomposition of inductive reasoning (descriptive)"),
    subtitle = md("Rooms are nested within condition; *n* is unequal, so inference uses the mixed model above.")) |>
  cols_align(align = "center", columns = -Source)
Table 1. Nested decomposition of inductive reasoning (descriptive)
Rooms are nested within condition; n is unequal, so inference uses the mixed model above.
Source SS df MS
Condition 608.48 1 608.48
Room (within Condition) 555.90 4 138.97
Residuals 464.93 23 20.21

16.6 — Mixed-Effects Models for Complex Nested Designs

Section 16.6 extends the unconditional model in two directions, using the two covariates that differ in level. Teaching skill is a property of the classroom (level 2), so it enters the between-classroom part of the model; cognitive ability is a property of the student (level 1), so it enters the within-classroom part and can carry its own random slope. The book treats them in turn.

16.6.2 — Models with Additional Level 2 Variables

Because teaching skill is constant within a classroom, it enters as an additional fixed effect and the random part is unchanged: adding a predictor at the highest level of the hierarchy changes the fixed effects but not the random-effects specification (book p. 955).

HideShow
fit_skill <- lmer(Inductive ~ Condition + Skill + (1 | Classroom), data = three)
summary(fit_skill)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Inductive ~ Condition + Skill + (1 | Classroom)
   Data: three

REML criterion at convergence: 164.5

Scaled residuals: 
     Min       1Q   Median       3Q      Max 
-1.40177 -0.69562 -0.06924  0.51685  2.01182 

Random effects:
 Groups    Name        Variance Std.Dev.
 Classroom (Intercept)  6.572   2.564   
 Residual              20.274   4.503   
Number of obs: 29, groups:  Classroom, 6

Fixed effects:
                   Estimate Std. Error      df t value Pr(>|t|)  
(Intercept)         12.6834     5.5039  3.1807   2.304   0.0996 .
ConditionTreatment   7.5686     2.7163  2.8876   2.786   0.0717 .
Skill                2.3092     0.8086  3.1249   2.856   0.0617 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) CndtnT
CndtnTrtmnt -0.127       
Skill       -0.939 -0.119
HideShow
#> Skill slope 2.3092 with SE 0.8086 and Condition 7.5686 with SE 2.7163 —
#> matches Table 16.7 (book p. 956), where they are 2.3092 (0.8085) and 7.5687
#> (2.7161). The book reads the skill slope as "approximately 2.31" on p. 955:
#> a one-point rise in rated teaching skill goes with a 2.31-point rise in a
#> classroom's mean inductive reasoning score.
#> Classroom variance 6.572 and Residual 20.274, against Table 16.7's 6.5704 and
#> 20.2747 (p. 956): agreement to about three significant digits, the remainder
#> REML convergence tolerance rather than a difference of model.

The book’s tests again use containment degrees of freedom: 3 for condition (one fewer than before, because a classroom-level predictor has been added) and 23 for skill. Those reproduce Table 16.7’s pp values exactly.

HideShow
containment_test <- function(fit, term, df) {
  est <- fixef(fit)[term]
  se  <- sqrt(vcov(fit)[term, term])
  t   <- est / se
  c(estimate = unname(est), se = unname(se),
    F_value = unname(t^2), p_value = unname(2 * pt(-abs(t), df = df)))
}
rbind(
  Condition = containment_test(fit_skill, "ConditionTreatment", df = 3),
  Skill     = containment_test(fit_skill, "Skill",              df = 23)
)
HideShow
          estimate        se  F_value     p_value
Condition 7.568622 2.7162537 7.764134 0.068622920
Skill     2.309244 0.8085643 8.156624 0.008938874
HideShow
#> Condition F(1, 3) = 7.76, p = .0686 and Skill F(1, 23) = 8.16, p = .0089 —
#> matches Table 16.7 (book p. 956), which prints the condition F as 7.77.

Two quantities the book draws from this output are worth reproducing. The first is the confidence interval for the condition effect, which is narrower than it was without teaching skill in the model.

HideShow
est_c <- fixef(fit_skill)["ConditionTreatment"]
se_c  <- sqrt(vcov(fit_skill)["ConditionTreatment", "ConditionTreatment"])
est_c + c(-1, 1) * qt(0.975, df = 3) * se_c
HideShow
[1] -1.075709 16.212954
HideShow
#> -1.07 to 16.21 — matches book p. 955. Compare the -4.50 to 20.79 of the model
#> without teaching skill (p. 950): the interval is substantially narrower,
#> though it still contains zero.

The second is the squared semipartial correlation for teaching skill — the share of the between-classroom variance it accounts for.

HideShow
v_without <- as.data.frame(VarCorr(fit_three))$vcov[1]   # 26.627 (Table 16.6)
v_with    <- as.data.frame(VarCorr(fit_skill))$vcov[1]   #  6.572 (Table 16.7: 6.5704)
(v_without - v_with) / v_without
HideShow
[1] 0.753184
HideShow
#> .75 — matches book p. 957: teaching skill accounts for about 75% of the
#> between-classroom variance in inductive reasoning. The denominator is
#> variance between classrooms, not between students, and the effective sample
#> size behind it is only six classrooms, so the book is careful not to read
#> this as a causal share.

Notice also that the residual variance barely moved: 20.255 without teaching skill, 20.274 with it (book p. 957). A level-2 covariate soaks up between-classroom variance and leaves the within-classroom variance alone, because the level-1 equation is unchanged.

Tidy fixed effects, and the two models side by side

broom.mixed::tidy() puts the fixed effects of a mixed model into a data frame, which is convenient when the next step is a table or a plot rather than reading the console.

HideShow
broom.mixed::tidy(fit_skill, effects = "fixed", conf.int = TRUE, conf.level = 0.95)
HideShow
# A tibble: 3 × 9
  effect term      estimate std.error statistic    df p.value conf.low conf.high
  <chr>  <chr>        <dbl>     <dbl>     <dbl> <dbl>   <dbl>    <dbl>     <dbl>
1 fixed  (Interce…    12.7      5.50       2.30  3.18  0.0996   -4.28      29.6 
2 fixed  Conditio…     7.57     2.72       2.79  2.89  0.0717   -1.27      16.4 
3 fixed  Skill         2.31     0.809      2.86  3.12  0.0617   -0.207      4.83

modelsummary puts each model in its own column with fit statistics at the foot.

HideShow
modelsummary(
  list("Condition only" = fit_three, "Condition + Skill" = fit_skill),
  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
)
Condition only Condition + Skill
(Intercept) 27.478 12.683
(3.203) (5.504)
ConditionTreatment 8.148 7.569
(4.548) (2.716)
Skill 2.309
(0.809)
SD (Intercept Classroom) 5.160 2.564
SD (Observations) 4.501 4.503
Num.Obs. 29 29
AIC 179.0 174.5
BIC 184.5 181.3
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

The same comparison as a gtsummary table, each model under its own spanning header.

HideShow
t_base  <- tbl_regression(fit_three, intercept = TRUE)
t_skill <- tbl_regression(fit_skill, intercept = TRUE)
tbl_merge(list(t_base, t_skill),
          tab_spanner = c("**Condition only**", "**Condition + Skill**"))
Characteristic
Condition only
Condition + Skill
Beta 95% CI p-value Beta 95% CI p-value
(Intercept) 27 18, 37 0.001 13 -4.3, 30 0.10
Condition





    Control — —
— —
    Treatment 8.1 -4.6, 21 0.15 7.6 -1.3, 16 0.072
Skill


2.3 -0.21, 4.8 0.062
Abbreviation: CI = Confidence Interval

sjPlot::tab_model() shows both models with the random-effect variances and the ICC in one view; the fall in the classroom variance from the first column to the second is the 75% reduction computed above.

HideShow
tab_model(fit_three, fit_skill,
          show.icc    = TRUE,
          show.re.var = TRUE,
          dv.labels   = c("Condition only", "Condition + Skill"))
  Condition only Condition + Skill
Predictors Estimates CI p Estimates CI p
(Intercept) 27.48 20.88 – 34.07 <0.001 12.68 1.32 – 24.04 0.030
Condition [Treatment] 8.15 -1.22 – 17.52 0.085 7.57 1.96 – 13.17 0.010
Skill 2.31 0.64 – 3.98 0.009
Random Effects
σ2 20.26 20.27
τ00 26.63 Classroom 6.57 Classroom
ICC 0.57 0.24
N 6 Classroom 6 Classroom
Observations 29 29
Marginal R2 / Conditional R2 0.268 / 0.684 0.555 / 0.664

One caution about all three tables: each package applies its own default degrees of freedom to the fixed effects, and none of them is the book’s containment dfdf. Their pp values therefore differ from one another and from Table 16.6 and Table 16.7. The containment tests computed above are the ones to compare with the book; read these tables for the estimates, the standard errors, and the variance components.

16.6.3 — Models with Additional Level 1 Variables

Cognitive ability is a student characteristic, so it enters the level-1 equation (Equation 16.12), and each classroom is now characterized two ways: by the intercept and by the slope of the within-classroom regression of inductive reasoning on cognitive ability. The book builds the argument from the data before fitting anything, and the three figures below follow it step by step.

Figure 16.1. Inductive reasoning and cognitive ability in one classroom

The book starts inside a single classroom — the first classroom in the control condition, four students — to make concrete what a level-1 regression line is.

HideShow
control_1 <- three |> filter(Classroom == "Control 1")

ggplot(control_1, aes(Cognition, Inductive)) +
  geom_point(size = 2.6) +
  geom_smooth(method = "lm", se = FALSE, color = "#0C2340", linewidth = 1) +
  labs(title = "Figure 16.1. Control classroom 1",
       x = "Cognitive ability", y = "Inductive reasoning")
Figure 16.1. Scatterplot of inductive reasoning and cognitive ability scores for students in the first classroom of the control condition.

Figure 16.1. Scatterplot of inductive reasoning and cognitive ability scores for students in the first classroom of the control condition.

HideShow
coef(lm(Inductive ~ Cognition, data = control_1))
HideShow
(Intercept)   Cognition 
-11.9677419   0.7419355 
HideShow
#> Slope 0.74 and intercept -11.97 for these 4 students — matches book p. 959.
Figure 16.2. Within-classroom regression lines, all six classrooms

The same line is then fit inside each of the six classrooms. The within-classroom slopes need not resemble one another, and they need not resemble the slope that would be obtained by ignoring classrooms altogether: this is the between- versus within-cluster distinction at the heart of the chapter.

HideShow
ggplot(three, aes(Cognition, Inductive, color = Classroom)) +
  geom_point(size = 2.3) +
  geom_smooth(method = "lm", se = FALSE, linewidth = 0.9) +
  labs(title = "Figure 16.2. Within-classroom regression on cognitive ability",
       x = "Cognitive ability", y = "Inductive reasoning", color = NULL)
Figure 16.2. Regression lines relating inductive reasoning and cognitive ability scores within each of six classrooms.

Figure 16.2. Regression lines relating inductive reasoning and cognitive ability scores within each of six classrooms.

Table 16.8 gives the numerical slope and intercept for each classroom.

HideShow
three |>
  group_by(Condition, Room) |>
  summarise(Slope     = coef(lm(Inductive ~ Cognition))[2],
            Intercept = coef(lm(Inductive ~ Cognition))[1],
            .groups   = "drop")
HideShow
# A tibble: 6 × 4
  Condition Room  Slope Intercept
  <fct>     <fct> <dbl>     <dbl>
1 Control   1     0.742    -12.0 
2 Control   2     0.446      1.14
3 Control   3     0.562      5.00
4 Treatment 1     0.125     23.3 
5 Treatment 2     1.03     -13.2 
6 Treatment 3     0.548     10.6 
HideShow
#> Slopes 0.74, 0.45, 0.56 (control) and 0.12, 1.03, 0.55 (treatment);
#> intercepts -11.97, 1.14, 5.00 and 23.25, -13.19, 10.64 — matches Table 16.8
#> (book p. 960).
Figure 16.3. The same lines after centering cognitive ability

An intercept is the fitted value when the predictor is zero, and a cognitive ability score of zero is off the scale, so the intercepts of Table 16.8 are not interpretable. Subtracting the grand mean of 49.72 fixes that: the intercept becomes the classroom’s fitted inductive reasoning score for a student of average cognitive ability. Centering leaves the slopes untouched and moves the intercepts (book p. 961).

HideShow
ggplot(three, aes(CogCent, Inductive, color = Classroom)) +
  geom_point(size = 2.3) +
  geom_smooth(method = "lm", se = FALSE, linewidth = 0.9) +
  labs(title = "Figure 16.3. Within-classroom regression on centered cognitive ability",
       x = "Cognitive ability (centered at the grand mean, 49.72)",
       y = "Inductive reasoning", color = NULL)
Figure 16.3. Regression lines relating inductive reasoning and centered cognitive ability scores within each of six classrooms.

Figure 16.3. Regression lines relating inductive reasoning and centered cognitive ability scores within each of six classrooms.

HideShow
three |>
  group_by(Condition, Room) |>
  summarise(Slope     = coef(lm(Inductive ~ CogCent))[2],
            Intercept = coef(lm(Inductive ~ CogCent))[1],
            .groups   = "drop")
HideShow
# A tibble: 6 × 4
  Condition Room  Slope Intercept
  <fct>     <fct> <dbl>     <dbl>
1 Control   1     0.742      24.9
2 Control   2     0.446      23.3
3 Control   3     0.563      33.0
4 Treatment 1     0.125      29.5
5 Treatment 2     1.03       38.3
6 Treatment 3     0.548      37.9
HideShow
#> Slopes unchanged at 0.74, 0.45, 0.56, 0.12, 1.03, 0.55; intercepts now
#> 24.92, 23.34, 32.97, 29.47, 38.27, 37.90 — matches Table 16.9 (book p. 962).
#> Centering has produced a clearer separation between the control and treatment
#> intercepts than Table 16.8 showed.

Substituting the book’s two level-2 equations — 16.13 for the intercept and 16.14 for the slope (book p. 963) — into the level-1 equation gives the single-equation full model of Equation 16.15 (book p. 964). It lets each classroom have its own intercept and its own slope on centered cognitive ability, allows the two to covary, and adds a condition-by-cognition interaction to the fixed part. In lmer notation that is Inductive ~ Condition * CogCent + (CogCent | Classroom).

HideShow
fit_cog <- lmer(Inductive ~ Condition * CogCent + (CogCent | Classroom),
                data = three)
summary(fit_cog)
HideShow
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Inductive ~ Condition * CogCent + (CogCent | Classroom)
   Data: three

REML criterion at convergence: 157.5

Scaled residuals: 
     Min       1Q   Median       3Q      Max 
-1.50204 -0.61776  0.02134  0.67690  1.67423 

Random effects:
 Groups    Name        Variance  Std.Dev. Corr 
 Classroom (Intercept) 18.524896 4.30406       
           CogCent      0.004772 0.06908  1.00 
 Residual              11.738104 3.42609       
Number of obs: 29, groups:  Classroom, 6

Fixed effects:
                           Estimate Std. Error       df t value Pr(>|t|)    
(Intercept)                27.03544    2.64430  3.76183  10.224 0.000702 ***
ConditionTreatment          9.06664    3.75887  3.82427   2.412 0.076333 .  
CogCent                     0.66722    0.21293 12.98348   3.133 0.007931 ** 
ConditionTreatment:CogCent -0.02521    0.30052 12.53846  -0.084 0.934479    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) CndtnT CogCnt
CndtnTrtmnt -0.703              
CogCent      0.127 -0.090       
CndtnTrt:CC -0.090  0.191 -0.709
optimizer (nloptwrap) convergence code: 0 (OK)
boundary (singular) fit: see help('isSingular')

Two things to read here. First, the residual variance has fallen from 20.255 in the unconditional model to about 11.74. The book reports 11.80 (Table 16.10, book p. 966, discussed p. 969) against 20.26 and 20.27 for the two earlier models: cognitive ability explains a large share of the within-classroom variance, the part teaching skill left untouched. Second, lme4 reports a singular fit. The three classroom covariance parameters below show where this fit reached a boundary.

HideShow
isSingular(fit_cog)
HideShow
[1] TRUE
HideShow
as.data.frame(VarCorr(fit_cog))
HideShow
        grp        var1    var2         vcov     sdcor
1 Classroom (Intercept)    <NA> 18.524896203 4.3040558
2 Classroom     CogCent    <NA>  0.004772074 0.0690802
3 Classroom (Intercept) CogCent  0.297325019 1.0000000
4  Residual        <NA>    <NA> 11.738103906 3.4260916

In two treatment classrooms, the slopes in Table 16.9 are 0.12 and 1.03 points of predicted inductive reasoning per point of cognitive ability. These fitted slopes vary with the students sampled, and the slope variance in Table 16.10 estimates how much the underlying slopes vary among classrooms within the same condition after accounting for that sampling variation. With 29 students in six classrooms, SAS estimated the slope variance at its lower bound of zero (p. 969) and reported an intercept–slope covariance of 0.7246. In R, lme4 requires the two variances and their covariance to form a valid covariance matrix and reaches its boundary with a slope variance of 0.00477 and an intercept–slope correlation of +1.

Both fits give a residual variance near 11.8, a fitted treatment advantage of about 9 points at average cognitive ability, and little evidence that the average slope differs by treatment condition.

The book warns (p. 967) that the cogcent row of the solution is a simple effect, not a main effect: with treatment contrasts it is the slope in the reference condition. Table 16.10’s Type 3 test of cognitive ability is instead the slope averaged over conditions, which in R comes from sum-to-zero contrasts on condition.

HideShow
three_sum <- three
contrasts(three_sum$Condition) <- contr.sum(2)
fit_cog_sum <- lmer(Inductive ~ Condition * CogCent + (CogCent | Classroom),
                    data = three_sum)
rbind(
  Condition           = containment_test(fit_cog_sum, "Condition1",         df = 4),
  CogCent             = containment_test(fit_cog_sum, "CogCent",            df = 4),
  `Condition:CogCent` = containment_test(fit_cog_sum, "Condition1:CogCent", df = 4)
)
HideShow
                     estimate        se      F_value    p_value
Condition         -4.53325266 1.8795752  5.817018265 0.07340763
CogCent            0.65459905 0.1502679 18.976593569 0.01209798
Condition:CogCent  0.01261834 0.1502679  0.007051341 0.93711315
HideShow
#> F(1, 4) = 5.82, 18.98, and 0.01 against Table 16.10's 5.18, 19.63, and 0.10
#> (book p. 966). Same three conclusions — condition not quite significant,
#> cognitive ability significant, no interaction — with the last digits moved by
#> the boundary described above, not by a different model. Only the F and p
#> columns are comparable here: under sum-to-zero coding the Condition estimate
#> is the control group's deviation from the grand mean, which is half the
#> treatment-minus-control effect with the sign reversed.

Dropping the uninformative random slope gives a non-singular fit that carries the same message and is easier to defend from six classrooms.

HideShow
fit_cog_ri <- lmer(Inductive ~ Condition * CogCent + (1 | Classroom), data = three)
as.data.frame(VarCorr(fit_cog_ri))
HideShow
        grp        var1 var2     vcov    sdcor
1 Classroom (Intercept) <NA> 18.08857 4.253066
2  Residual        <NA> <NA> 11.81926 3.437915
HideShow
anova(fit_cog_ri, ddf = "Kenward-Roger")
HideShow
Type III Analysis of Variance Table with Kenward-Roger's method
                   Sum Sq Mean Sq NumDF   DenDF F value    Pr(>F)    
Condition          71.372  71.372     1  3.9583  6.0386 0.0705527 .  
CogCent           237.222 237.222     1 21.6364 20.0708 0.0001935 ***
Condition:CogCent   0.002   0.002     1 21.6364  0.0002 0.9901447    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Residual 11.82, essentially the 11.8050 of Table 16.10 (book p. 966). The
#> cognitive-ability and interaction tests carry far more denominator df here
#> than in Table 16.10: with no random slope, cognitive ability becomes an
#> ordinary within-classroom effect, whereas the book's retained-but-zero slope
#> holds those tests to 4 df.

The headline comparison the book draws (p. 967) is what including cognitive ability does to the condition test.

HideShow
containment_test(fit_cog, "ConditionTreatment", df = 4)
HideShow
  estimate         se    F_value    p_value 
9.06663504 3.75886729 5.81806116 0.07339044 
HideShow
#> p = .073 here against the .1477 of the unconditional model (Table 16.6,
#> book p. 950). The book's Table 16.10 gives .0852 for the same comparison
#> (p. 967). Either way, including a level-1 covariate that predicts the outcome
#> has sharpened the test of the treatment effect, which is the book's point.
HideShow
est_g <- fixef(fit_cog)["ConditionTreatment"]
se_g  <- sqrt(vcov(fit_cog)["ConditionTreatment", "ConditionTreatment"])
est_g + c(-1, 1) * qt(0.975, df = 4) * se_g
HideShow
[1] -1.369654 19.502924
HideShow
#> -1.37 to 19.50. The book's interval from Table 16.10 is -1.99 to 19.97
#> (p. 968), built from its estimate 8.99 and SE 3.9487. Both are narrower than
#> the -4.50 to 20.79 of the model without covariates, and both still contain
#> zero: with six classrooms the treatment effect remains poorly pinned down.
HideShow
tab_model(fit_cog_ri,
          show.icc    = TRUE,
          show.re.var = TRUE,
          dv.labels   = "Inductive (with cognitive ability, level 1)")
  Inductive (with cognitive ability, level 1)
Predictors Estimates CI p
(Intercept) 27.07 21.66 – 32.49 <0.001
Condition [Treatment] 9.15 1.45 – 16.84 0.022
CogCent 0.67 0.24 – 1.10 0.004
Condition [Treatment] ×
CogCent
-0.00 -0.61 – 0.61 0.990
Random Effects
σ2 11.82
τ00 Classroom 18.09
ICC 0.60
N Classroom 6
Observations 29
Marginal R2 / Conditional R2 0.481 / 0.795

16.7 — Power Analysis and Sample Size Planning

The book gives three routes for planning a study that will be analyzed with a mixed-effects model for nested data. The first assumes an idealized equal-nn design and uses the Chapter 10 power machinery; because maximum likelihood does not map onto least squares in general, the resulting NN is a lower bound — a principled best case. The second builds an exemplary data set in which each cell’s supposed population mean is repeated according to its planned cell size, fits the model with the error variance fixed at its supposed value, converts the test statistic into a noncentrality parameter, and iterates over sample sizes. The third is an a priori Monte Carlo simulation, which is the most flexible of the three: it accommodates unequal cell sizes and differential rates of missing data, and it can target power and precision at once.

Clustering and the design effect

The book does not work the design effect in this chapter, but it is the quickest way to see what the clustering above costs, so we add it here. When clusters are the unit of assignment and individuals are the unit of analysis, the effective sample size is the nominal one divided by

DE=1+(m−1)ρI, \text{DE} \;=\; 1 + (m - 1)\,\rho_I,

where mm is the cluster size and ρI\rho_I the intraclass correlation. The inductive reasoning data supply both ingredients from the unconditional model of Section 16.5.2.

HideShow
vc_three <- as.data.frame(VarCorr(fit_three))
rho_I    <- vc_three$vcov[1] / sum(vc_three$vcov)
m_bar    <- mean(table(three$Classroom))
c(icc = rho_I, mean_cluster_size = m_bar,
  design_effect = 1 + (m_bar - 1) * rho_I)
HideShow
              icc mean_cluster_size     design_effect 
        0.5679603         4.8333333         3.1771810 

With an ICC near .57, even classrooms this small cost a factor of about three. A study of 29 children clustered this way carries roughly the information of nine independent ones, which is the arithmetic behind the stubbornly wide intervals throughout the chapter.

DMAR’s design_effect() does the same arithmetic and adds what the one-line formula cannot: Kish’s correction for unequal cluster sizes, the effective nn, and the cluster bookkeeping.

HideShow
design_effect(cluster_sizes = as.vector(table(three$Classroom)), icc = rho_I)
term value
design_effect 3.311
deft 1.820
effective_n 8.759
N 29
n_clusters_total 6
n_clusters_with_data 6
n_clusters_empty 0
n_clusters_singletons 0
n_clusters_informative 6
m_bar 4.833
m_kish 5.069
icc 0.568

The m_bar row is the simple mean cluster size used above; m_kish is the variance-weighted size that the unequal classroom sizes call for, and the design effect reported is the one built from it. The effective_n row translates the whole thing back into a number of independent observations.

The same ICC drives sample size planning. DMAR’s cluster-randomized AIPE family plans for a target confidence-interval width on the treatment effect rather than for power — the ss_aipe_crd_* functions — and a Fisher-transform planner handles the companion question of planning to estimate an ICC precisely in the first place.

HideShow
# Clusters needed for a standardized treatment effect estimated to within a
# full-width of 0.5, with 20 individuals per cluster and an ICC of .05.
ss_aipe_crd_n_clusters_fixed_width(
  width          = 0.5,
  cluster_size   = 20,
  pr_treat       = 0.5,
  true_icc       = 0.05,
  true_total_var = 1,
  conf_level     = 0.95
)
term value
necessary_n_clusters 27
width 0.500
expected_width 0.495

Confidence level: 95%

HideShow
# Clusters needed to estimate an ICC of .10 to within a full-width of .10,
# with 20 observations per cluster.
ss_aipe_icc(
  true_icc   = 0.10,
  n_raters   = 20,
  width      = 0.10,
  conf_level = 0.95,
  type       = "ICC(1,1)"
)
term value
necessary_N 58
expected_width 0.100
true_icc 0.100
n_raters 20
width 0.100
conf_level 0.950

Confidence level: 95%

Both planners make the chapter’s recurring lesson quantitative: with clustered data it is the number of clusters, far more than the number of individuals inside them, that buys precision.

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 16: An Introduction to Mixed-Effects Models: Nested Designs (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