Chapter 7: Two-Way Between-Subjects Factorial Designs

R Code and Instructions

Scott E. Maxwell, Harold D. Delaney, and Ken Kelley

Code
Results
On this page

Examples follow the book’s section numbers.

Chapter 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

Scroll to Top