Examples follow the book’s section numbers.

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

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

data(chapter_9_table_1)
chapter_9_table_1
  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
chapter_9_table_1$Group <- as.factor(chapter_9_table_1$Group)
str(chapter_9_table_1)
'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.

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

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
summary(lm_2)

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

# 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")
Restricted Model Error Sum of Squares (ER): 14.4 
#> E_R = 14.40 — matches book p. 446 (Table 9.3)

# The restricted model's intercept and slope themselves:
coef(Restricted.Model)
(Intercept)           X 
        2.2         2.6 
#> 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")
Full Model Error Sum of Squares (EF): 12 
#> 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.

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

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.

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.

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.

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

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
# ANCOVA output
anova(ANCOVA_9_1)
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
#> Group SS = 2.4, Error SS = 12.0, F = 0.6 — matches book p. 451 (Equation 9.22)
summary(ANCOVA_9_1)

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.

Anova(ANCOVA_9_1, type="III")
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               
#> 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.

anova(ANOVA_9_1, ANCOVA_9_1)
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
#> 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:

# 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
[1] 0.6
#> 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.

# 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
  Obs_Mean_X X_Grand_Mean Obs_Mean_Y Adjusted_Group_Means_Y
1          2            3          7                      9
2          4            3         13                     11
#> 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:

emmeans(ANCOVA_9_1, ~ Group)
 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 
#> 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.

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:

Data.Fitted <- cbind(Data, y.hat = fitted(Result))

Data.Fitted[Data.Fitted$Treatment == 0, "y.hat"]
[1]  83.76818  93.52574  97.32035 100.03078 100.57287 104.90956 110.87252
Data.Fitted[Data.Fitted$Treatment == 1, "y.hat"]
[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.)

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.

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

# 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")
True Adjusted Effect (Perfect Covariate): 0 
#> 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")
Fallible Regression Slope: 0.2 
#> 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")
Estimated Adjusted Effect (Fallible Covariate): 8 
#> 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.

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

group_by(chapter_9_table_7, Group) %>%
summarise(mean=mean(Pre), sd=sd(Pre), n=n())
# 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
#> 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())
# 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
#> posttest means 7.3, 12.2, 14.0 — matches book p. 467 (Table 9.7, last line)

mean(chapter_9_table_7$Pre)
[1] 17.36667
#> 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.

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

anova(lm(Post ~ 1, data = chapter_9_table_7), Beck_ANCOVA_Model)
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
#> 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.

# ANCOVA Output (Type III SS) - See second part of Table 9.9
Anova(Beck_ANCOVA_Model, type="III")
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
#> 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)

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

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)

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

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:

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:

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

# Calculate Estimated Marginal Means (Adjusted Means)
Adjusted_Means <- emmeans(Beck_ANCOVA_Model, ~ Group)
Adjusted_Means
 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 
#> 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.

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%

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

# 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
[1] 0.5412457
# 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
# 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.

# 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")
Extrinsic R-squared: 0.22 
#> 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.

# 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")
Intrinsic R-squared: 0.18 
#> 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)

# 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")
Omega Squared: 0.12 
#> 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.

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

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

# 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")
MS_W: 39.62  SD_within: 6.29 
#> 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")
Cohen's d (Wait List vs SSRI): 1.02 
#> 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.

# 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
[1] 752.5
#> 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))
 s_anova s_ancova 
6.294324 5.393496 
#> 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%

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

# Table 9.10
Pairwise_Comparisons <- pairs(Adjusted_Means, adjust = "tukey")

# Show the simultaneous 95% confidence intervals for those differences
confint(Pairwise_Comparisons)
 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 
#> 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.

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

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

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

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

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

# 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")
Example 1 Threshold: 7.68 
cat("Should we include? ", r_covariates < threshold)
Should we include?  TRUE
#> threshold = 7.68 — matches book p. 477: "r here is only 1, which is less
#> than 7.68 [i.e., (.40^2)(48)]"
# 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")
Example 2 Threshold: 9.6 
cat("Should we include? ", r_covariates_2 < threshold_2)
Should we include?  TRUE
#> 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.

# 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")
Total Sample Size Required for ANOVA: 63 
#> 21 per group, 63 in total — matches book p. 478
# 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")
Adjusted Effect Size (f) for ANCOVA: 0.4713 
#> 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")
Total Sample Size Required for ANCOVA: 48 
#> 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.

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

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.

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.

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

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

