Examples follow the book’s section numbers.
Chapter 4 tests individual comparisons of means:
single questions about a set of group means, each posed as a contrast
and each tested by comparing a full model against a restricted model
that forces the contrast to zero. Every worked example in the chapter
uses the hypothetical hypertension data of Table 4.1, which is
chapter_4_table_1 in the AMCP package.
Chapter 1 of these notes explains how to install the packages and how
AMCP names its data sets.
# Load all of the packages used.
library(dplyr) # data manipulation
library(AMCP) # the textbook's data sets
library(emmeans) # estimated marginal means and contrasts of them
library(DMAR) # design, measurement, and analysis
library(gt) # polished HTML tables
library(gtsummary) # publication-ready regression / comparison tables
library(modelsummary) # side-by-side model-comparison tablesTable 4.1 holds blood pressure readings for 20 mild hypertensives
assigned to four treatments. The group codes are spelled out one at a
time with case_when(), and factor() is then
used only to fix the level order to the book’s, so that Drug Therapy is
the reference group in every model fitted below.
bloodpr cond
1 84 1
2 95 1
3 93 1
4 104 1
5 81 2
6 84 2
7 92 2
8 101 2
9 80 2
10 108 2
11 98 3
12 95 3
13 86 3
14 87 3
15 94 3
16 91 4
17 78 4
18 85 4
19 80 4
20 81 4
Summary_4_1 <- chapter_4_table_1 |>
group_by(group) |>
summarize(
mean = mean(bloodpr),
median = median(bloodpr),
var = var(bloodpr),
sd = sd(bloodpr),
n = n()
) |>
as.data.frame()
# The conversion to a data frame matters for how Summary_4_1 is used later: a
# single bracketed value extracted from a data frame is a scalar, whereas the
# same extraction from a dplyr tibble returns a one-column tibble.
Summary_4_1 group mean median var sd n
1 Drug Therapy 94 94 67.33333 8.205689 4
2 Biofeedback 91 88 132.00000 11.489125 6
3 Diet 92 94 27.50000 5.244044 5
4 Combination 83 81 26.50000 5.147815 5
#> Means 94.0, 91.0, 92.0, 83.0 and variances 67.3, 132.0, 27.5, 26.5
#> on n = 4, 6, 5, 5 — matches Table 4.1, book p. 164The means and variances reproduce the bottom two rows of Table 4.1, and the unequal group sizes are the ones the book chose deliberately, so that the example illustrates the general case for testing comparisons.
Every test in the chapter that assumes homogeneity of variance uses the same error term, . It can be built directly from the definition as the weighted mean of the within-group variances, or read off an analysis of variance table.
# Method 1: the pooled within-group variance, straight from the definition.
MS_within <- sum(Summary_4_1$var * (Summary_4_1$n - 1)) / sum(Summary_4_1$n - 1)
MS_within[1] 67.375
# Method 2: extracting the same quantity from a fitted ANOVA.
ANOVA_Object <- aov(bloodpr ~ group, data = chapter_4_table_1)
ANOVA_4_1 <- anova(ANOVA_Object)
ANOVA_4_1Analysis of Variance Table
Response: bloodpr
Df Sum Sq Mean Sq F value Pr(>F)
group 3 334.55 111.517 1.6552 0.2165
Residuals 16 1078.00 67.375
[1] 334.55 1078.00
#> 334.55 — matches book p. 182; 1078.00 — matches book p. 165 (E_F) and p. 183
MS_b <- ANOVA_4_1$"Mean Sq"[1]
MS_w <- ANOVA_4_1$"Mean Sq"[2]
c(MS_b, MS_w)[1] 111.5167 67.3750
The book notes in passing that an omnibus test of these data would return , nonsignificant at the .05 level, and then sets the omnibus question aside in favor of contrasts. The omnibus is itself a model comparison: the full cell-means model against the restricted model that allows only a grand mean.
fit_grand <- lm(bloodpr ~ 1, data = chapter_4_table_1) # grand mean only
fit_full <- lm(bloodpr ~ group, data = chapter_4_table_1) # one mean per group
anova(fit_grand, fit_full)Analysis of Variance Table
Model 1: bloodpr ~ 1
Model 2: bloodpr ~ group
Res.Df RSS Df Sum of Sq F Pr(>F)
1 19 1412.5
2 16 1078.0 3 334.55 1.6552 0.2165
The same omnibus analysis as an APA-style table — sums of squares,
df, MS, , , and the proportion of total
variability associated with the group effect. The table is built with
gt from the anova() output rather than
from a tidying helper, which keeps the chapter’s dependency stack to the
packages it actually needs. The last column is of the book’s
Equation 4.45 (p. 182), which in a one-way design is also what software
labels partial .
anova_table <- data.frame(
Source = c("Between (Treatment)", "Within (Error)"),
SS = ANOVA_4_1$"Sum Sq",
df = ANOVA_4_1$"Df",
MS = ANOVA_4_1$"Mean Sq",
Fstat = ANOVA_4_1$"F value",
p = ANOVA_4_1$"Pr(>F)",
R2 = c(SS_b / (SS_b + SS_w), NA_real_)
)
anova_table |>
gt() |>
fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
fmt_number(columns = R2, decimals = 3) |>
fmt_number(columns = p, decimals = 4) |>
sub_missing(missing_text = "") |>
cols_label(Fstat = md("*F*"), p = md("*p*"), R2 = md("*R*<sup>2</sup>")) |>
tab_header(title = md("**Omnibus analysis of variance for the Table 4.1 blood pressure data**")) |>
cols_align(align = "center", columns = -Source)| Omnibus analysis of variance for the Table 4.1 blood pressure data | ||||||
| Source | SS | df | MS | F | p | R2 |
|---|---|---|---|---|---|---|
| Between (Treatment) | 334.55 | 3 | 111.52 | 1.66 | 0.2165 | 0.237 |
| Within (Error) | 1,078.00 | 16 | 67.38 | |||
modelsummary places the restricted and full models side by side, with the fit statistics at the foot:
modelsummary(
list("Restricted (grand mean)" = fit_grand, "Full (group means)" = fit_full),
estimate = "{estimate}",
statistic = "({std.error})", # standard errors in parentheses, APA style
gof_map = c("nobs", "aic", "bic", "logLik"),
stars = TRUE,
output = "gt"
)| Restricted (grand mean) | Full (group means) | |
|---|---|---|
| (Intercept) | 89.850 | 94.000 |
| (1.928) | (4.104) | |
| groupBiofeedback | -3.000 | |
| (5.298) | ||
| groupDiet | -2.000 | |
| (5.506) | ||
| groupCombination | -11.000 | |
| (5.506) | ||
| Num.Obs. | 20 | 20 |
| AIC | 145.9 | 146.5 |
| BIC | 147.9 | 151.5 |
| Log.Lik. | -70.953 | -68.250 |
| + p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001 | ||
The same two models as a gtsummary table, each under
its own spanning header. The full model adds the three group-difference
terms — each treatment relative to Drug Therapy, the first level of
group — that the restricted model leaves out:
t_restricted <- tbl_regression(fit_grand, intercept = TRUE)
t_full <- tbl_regression(fit_full, intercept = TRUE)
# quiet = TRUE: the two models have different numbers of coefficient rows, which
# is expected here (the full model adds the group terms).
tbl_merge(list(t_restricted, t_full),
tab_spanner = c("**Restricted (grand mean)**", "**Full (group means)**"),
quiet = TRUE)| Characteristic |
Restricted (grand mean)
|
Full (group means)
|
||||
|---|---|---|---|---|---|---|
| Beta | 95% CI | p-value | Beta | 95% CI | p-value | |
| (Intercept) | 90 | 86, 94 | <0.001 | 94 | 85, 103 | <0.001 |
| group | ||||||
| Drug Therapy | — | — | ||||
| Biofeedback | -3.0 | -14, 8.2 | 0.6 | |||
| Diet | -2.0 | -14, 9.7 | 0.7 | |||
| Combination | -11 | -23, 0.67 | 0.063 | |||
| Abbreviation: CI = Confidence Interval | ||||||
The hypothesis the book tests is whether drug therapy and biofeedback are equally effective, . Table 4.2 (p. 165) shows two equivalent routes to it, and two further routes are added here. All four use only base R.
Approach 1: the definitional formulas of Equation 4.12 (p. 162). Although this approach does not take advantage of some features of R and packages, it is useful to see the analysis in this way, as it corresponds with the book and allows one to more fully investigate aspects of data that might be missed using a more automated approach.
# Corresponds to the lower half of Table 4.2 in the book.
# For ease, separate the data into their corresponding groups
# (so that the summary statistics can be used).
Group_1 <- chapter_4_table_1[chapter_4_table_1$cond == 1, "bloodpr"]
Group_2 <- chapter_4_table_1[chapter_4_table_1$cond == 2, "bloodpr"]
Group_3 <- chapter_4_table_1[chapter_4_table_1$cond == 3, "bloodpr"]
Group_4 <- chapter_4_table_1[chapter_4_table_1$cond == 4, "bloodpr"]
# Descriptive statistics.
Y_bar1 <- mean(Group_1); s2_1 <- var(Group_1); n_1 <- length(Group_1)
Y_bar2 <- mean(Group_2); s2_2 <- var(Group_2); n_2 <- length(Group_2)
Y_bar3 <- mean(Group_3); s2_3 <- var(Group_3); n_3 <- length(Group_3)
Y_bar4 <- mean(Group_4); s2_4 <- var(Group_4); n_4 <- length(Group_4)
# Under the restricted model groups 1 and 2 share one mean, Y-bar-star.
Y_bar_Star <- mean(c(Group_1, Group_2))
Y_bar_Star[1] 92.2
#> 92.2 — matches book p. 165
N <- nrow(chapter_4_table_1)
a <- length(unique(chapter_4_table_1$cond))
# Model comparisons.
df_R <- N - (a - 1)
df_F <- N - a
c(df_R, df_F)[1] 17 16
#> 17 and 16 — matches book p. 165
E_F <- sum((Group_1 - Y_bar1)^2) + sum((Group_2 - Y_bar2)^2) +
sum((Group_3 - Y_bar3)^2) + sum((Group_4 - Y_bar4)^2)
E_F[1] 1078
#> 1078.00 — matches book p. 165
E_R <- sum((Group_1 - Y_bar_Star)^2) + sum((Group_2 - Y_bar_Star)^2) +
sum((Group_3 - Y_bar3)^2) + sum((Group_4 - Y_bar4)^2)
E_R[1] 1099.6
#> 1099.60 — matches book p. 165
# The four component sums the book prints on the way to E_R.
c(sum((Group_1 - Y_bar_Star)^2), sum((Group_2 - Y_bar_Star)^2),
sum((Group_3 - Y_bar3)^2), sum((Group_4 - Y_bar4)^2))[1] 214.96 668.64 110.00 106.00
#> 214.96, 668.64, 110.00, 106.00 — matches book p. 165
# Named F_obs rather than F: R reads a bare `F` as an abbreviation for FALSE,
# so assigning to it would mask the built-in constant for the rest of the session.
F_obs <- ((E_R - E_F) / (df_R - df_F)) / (E_F / df_F)
F_obs[1] 0.3205937
#> 0.32 — matches book p. 165 (Table 4.2)
# A single contrast is tested against an F with df_R - df_F = 1 numerator df and
# df_F = N - a = 16 denominator df (the book, p. 164, reports "1 and 16 degrees
# of freedom"), not against the omnibus F(a - 1, N - 1).
1 - pf(F_obs, df_R - df_F, df_F)[1] 0.579107
[1] 4.493998
Approach 2: Equation 4.18 (p. 163), the computationally simpler form available whenever the comparison is pairwise.
[1] 0.3205937
[1] 0.579107
Approach 3: the restricted model read off the
dplyr summary table. Some of the values from above
are repeated here for completeness. Note that the way objects are
extracted from the summary table Summary_4_1 requires the
conversion of the dplyr tibble to a data frame (see the
descriptive-statistics chunk above).
Y_bar_star <- mean(chapter_4_table_1[chapter_4_table_1$group %in%
c("Drug Therapy", "Biofeedback"),
"bloodpr"])
E_R <- sum((chapter_4_table_1[chapter_4_table_1$group %in%
c("Drug Therapy", "Biofeedback"),
"bloodpr"] - Y_bar_star)^2) +
sum((chapter_4_table_1[chapter_4_table_1$group == "Diet", "bloodpr"] -
Summary_4_1[Summary_4_1$group == "Diet", "mean"])^2) +
sum((chapter_4_table_1[chapter_4_table_1$group == "Combination", "bloodpr"] -
Summary_4_1[Summary_4_1$group == "Combination", "mean"])^2)
# From the previously performed ANOVA.
E_F <- SS_w
F_obs <- ((E_R - E_F) / (df_R - df_F)) / (E_F / df_F)
c(E_R, E_F, F_obs)[1] 1099.6000000 1078.0000000 0.3205937
#> 1099.60, 1078.00, 0.32 — matches book p. 165
# Same single-contrast reference distribution as above: F(1, N - a) = F(1, 16).
1 - pf(F_obs, df_R - df_F, df_F)[1] 0.579107
Approach 4: c-weights, Equation 4.32 (p. 170), with the mean square within obtained earlier from the ANOVA. Equation 4.32 is developed in §4.5 for contrasts in general; applied to a pairwise contrast it returns the Table 4.2 result.
c_weights <- c(1, -1, 0, 0)
Ybar <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
n <- c(n_1, n_2, n_3, n_4)
Psi <- sum(c_weights * Ybar)
Psi[1] 3
#> psi-hat = 3.00 — matches Table 4.4, book p. 177
F_obs <- (Psi^2 / sum(c_weights^2 / n)) / MS_w
F_obs[1] 0.3205937
#> 0.32 — matches book p. 165 (Table 4.2)
# A contrast carries 1 numerator df, tested against F(1, N - a) = F(1, 16).
1 - pf(F_obs, 1, N - a)[1] 0.579107
The book’s point is that a contrast is a comparison of two
models, so it is worth fitting both models and handing them to
anova(). The restricted model that forces is simply the cell-means
model with groups 1 and 2 collapsed into one level, and
anova() then reports , , their difference, and the of Table 4.2 in one line.
chapter_4_table_1 <- chapter_4_table_1 |>
mutate(group_R = case_when(
cond %in% c(1, 2) ~ "Drug Therapy or Biofeedback",
cond == 3 ~ "Diet",
cond == 4 ~ "Combination"
))
fit_full_cells <- lm(bloodpr ~ group - 1, data = chapter_4_table_1)
fit_restricted <- lm(bloodpr ~ group_R - 1, data = chapter_4_table_1)
anova(fit_restricted, fit_full_cells)Analysis of Variance Table
Model 1: bloodpr ~ group_R - 1
Model 2: bloodpr ~ group - 1
Res.Df RSS Df Sum of Sq F Pr(>F)
1 17 1099.6
2 16 1078.0 1 21.6 0.3206 0.5791
emmeans is the mainstream route to contrasts of fitted means, and it reproduces the “assumes equal variances” half of the book’s Table 4.4 (p. 177) directly: the value of the contrast, its standard error, , its degrees of freedom, and the two-tailed value. Squaring returns the of Table 4.2, exactly as the book notes on p. 177.
group emmean SE df lower.CL upper.CL
Drug Therapy 94 4.10 16 85.3 102.7
Biofeedback 91 3.35 16 83.9 98.1
Diet 92 3.67 16 84.2 99.8
Combination 83 3.67 16 75.2 90.8
Confidence level used: 0.95
contrast_pairwise <- contrast(emm_groups,
method = list("Drug Therapy vs. Biofeedback" = c(1, -1, 0, 0)),
adjust = "none")
contrast_pairwise contrast estimate SE df t.ratio p.value
Drug Therapy vs. Biofeedback 3 5.3 16 0.566 0.5791
# The same result at full precision, so the standard error can be read against
# the book's.
as.data.frame(contrast_pairwise) contrast estimate SE df t.ratio p.value
Drug Therapy vs. Biofeedback 3 5.298388 16 0.566 0.5791
#> estimate 3.00, SE 5.298, df 16, t = 0.566, p = .579
#> — matches Table 4.4, book p. 177
summary(contrast_pairwise)$t.ratio^2[1] 0.3205937
The tests above answer only whether the contrast differs from zero.
DMAR’s ci_sc() adds what none of them gives: a confidence
interval on the standardized contrast, built by inverting the
noncentral distribution. The
interval includes zero, consistent with the nonsignificant above; the point estimate is the
standardized difference the book reports in §4.8.1.2.
Ybar_groups <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
n_groups <- c(n_1, n_2, n_3, n_4)
ci_sc(
means = Ybar_groups,
s_anova = sqrt(MS_w),
c_weights = c(1, -1, 0, 0),
n_per_group = n_groups,
N = sum(n_groups),
conf_level = 0.95
)| term | value |
|---|---|
| ci_lower | -0.911 |
| std_contrast | 0.365 |
| ci_upper | 1.631 |
Confidence level: 95%
The contrast of interest is now the combined treatment against the average of the other three. Other than the c-weights, the code is the same as for the pairwise contrast.
# Corresponds to the upper half of Table 4.3.
c_weights <- c(1/3, 1/3, 1/3, -1)
Ybar <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
n <- c(n_1, n_2, n_3, n_4)
Psi <- sum(c_weights * Ybar)
Psi[1] 9.333333
#> 9.33 — the contrast Table 4.3 writes as (92.33 - 83), book p. 171; the
#> value 9.33 itself is printed on p. 180
sum(c_weights^2 / n)[1] 0.2685185
[1] 4.815047
#> 4.82 — matches book p. 171 (Table 4.3)
# Like every single contrast, this one is tested against F(1, N - a) = F(1, 16).
# The book (p. 171) notes F = 4.82 exceeds the critical value of 4.49 for 1 and
# 16 df, so the complex comparison is significant; testing against F(a - 1, N - 1)
# would use the wrong reference distribution.
1 - pf(F_obs, 1, N - a)[1] 0.04332063
The lower half of Table 4.3 works the same contrast through Equation
4.12, and the book remarks that the least squares estimates under the
restricted model are tedious to find by hand. They are not tedious for
lm(). The restriction says ; substituting that into the cell-means model
leaves three free parameters, whose predictors are the group-1, group-2,
and group-3 indicators each plus one third of the group-4 indicator.
X_cells <- model.matrix(~ group - 1, data = chapter_4_table_1)
chapter_4_table_1$x1 <- X_cells[, 1] + X_cells[, 4] / 3
chapter_4_table_1$x2 <- X_cells[, 2] + X_cells[, 4] / 3
chapter_4_table_1$x3 <- X_cells[, 3] + X_cells[, 4] / 3
fit_restricted_complex <- lm(bloodpr ~ x1 + x2 + x3 - 1, data = chapter_4_table_1)
# The three coefficients are mu-hat 1 to 3 under the restriction, and the fourth
# mean is their average.
mu_restricted <- unname(c(coef(fit_restricted_complex),
mean(coef(fit_restricted_complex))))
round(mu_restricted, 3)[1] 91.103 89.069 89.683 89.952
[1] 0
#> zero, to within floating-point rounding: the restriction the book checks
#> on p. 172
anova(fit_restricted_complex, fit_full_cells)Analysis of Variance Table
Model 1: bloodpr ~ x1 + x2 + x3 - 1
Model 2: bloodpr ~ group - 1
Res.Df RSS Df Sum of Sq F Pr(>F)
1 17 1402.4
2 16 1078.0 1 324.41 4.815 0.04332 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
The book’s Table 4.4 enters this contrast with the whole-number weights 1, 1, 1, , which multiply both the contrast and its standard error by three. Entering both weightings in emmeans shows that , the degrees of freedom, and are unchanged, while only the scale of the estimate moves.
contrast_complex <- contrast(emm_groups,
method = list(
"Combination vs. others (1, 1, 1, -3)" = c(1, 1, 1, -3),
"Combination vs. others (1/3, 1/3, 1/3, -1)" = c(1/3, 1/3, 1/3, -1)
),
adjust = "none")
contrast_complex contrast estimate SE df t.ratio p.value
Combination vs. others (1, 1, 1, -3) 28.00 12.80 16 2.194 0.0433
Combination vs. others (1/3, 1/3, 1/3, -1) 9.33 4.25 16 2.194 0.0433
contrast estimate SE df t.ratio
Combination vs. others (1, 1, 1, -3) 28.000000 12.760208 16 2.194
Combination vs. others (1/3, 1/3, 1/3, -1) 9.333333 4.253403 16 2.194
p.value
0.0433
0.0433
DMAR’s ci_c() and ci_sc() add intervals on
the raw and the standardized contrast. Both exclude zero, consistent
with the significant .
c_complex <- c(1/3, 1/3, 1/3, -1)
# Raw (unstandardized) contrast, in mm Hg:
ci_c(
means = Ybar_groups,
s_anova = sqrt(MS_w),
c_weights = c_complex,
n_per_group = n_groups,
N = sum(n_groups),
conf_level = 0.95
)| term | value |
|---|---|
| ci_lower | 0.317 |
| contrast | 9.333 |
| ci_upper | 18.350 |
Confidence level: 95%
#> 9.33, with limits 0.317 and 18.350 — matches the 9.33 +/- 9.01 on book p. 180
# Standardized contrast (psi / sigma):
ci_sc(
means = Ybar_groups,
s_anova = sqrt(MS_w),
c_weights = c_complex,
n_per_group = n_groups,
N = sum(n_groups),
conf_level = 0.95
)| term | value |
|---|---|
| ci_lower | 0.033 |
| std_contrast | 1.137 |
| ci_upper | 2.210 |
Confidence level: 95%
Here we do not assume homogeneity of variance for a contrast. We repeat some of the code from above for completeness. Note that the way we write the code, which matches how it is displayed in the book, is due to R’s “vectorized arithmetic” (and thus making the equations in the R code mimic those in the book). Equation 4.33 (p. 174) supplies the denominator and Equation 4.34 (p. 174) the Satterthwaite degrees of freedom. The two contrasts are the ones in the lower half of the book’s Table 4.4.
Ybar <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
s2 <- c(s2_1, s2_2, s2_3, s2_4)
n <- c(n_1, n_2, n_3, n_4)
# Contrast 1: the pairwise comparison.
c1 <- c(1, -1, 0, 0)
Psi1 <- sum(Ybar * c1)
var_Psi1 <- sum((c1^2 / n) * s2)
F1 <- Psi1^2 / var_Psi1
df1 <- sum(c1^2 * s2 / n)^2 / sum((c1^2 * s2 / n)^2 / (n - 1))
c(Psi1, sqrt(var_Psi1), sqrt(F1), df1)[1] 3.0000000 6.2316397 0.4814142 7.8849599
[1] 0.6432981
#> .643 — matches Table 4.4, book p. 177
# Contrast 2: the complex comparison.
# Notice we use fractional c-weights, whereas the book uses whole numbers; the
# scale of the weights cancels out of F and out of the degrees of freedom.
c2 <- c(1/3, 1/3, 1/3, -1)
Psi2 <- sum(Ybar * c2)
var_Psi2 <- sum((c2^2 / n) * s2)
F2 <- Psi2^2 / var_Psi2
df2 <- sum(c2^2 * s2 / n)^2 / sum((c2^2 * s2 / n)^2 / (n - 1))
c(Psi2 * 3, sqrt(var_Psi2) * 3, sqrt(F2), df2)[1] 28.000000 9.593401 2.918673 11.034012
[1] 0.01392933
The pairwise comparison stays nonsignificant and loses both and degrees of freedom, while the complex comparison becomes more significant, its rising from 2.19 to 2.92. The book explains why on pp. 177–178: the complex contrast puts the largest weight on group 4, which has the smallest variance in these data, so the separate-variance denominator is smaller than here. The approach is not uniformly more conservative; only its denominator degrees of freedom necessarily are.
When the contrast is pairwise, the separate-variance test is exactly Welch’s two-sample test, so base R gives it with no hand computation at all. The arguments are spelled out rather than left to defaults, so the call documents the analyst’s choices.
drug <- chapter_4_table_1[chapter_4_table_1$cond == 1, "bloodpr"]
bio <- chapter_4_table_1[chapter_4_table_1$cond == 2, "bloodpr"]
t.test(
x = drug,
y = bio,
alternative = "two.sided",
paired = FALSE,
var.equal = FALSE,
conf.level = 0.95
)
Welch Two Sample t-test
data: drug and bio
t = 0.48141, df = 7.885, p-value = 0.6433
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-11.40676 17.40676
sample estimates:
mean of x mean of y
94 91
DMAR’s welch_t() returns the identical test as a tidy
data.frame rather than as a printed htest
object, which is what it adds: the result composes with
dplyr when many such tests are collected into one table,
and it reports the two group standard deviations and sample sizes
alongside the test.
| term | value |
|---|---|
| mean_difference | 3.000 |
| t_value | 0.481 |
| df | 7.885 |
| p_value | 0.6433 |
| ci_lower | -11.407 |
| ci_upper | 17.407 |
| mean_x | 94.000 |
| mean_y | 91.000 |
| sd_x | 8.206 |
| sd_y | 11.489 |
| n_x | 4 |
| n_y | 6 |
Confidence level: 95%
Equation 4.40 (p. 179) builds the interval from the contrast, the critical , and the standard error of the contrast under homogeneity of variance. The book works both intervals this way on p. 180 from the Table 4.4 output.
F_crit <- qf(0.95, 1, N - a)
se_Psi1 <- sqrt(MS_w * sum(c1^2 / n))
se_Psi2 <- sqrt(MS_w * sum(c2^2 / n))
c(se_Psi1, se_Psi2 * 3)[1] 5.298388 12.760208
#> 5.298 and 12.760 — matches Table 4.4, book p. 177
# Pairwise comparison.
c(Psi1, sqrt(F_crit) * se_Psi1)[1] 3.00000 11.23208
[1] -8.232081 14.232081
#> -8.23 to 14.23 — matches book p. 180
# Complex comparison, in the metric in which the coefficients sum in absolute
# value to 2, which is what makes the interval a difference between means.
c(Psi2, sqrt(F_crit) * se_Psi2)[1] 9.333333 9.016811
[1] 0.3165222 18.3501444
#> 0.32 to 18.35 — matches the 0.32 to 18.34 on book p. 180, which the book
#> obtains by adding its rounded 9.33 and 9.01Equation 4.41 (p. 179) relaxes homogeneity of variance by replacing the error term with the separate-variance denominator and the degrees of freedom with the Satterthwaite value. The book is deliberately slightly conservative on p. 180, using 7 denominator degrees of freedom for the pairwise contrast instead of 7.885.
[1] 14.73549
#> half-width 14.73, so 3.0 +/- 14.73 — matches book p. 180
# Complex comparison, at the Satterthwaite df of 11.034.
sqrt(qf(0.95, 1, df2)) * sqrt(var_Psi2)[1] 7.035665
DMAR’s ci_c() computes the two equal-variance intervals
directly from the group summaries.
groups <- split(chapter_4_table_1$bloodpr, chapter_4_table_1$cond)
Y_bar <- sapply(groups, mean)
n <- sapply(groups, length)
ci_c(
means = Y_bar,
c_weights = c(1, -1, 0, 0),
n_per_group = n,
N = N,
s_anova = sqrt(MS_w),
conf_level = 0.95
)| term | value |
|---|---|
| ci_lower | -8.232 |
| contrast | 3.000 |
| ci_upper | 14.232 |
Confidence level: 95%
#> -8.232 to 14.232 — matches book p. 180
ci_c(
means = Y_bar,
c_weights = c(1/3, 1/3, 1/3, -1),
n_per_group = n,
N = N,
s_anova = sqrt(MS_w),
conf_level = 0.95
)| term | value |
|---|---|
| ci_lower | 0.317 |
| contrast | 9.333 |
| ci_upper | 18.350 |
Confidence level: 95%
Equation 4.44 (p. 181) standardizes a contrast by , with the factor that keeps the result a difference between means however the coefficients happen to be scaled.
[1] 0.3654869
[1] 1.13707
DMAR’s ci_sc() inverts the noncentral distribution to give a confidence
interval on the standardized scale.
ci_sc(
means = Y_bar,
c_weights = c(1, -1, 0, 0),
n_per_group = n,
N = N,
s_anova = sqrt(MS_w),
conf_level = 0.95
)| term | value |
|---|---|
| ci_lower | -0.911 |
| std_contrast | 0.365 |
| ci_upper | 1.631 |
Confidence level: 95%
#> 0.365, limits -0.911 to 1.631
ci_sc(
means = Y_bar,
c_weights = c(1/3, 1/3, 1/3, -1),
n_per_group = n,
N = N,
s_anova = sqrt(MS_w),
conf_level = 0.95
)| term | value |
|---|---|
| ci_lower | 0.033 |
| std_contrast | 1.137 |
| ci_upper | 2.210 |
Confidence level: 95%
The book cautions on p. 181 against reading a verbal label off a standardized difference: the interval for the pairwise contrast includes zero, so describing that difference as “small to medium” would overstate what the data support. The intervals above are what makes that caution checkable.
For the pairwise comparison, DMAR translates the same standardized difference into scales an applied audience reads more easily: the proportion of superiority (U3), the common-language effect size (CLES), and the number needed to treat (NNT). Each is a function of , so each carries the same uncertainty, which the accompanying intervals make explicit.
| term | value |
|---|---|
| smd | 0.365 |
| proportion_of_superiority | 0.643 |
| smd_ci_lower | -0.923 |
| smd_ci_upper | 1.632 |
| ci_lower | 0.178 |
| ci_upper | 0.949 |
Confidence level: 95%
| term | value |
|---|---|
| smd | 0.365 |
| cles | 0.602 |
| smd_ci_lower | -0.923 |
| smd_ci_upper | 1.632 |
| cles_ci_lower | 0.257 |
| cles_ci_upper | 0.876 |
Confidence level: 95%
| term | value |
|---|---|
| smd | 0.365 |
| srd | 0.204 |
| nnt | 4.904 |
| smd_ci_lower | -0.923 |
| smd_ci_upper | 1.632 |
| nnt_ci_lower | NA |
| nnt_ci_upper | NA |
| srd_ci_lower | -0.486 |
| srd_ci_upper | 0.751 |
Confidence level: 95%
The interval for the SRD includes 0, so the confidence set for the NNT is two intervals: NNT <= -2.058 (harm) or NNT >= 1.331 (benefit), joined at infinity (Altman, 1998)
The three measures of association strength for a contrast share the numerator and differ in the denominator, so the sums of squares for the two contrasts are computed once here and reused.
Y_bars <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
n <- c(n_1, n_2, n_3, n_4)
c_weights_1 <- c(1, -1, 0, 0)
Psi_1 <- sum(c_weights_1 * Y_bars)
SS_Psi_1 <- Psi_1^2 / sum(c_weights_1^2 / n)
SS_Psi_1[1] 21.6
#> 21.60 — matches book p. 182
c_weights_2 <- c(1/3, 1/3, 1/3, -1)
Psi_2 <- sum(c_weights_2 * Y_bars)
SS_Psi_2 <- Psi_2^2 / sum(c_weights_2^2 / n)
SS_Psi_2[1] 324.4138
Equation 4.46 (p. 182) divides the contrast’s sum of squares by the between-group sum of squares, which says how much of the difference among the groups that one contrast has captured.
[1] 334.55
#> 334.55 — matches book p. 182
R2_alerting_1 <- SS_Psi_1 / SS_b
R2_alerting_2 <- SS_Psi_2 / SS_b
c(R2_alerting_1, R2_alerting_2)[1] 0.06456434 0.96970197
Almost all of the variability among the four groups is captured by the fact that the combined group differs from the other three. The two percentages sum to more than 100%, which the book flags on pp. 182–183 as a case where adding them is not meaningful, and takes up again in §4.10.3 below.
Equation 4.47 (p. 183) keeps the same numerator and divides instead by the total sum of squares, so it reports the share of total variability associated with the contrast.
[1] 1412.55
#> 1412.55 — matches book p. 183
R2_effect_size_1 <- SS_Psi_1 / SS_T
R2_effect_size_2 <- SS_Psi_2 / SS_T
c(R2_effect_size_1, R2_effect_size_2)[1] 0.01529149 0.22966535
Equation 4.48 (p. 184) divides by the contrast’s own sum of squares plus the within-group sum of squares, which removes the influence of groups that the contrast does not involve.
R2_contrast_1 <- SS_Psi_1 / (SS_Psi_1 + SS_w)
R2_contrast_2 <- SS_Psi_2 / (SS_Psi_2 + SS_w)
c(R2_contrast_1, R2_contrast_2)[1] 0.01964351 0.23132530
The step the book takes next is to compute from only the groups the contrast
involves. The sum of squares for the contrast does not change with the
reduction in groups, but the sum of squares within does;
_12 marks the objects that concern only groups 1 and 2. As
the book states, “our general preference is to base only on the groups
actually involved in the comparison” (p. 184).
ANOVA_Object_12 <- aov(bloodpr ~ group,
data = chapter_4_table_1[chapter_4_table_1$cond %in% c(1, 2), ])
ANOVA_4_1_12 <- anova(ANOVA_Object_12)
SS_w_12 <- ANOVA_4_1_12$"Sum Sq"[2]
R2_contrast_1_12 <- SS_Psi_1 / (SS_Psi_1 + SS_w_12)
R2_contrast_1_12[1] 0.02444545
The book plans a study with 20 participants per group and the population means , , , , with . Equation 4.52 (p. 186) gives for the “exemplary dataset”, and Equation 4.53 says that for a contrast the noncentrality parameter is just , because the numerator has a single degree of freedom.
# Population parameters.
mu_Drug <- 90
mu_Bio <- 92
mu_Diet <- 88
mu_Combo <- 81
sigma <- 12
n <- 20
# Define the contrast weights.
c_weights <- c(1/3, 1/3, 1/3, -1)
mu_vector <- c(mu_Drug, mu_Bio, mu_Diet, mu_Combo)
# The value of the contrast in the population.
psi <- sum(c_weights * mu_vector)
psi[1] 9
#> 9 — matches book p. 186
# The noncentrality parameter, Equations 4.52 and 4.53.
sum_c_squared <- sum(c_weights^2)
lambda <- (n * psi^2) / (sum_c_squared * sigma^2)
lambda[1] 8.4375
#> 8.4375 — matches book p. 186
# Degrees of freedom: numerator 1, denominator N - a = 80 - 4 = 76.
df1 <- 1
df2 <- (4 * n) - 4
alpha <- 0.05
F_crit <- qf(1 - alpha, df1, df2)
F_crit[1] 3.96676
[1] 0.8180309
The book contrasts this with the power of the omnibus test under the same population parameters, which is lower.
sigma_m <- sqrt(sum((mu_vector - mean(mu_vector))^2) / 4) # Equation 3.90
f_omnibus <- sigma_m / sigma # Equation 3.91
lambda_omnibus <- (4 * n) * f_omnibus^2 # Equation 4.49
1 - pf(qf(0.95, 3, 4 * n - 4), 3, 4 * n - 4, ncp = lambda_omnibus)[1] 0.7149725
Equation 4.56 (p. 188) rewrites the same information as an effect size for the contrast, which is what power software such as G*Power or WebPower asks for.
[1] 0.3247595
DMAR’s ss_power_contrast() takes the expected means, the
within-group variance, and the contrast weights, and returns the power
at a stated per-group sample size together with the noncentral parameter and the implied — so the three hand computations above
arrive in one object. Replacing specified_n_per_group with
desired_power turns the same planner around and solves for
the sample size instead, which the book notes (p. 187) is the harder
direction by hand because the denominator degrees of freedom depend on
the answer.
ss_power_contrast(
c_weights = c(1/3, 1/3, 1/3, -1),
true_means = mu_vector,
true_var_error = sigma^2,
specified_n_per_group = n,
alpha_level = 0.05
)| term | value |
|---|---|
| specified_n_per_group | 20 |
| total_N | 80 |
| actual_power | 0.818 |
| noncentral_t_parm | 2.905 |
| true_f | 0.325 |
#> actual_power 0.818 and true_f 0.325 — matches book pp. 187-188
ss_power_contrast(
c_weights = c(1/3, 1/3, 1/3, -1),
true_means = mu_vector,
true_var_error = sigma^2,
desired_power = 0.80,
alpha_level = 0.05
)| term | value |
|---|---|
| necessary_n_per_group | 20 |
| total_N | 80 |
| actual_power | 0.818 |
| noncentral_t_parm | 2.905 |
| true_f | 0.325 |
For accuracy in parameter estimation, the book asks for 90% assurance
that the full width of the 95% confidence interval is at most 5 points
(half-width 2.5). DMAR’s ss_aipe_c() computes the group
size for each contrast.
ss_aipe_c(
true_var_error = 12^2,
c_weights = c(0, 1, -1, 0),
width = 5,
conf_level = 0.95,
assurance = 0.90
)| term | value |
|---|---|
| necessary_n_per_group | 190 |
Confidence level: 95%
#> 190 per group — 760 in total, as on book p. 188
ss_aipe_c(
true_var_error = 12^2,
c_weights = c(1/3, 1/3, 1/3, -1),
width = 5,
conf_level = 0.95,
assurance = 0.90
)| term | value |
|---|---|
| necessary_n_per_group | 129 |
Confidence level: 95%
Equation 4.61 (p. 191) defines two contrasts as orthogonal, with equal sample sizes, when the sum of the products of their coefficients is zero. Here we define a matrix in which the rows represent contrasts of interest, for and two contrasts. These are the and of the book’s Equation 4.60.
C_Matrix <- rbind(Psi1 = c(1, -1, 0), Psi2 = c(1, 0, -1))
# First, verify that the sum of the c-weights is zero (it is below, continue).
apply(C_Matrix, MARGIN = 1, FUN = sum)Psi1 Psi2
0 0
# Check if the sum of the products of c-weights is zero (it is not below;
# these are nonorthogonal contrasts).
sum(C_Matrix["Psi1", ] * C_Matrix["Psi2", ])[1] 1
Replacing with the book’s gives an orthogonal pair instead.
C_Matrix2 <- rbind(Psi1 = c(1, -1, 0), Psi3 = c(1/2, 1/2, -1))
# First, verify that the sum of the c-weights is zero.
apply(C_Matrix2, MARGIN = 1, FUN = sum)Psi1 Psi3
0 0
# Check if the sum of the products of c-weights is zero (it is below; these are
# orthogonal contrasts).
sum(C_Matrix2["Psi1", ] * C_Matrix2["Psi3", ])[1] 0
For a set of more than two contrasts, Equation 4.61 has to be applied
times, once per distinct
pair. DMAR’s is_orthogonal_set() does that bookkeeping: it
reports every pairwise inner product, confirms that each contrast’s
weights sum to zero, and returns a single flag for whether the whole set
is mutually orthogonal. Following the DMAR convention, the contrasts are
the columns of the matrix. Below are the two pairs from above,
and then the three-contrast set on four groups that the book works
through on p. 192.
# The nonorthogonal pair from above (a = 3):
C_nonorth <- cbind(Psi1 = c(1, -1, 0), Psi2 = c(1, 0, -1))
is_orthogonal_set(C_nonorth)| term | value |
|---|---|
| all_orthogonal | 0 |
| all_contrasts_sum_to_zero | 1 |
| n_contrasts | 2 |
| dot[Psi1 . Psi2] | 1 |
#> all_orthogonal 0, inner product 1 — agrees with the base R check and book p. 191
# The orthogonal pair from above (a = 3):
C_orth <- cbind(Psi1 = c(1, -1, 0), Psi3 = c(1/2, 1/2, -1))
is_orthogonal_set(C_orth)| term | value |
|---|---|
| all_orthogonal | 1 |
| all_contrasts_sum_to_zero | 1 |
| n_contrasts | 2 |
| dot[Psi1 . Psi3] | 0 |
#> all_orthogonal 1, inner product 0 — agrees with the base R check and book p. 192
# The book's orthogonal set of three contrasts on four groups (p. 192):
C_three <- cbind(
Psi1 = c(1, -1, 0, 0),
Psi2 = c(1/2, 1/2, -1, 0),
Psi3 = c(1/3, 1/3, 1/3, -1)
)
is_orthogonal_set(C_three)| term | value |
|---|---|
| all_orthogonal | 1 |
| all_contrasts_sum_to_zero | 1 |
| n_contrasts | 3 |
| dot[Psi1 . Psi2] | 0 |
| dot[Psi1 . Psi3] | 0 |
| dot[Psi2 . Psi3] | 0 |
A set of groups admits at most mutually orthogonal contrasts, so three is the maximum here, and the book proves that bound on p. 192.
That bound also settles the loose end left in §4.8.2, where the two
values summed
to more than 100%. Orthogonality is the reason, and which condition
applies depends on the sample sizes: with equal the test is Equation 4.61, but the
Table 4.1 group sizes are unequal, so the condition is Equation 4.62
(p. 191), . Passing n_per_group to
is_orthogonal_set() switches it to that condition.
C_chapter <- cbind(Psi1 = c(1, -1, 0, 0), Psi2 = c(1/3, 1/3, 1/3, -1))
# Equation 4.61, the equal-n condition:
is_orthogonal_set(C_chapter)| term | value |
|---|---|
| all_orthogonal | 1 |
| all_contrasts_sum_to_zero | 1 |
| n_contrasts | 2 |
| dot[Psi1 . Psi2] | 0 |
# Equation 4.62, the condition that actually applies to these data:
is_orthogonal_set(C_chapter, n_per_group = c(n_1, n_2, n_3, n_4))| term | value |
|---|---|
| all_orthogonal | 0 |
| all_contrasts_sum_to_zero | 1 |
| n_contrasts | 2 |
| dot[Psi1 . Psi2] | 0.028 |
The chapter’s two contrasts would be orthogonal under equal sample sizes, but with they are not, so they carry overlapping information about how the groups differ and their values cannot be added.
The book. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.
This page. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Chapter 4: Individual Comparisons of Means (R code and instructions). Companion materials for Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). https://DesigningExperiments.com
These examples use DMAR 1.2.0. The printed book predates DMAR.
Arel-Bundock V (2026). modelsummary: Summary Tables and Plots for Statistical Models and Data: Beautiful, Customizable, and Publication-Ready. doi:10.32614/CRAN.package.modelsummary https://doi.org/10.32614/CRAN.package.modelsummary. R package version 2.6.0, https://CRAN.R-project.org/package=modelsummary.
Iannone R, Cheng J, Schloerke B, Haughton S, Hughes E, Lauer A, François R, Seo J, Brevoort K, Roy O (2026). gt: Easily Create Presentation-Ready Display Tables. doi:10.32614/CRAN.package.gt https://doi.org/10.32614/CRAN.package.gt. R package version 1.3.0, https://CRAN.R-project.org/package=gt.
Kelley K (2026). DMAR: Design, Measurement, and Analysis in R (DMAR). R package version 1.2.0, https://kenkelley.org.
Lenth R, Piaskowski J (2026). emmeans: Estimated Marginal Means, aka Least-Squares Means. doi:10.32614/CRAN.package.emmeans https://doi.org/10.32614/CRAN.package.emmeans. R package version 2.0.4, https://CRAN.R-project.org/package=emmeans.
Maxwell S, Delaney H, Kelley K (2026). AMCP: Data Sets to Accompany Designing Experiments and Analyzing Data: A Model Comparison Perspective (Maxwell, Delaney, and Kelley, 2027, 4th Edition). doi:10.32614/CRAN.package.AMCP https://doi.org/10.32614/CRAN.package.AMCP. R package version 2.0.0, https://CRAN.R-project.org/package=AMCP.
Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.
R Core Team (2026). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria. doi:10.32614/R.manuals https://doi.org/10.32614/R.manuals. https://www.R-project.org/.
Sjoberg D, Larmarange J, Curry M, de la Rua E, Lavery J, Whiting K, Zabor E (2026). gtsummary: Presentation-Ready Data Summary and Analytic Result Tables. doi:10.32614/CRAN.package.gtsummary https://doi.org/10.32614/CRAN.package.gtsummary. R package version 2.5.1, https://CRAN.R-project.org/package=gtsummary.
Wickham H, François R, Henry L, Müller K, Vaughan D (2026). dplyr: A Grammar of Data Manipulation. doi:10.32614/CRAN.package.dplyr https://doi.org/10.32614/CRAN.package.dplyr. R package version 1.2.1, https://CRAN.R-project.org/package=dplyr.