# Pull in data with AMCP package
data("chapter_9_table_12")
head(chapter_9_table_12)
  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
# 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.

chapter_9_table_12 |>
  group_by(Block, Task) |>
  summarise(mean_X = mean(X), mean_Y = mean(Y), .groups = "drop")
# 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
#> 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")
# 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  
#> 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.

Model_ANOVA <- lm(Y ~ Task, data = chapter_9_table_12)
car::Anova(Model_ANOVA, type = "III")
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
#> 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.

Model_Block <- lm(Y ~ Task * Block, data = chapter_9_table_12)
car::Anova(Model_Block, type = "III")
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():

anova(Model_Block)
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
#> 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:

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.

Model_ANCOVA <- lm(Y ~ Task + X, data = chapter_9_table_12)
car::Anova(Model_ANCOVA, type = "III")
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
#> 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.

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

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

# Step 3: Check Covariate Balance
summary(match_model)

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.

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

data(chapter_9_extension_table_1)
chapter_9_extension_table_1
  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
#> 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")
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
summary(ANOVA_model)

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
# ANCOVA Model (Restricted Model: Homogeneous slopes)
ANCOVA_model <- lm(Y ~ Group + X, data=chapter_9_extension_table_1)
Anova(ANCOVA_model, type="III")
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               
#> 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)

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

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

# Adjusted means from the homogeneous-slopes ANCOVA
emmeans(ANCOVA_model, ~ Group)
 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 
#> 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)
     s2_het SS_x_within          se 
   6.000000    4.000000    3.162278 
#> 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)
         t         df 
-0.6324555  2.0000000 
#> 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).

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")
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
#> 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
[1] 131.2118
#> 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.

# 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))
# 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.
# Descriptives for covariate
group_by(Pygmalion, Treatment) %>%
summarise(mean_IQPre=mean(IQPre), var_IQPre=var(IQPre), sd_IQPre=sd(IQPre), n=n())
# 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
#> 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
(Intercept)       IQPre 
 24.0543105   0.8463595 
coef(lm(AvPost ~ IQPre, data = subset(Pygmalion, Treatment == 0)))   # Controls
(Intercept)       IQPre 
 32.6912117   0.7244454 
#> 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.

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

To_Predict <- data.frame(IQPre=mean(Pygmalion$IQPre), Treatment=as.factor(c(0, 1)))
predict(ANCOVA_Heterogeneity_IQ, newdata=To_Predict)
       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.

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

# 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
# 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))
[1] 1.612205
# 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))
[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.

# 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)))
[1] "Center of Accuracy (C_a) on the Pre-test IQ scale: 100.42"
# 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)))
[1] "Standard Error of the difference at C_a: 1.612"
# 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)))
[1] "Predicted Treatment Difference at C_a: 3.605"
# Conduct the t-test (Difference / Standard Error)
t_stat <- Predicted_Diff_Ca / SE_C_a
print(paste("t-statistic:", round(t_stat, 3)))
[1] "t-statistic: 2.237"
# 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)))
[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:

# Obtain W^2 for simultaneous regions of significance
N <- nrow(Pygmalion)
W2 <- 2 * qf(.95, df1 = 2, df2 = N - 4)
W2
[1] 6.050506
#> 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.

# 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)
[1] 3.554513
# Example: Estimated treatment effect at the mean of the covariate
D_X(ancova_model = ANCOVA_Heterogeneity_IQ, Xp = mean(Pygmalion$IQPre))
[1] 3.367316

We can verify this vertical distance by using the predict() function, just as we did when plotting the regression lines earlier:

# 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
       1        2 
104.0234 107.3907 
# The difference between these predictions matches the D(X) output
predictions[2] - predictions[1]
       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:

# 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")
--- Non-Simultaneous Region ---
 A: -0.012376 
 B: 1.682327 
 C: -210.1354 
 Lower Limit (X_LL): 97.22 
 Upper Limit (X_UL): 174.65 
# 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")
--- Simultaneous Region ---
 A: -0.027701 
 B: 3.221253 
 C: -370.3309 
 Lower Limit (X_LL): 103.89 
 Upper Limit (X_UL): 128.68 
#> 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.

# 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