R Code and Instructions
On this page
- 4.4 — A Model Comparison Approach for Testing Individual Comparisons
- 4.4.4 — Numerical Example
- 4.5 — Complex Comparisons
- 4.5.2 — Numerical Example
- 4.7 — Unequal Population Variances
- 4.7.1 — Numerical Example
- 4.8 — Measures of Effect
- 4.8.1 — Measures of Effect Size
- 4.8.1.1 — Confidence Intervals
- 4.8.1.2 — Standardized Difference
- 4.8.2 — Measures of Association Strength
- 4.9 — Statistical Power
- Power for a specific contrast
- Sample size for a sufficiently narrow interval
- 4.10 — Testing More Than One Contrast
- 4.10.3 — Orthogonality of Contrasts
- How to Cite This Page
- References
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.
HideShow
# Load all of the packages used.
library(dplyr) # data manipulation
library(AMCP) # the textbook's data sets
library(emmeans) # estimated marginal means and contrasts of them
library(DMAR) # design, measurement, and analysis
library(gt) # polished HTML tables
library(gtsummary) # publication-ready regression / comparison tables
library(modelsummary) # side-by-side model-comparison tables4.4 — A Model Comparison Approach for Testing Individual Comparisons
4.4.4 — Numerical Example
The data of Table 4.1
Table 4.1 holds blood pressure readings for 20 mild hypertensives
assigned to four treatments. The group codes are spelled out one at a
time with case_when(), and factor() is then
used only to fix the level order to the book’s, so that Drug Therapy is
the reference group in every model fitted below.
HideShow
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 4Group descriptive statistics with dplyr
HideShow
Summary_4_1 <- chapter_4_table_1 |>
group_by(group) |>
summarize(
mean = mean(bloodpr),
median = median(bloodpr),
var = var(bloodpr),
sd = sd(bloodpr),
n = n()
) |>
as.data.frame()
# The conversion to a data frame matters for how Summary_4_1 is used later: a
# single bracketed value extracted from a data frame is a scalar, whereas the
# same extraction from a dplyr tibble returns a one-column tibble.
Summary_4_1HideShow
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 5The means and variances reproduce the bottom two rows of Table 4.1, and the unequal group sizes are the ones the book chose deliberately, so that the example illustrates the general case for testing comparisons.
The error term,
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.
HideShow
[1] 67.375HideShow
Analysis of Variance Table
Response: bloodpr
Df Sum Sq Mean Sq F value Pr(>F)
group 3 334.55 111.517 1.6552 0.2165
Residuals 16 1078.00 67.375 HideShow
[1] 334.55 1078.00HideShow
[1] 111.5167 67.3750The omnibus test
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.
HideShow
Analysis of Variance Table
Model 1: bloodpr ~ 1
Model 2: bloodpr ~ group
Res.Df RSS Df Sum of Sq F Pr(>F)
1 19 1412.5
2 16 1078.0 3 334.55 1.6552 0.2165The 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 .
HideShow
anova_table <- data.frame(
Source = c("Between (Treatment)", "Within (Error)"),
SS = ANOVA_4_1$"Sum Sq",
df = ANOVA_4_1$"Df",
MS = ANOVA_4_1$"Mean Sq",
Fstat = ANOVA_4_1$"F value",
p = ANOVA_4_1$"Pr(>F)",
R2 = c(SS_b / (SS_b + SS_w), NA_real_)
)
anova_table |>
gt() |>
fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
fmt_number(columns = R2, decimals = 3) |>
fmt_number(columns = p, decimals = 4) |>
sub_missing(missing_text = "") |>
cols_label(Fstat = md("*F*"), p = md("*p*"), R2 = md("*R*<sup>2</sup>")) |>
tab_header(title = md("**Omnibus analysis of variance for the Table 4.1 blood pressure data**")) |>
cols_align(align = "center", columns = -Source)| Omnibus analysis of variance for the Table 4.1 blood pressure data | ||||||
| Source | SS | df | MS | F | p | R2 |
|---|---|---|---|---|---|---|
| Between (Treatment) | 334.55 | 3 | 111.52 | 1.66 | 0.2165 | 0.237 |
| Within (Error) | 1,078.00 | 16 | 67.38 | |||
modelsummary places the restricted and full models side by side, with the fit statistics at the foot:
| Restricted (grand mean) | Full (group means) | |
|---|---|---|
| (Intercept) | 89.850 | 94.000 |
| (1.928) | (4.104) | |
| groupBiofeedback | -3.000 | |
| (5.298) | ||
| groupDiet | -2.000 | |
| (5.506) | ||
| groupCombination | -11.000 | |
| (5.506) | ||
| Num.Obs. | 20 | 20 |
| AIC | 145.9 | 146.5 |
| BIC | 147.9 | 151.5 |
| Log.Lik. | -70.953 | -68.250 |
| + p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001 | ||
The same two models as a gtsummary table, each under
its own spanning header. The full model adds the three group-difference
terms — each treatment relative to Drug Therapy, the first level of
group — that the restricted model leaves out:
HideShow
t_restricted <- tbl_regression(fit_grand, intercept = TRUE)
t_full <- tbl_regression(fit_full, intercept = TRUE)
# quiet = TRUE: the two models have different numbers of coefficient rows, which
# is expected here (the full model adds the group terms).
tbl_merge(list(t_restricted, t_full),
tab_spanner = c("**Restricted (grand mean)**", "**Full (group means)**"),
quiet = TRUE)| Characteristic |
Restricted (grand mean)
|
Full (group means)
|
||||
|---|---|---|---|---|---|---|
| Beta | 95% CI | p-value | Beta | 95% CI | p-value | |
| (Intercept) | 90 | 86, 94 | <0.001 | 94 | 85, 103 | <0.001 |
| group | ||||||
| Drug Therapy | — | — | ||||
| Biofeedback | -3.0 | -14, 8.2 | 0.6 | |||
| Diet | -2.0 | -14, 9.7 | 0.7 | |||
| Combination | -11 | -23, 0.67 | 0.063 | |||
| Abbreviation: CI = Confidence Interval | ||||||
Testing the pairwise comparison of Table 4.2
The hypothesis the book tests is whether drug therapy and biofeedback are equally effective, . Table 4.2 (p. 165) shows two equivalent routes to it, and two further routes are added here. All four use only base R.
Approach 1: the definitional formulas of Equation 4.12 (p. 162). Although this approach does not take advantage of some features of R and packages, it is useful to see the analysis in this way, as it corresponds with the book and allows one to more fully investigate aspects of data that might be missed using a more automated approach.
HideShow
# Corresponds to the lower half of Table 4.2 in the book.
# For ease, separate the data into their corresponding groups
# (so that the summary statistics can be used).
Group_1 <- chapter_4_table_1[chapter_4_table_1$cond == 1, "bloodpr"]
Group_2 <- chapter_4_table_1[chapter_4_table_1$cond == 2, "bloodpr"]
Group_3 <- chapter_4_table_1[chapter_4_table_1$cond == 3, "bloodpr"]
Group_4 <- chapter_4_table_1[chapter_4_table_1$cond == 4, "bloodpr"]
# Descriptive statistics.
Y_bar1 <- mean(Group_1); s2_1 <- var(Group_1); n_1 <- length(Group_1)
Y_bar2 <- mean(Group_2); s2_2 <- var(Group_2); n_2 <- length(Group_2)
Y_bar3 <- mean(Group_3); s2_3 <- var(Group_3); n_3 <- length(Group_3)
Y_bar4 <- mean(Group_4); s2_4 <- var(Group_4); n_4 <- length(Group_4)
# Under the restricted model groups 1 and 2 share one mean, Y-bar-star.
Y_bar_Star <- mean(c(Group_1, Group_2))
Y_bar_StarHideShow
[1] 92.2HideShow
[1] 17 16HideShow
[1] 1078HideShow
[1] 1099.6HideShow
[1] 214.96 668.64 110.00 106.00HideShow
[1] 0.3205937HideShow
HideShow
[1] 0.579107HideShow
[1] 4.493998Approach 2: Equation 4.18 (p. 163), the computationally simpler form available whenever the comparison is pairwise.
HideShow
[1] 0.3205937HideShow
[1] 0.579107Approach 3: the restricted model read off the
dplyr summary table. Some of the values from above
are repeated here for completeness. Note that the way objects are
extracted from the summary table Summary_4_1 requires the
conversion of the dplyr tibble to a data frame (see the
descriptive-statistics chunk above).
HideShow
Y_bar_star <- mean(chapter_4_table_1[chapter_4_table_1$group %in%
c("Drug Therapy", "Biofeedback"),
"bloodpr"])
E_R <- sum((chapter_4_table_1[chapter_4_table_1$group %in%
c("Drug Therapy", "Biofeedback"),
"bloodpr"] - Y_bar_star)^2) +
sum((chapter_4_table_1[chapter_4_table_1$group == "Diet", "bloodpr"] -
Summary_4_1[Summary_4_1$group == "Diet", "mean"])^2) +
sum((chapter_4_table_1[chapter_4_table_1$group == "Combination", "bloodpr"] -
Summary_4_1[Summary_4_1$group == "Combination", "mean"])^2)
# From the previously performed ANOVA.
E_F <- SS_w
F_obs <- ((E_R - E_F) / (df_R - df_F)) / (E_F / df_F)
c(E_R, E_F, F_obs)HideShow
[1] 1099.6000000 1078.0000000 0.3205937HideShow
[1] 0.579107Approach 4: c-weights, Equation 4.32 (p. 170), with the mean square within obtained earlier from the ANOVA. Equation 4.32 is developed in §4.5 for contrasts in general; applied to a pairwise contrast it returns the Table 4.2 result.
HideShow
[1] 3HideShow
[1] 0.3205937HideShow
[1] 0.579107The same comparison as an explicit model comparison
The book’s point is that a contrast is a comparison of two
models, so it is worth fitting both models and handing them to
anova(). The restricted model that forces 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.
HideShow
chapter_4_table_1 <- chapter_4_table_1 |>
mutate(group_R = case_when(
cond %in% c(1, 2) ~ "Drug Therapy or Biofeedback",
cond == 3 ~ "Diet",
cond == 4 ~ "Combination"
))
fit_full_cells <- lm(bloodpr ~ group - 1, data = chapter_4_table_1)
fit_restricted <- lm(bloodpr ~ group_R - 1, data = chapter_4_table_1)
anova(fit_restricted, fit_full_cells)HideShow
Analysis of Variance Table
Model 1: bloodpr ~ group_R - 1
Model 2: bloodpr ~ group - 1
Res.Df RSS Df Sum of Sq F Pr(>F)
1 17 1099.6
2 16 1078.0 1 21.6 0.3206 0.5791The same comparison with emmeans
emmeans is the mainstream route to contrasts of fitted means, and it reproduces the “assumes equal variances” half of the book’s Table 4.4 (p. 177) directly: the value of the contrast, its standard error, , its degrees of freedom, and the two-tailed value. Squaring returns the of Table 4.2, exactly as the book notes on p. 177.
HideShow
group emmean SE df lower.CL upper.CL
Drug Therapy 94 4.10 16 85.3 102.7
Biofeedback 91 3.35 16 83.9 98.1
Diet 92 3.67 16 84.2 99.8
Combination 83 3.67 16 75.2 90.8
Confidence level used: 0.95 HideShow
contrast estimate SE df t.ratio p.value
Drug Therapy vs. Biofeedback 3 5.3 16 0.566 0.5791HideShow
contrast estimate SE df t.ratio p.value
Drug Therapy vs. Biofeedback 3 5.298388 16 0.566 0.5791HideShow
[1] 0.3205937A standardized contrast and its interval in DMAR
The tests above answer only whether the contrast differs from zero.
DMAR’s ci_sc() adds what none of them gives: a confidence
interval on the standardized contrast, built by inverting the
noncentral 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.
| term | value |
|---|---|
| ci_lower | -0.911 |
| std_contrast | 0.365 |
| ci_upper | 1.631 |
Confidence level: 95%
4.5 — Complex Comparisons
4.5.2 — Numerical Example
The complex comparison of Table 4.3
The contrast of interest is now the combined treatment against the average of the other three. Other than the c-weights, the code is the same as for the pairwise contrast.
HideShow
[1] 9.333333HideShow
[1] 0.2685185HideShow
[1] 4.815047HideShow
#> 4.82 — matches book p. 171 (Table 4.3)
# Like every single contrast, this one is tested against F(1, N - a) = F(1, 16).
# The book (p. 171) notes F = 4.82 exceeds the critical value of 4.49 for 1 and
# 16 df, so the complex comparison is significant; testing against F(a - 1, N - 1)
# would use the wrong reference distribution.
1 - pf(F_obs, 1, N - a)HideShow
[1] 0.04332063The complex comparison as an explicit model comparison
The lower half of Table 4.3 works the same contrast through Equation
4.12, and the book remarks that the least squares estimates under the
restricted model are tedious to find by hand. They are not tedious for
lm(). The restriction 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.
HideShow
X_cells <- model.matrix(~ group - 1, data = chapter_4_table_1)
chapter_4_table_1$x1 <- X_cells[, 1] + X_cells[, 4] / 3
chapter_4_table_1$x2 <- X_cells[, 2] + X_cells[, 4] / 3
chapter_4_table_1$x3 <- X_cells[, 3] + X_cells[, 4] / 3
fit_restricted_complex <- lm(bloodpr ~ x1 + x2 + x3 - 1, data = chapter_4_table_1)
# The three coefficients are mu-hat 1 to 3 under the restriction, and the fourth
# mean is their average.
mu_restricted <- unname(c(coef(fit_restricted_complex),
mean(coef(fit_restricted_complex))))
round(mu_restricted, 3)HideShow
[1] 91.103 89.069 89.683 89.952HideShow
[1] 0HideShow
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 ' ' 1The same complex comparison with emmeans
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.
HideShow
contrast estimate SE df t.ratio p.value
Combination vs. others (1, 1, 1, -3) 28.00 12.80 16 2.194 0.0433
Combination vs. others (1/3, 1/3, 1/3, -1) 9.33 4.25 16 2.194 0.0433HideShow
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.0433Confidence intervals for the complex contrast in DMAR
DMAR’s ci_c() and ci_sc() add intervals on
the raw and the standardized contrast. Both exclude zero, consistent
with the significant .
| term | value |
|---|---|
| ci_lower | 0.317 |
| contrast | 9.333 |
| ci_upper | 18.350 |
Confidence level: 95%
| term | value |
|---|---|
| ci_lower | 0.033 |
| std_contrast | 1.137 |
| ci_upper | 2.210 |
Confidence level: 95%
4.7 — Unequal Population Variances
4.7.1 — Numerical Example
Separate-variance tests of both contrasts
Here we do not assume homogeneity of variance for a contrast. We repeat some of the code from above for completeness. Note that the way we write the code, which matches how it is displayed in the book, is due to R’s “vectorized arithmetic” (and thus making the equations in the R code mimic those in the book). Equation 4.33 (p. 174) supplies the denominator and Equation 4.34 (p. 174) the Satterthwaite degrees of freedom. The two contrasts are the ones in the lower half of the book’s Table 4.4.
HideShow
Ybar <- c(Y_bar1, Y_bar2, Y_bar3, Y_bar4)
s2 <- c(s2_1, s2_2, s2_3, s2_4)
n <- c(n_1, n_2, n_3, n_4)
# Contrast 1: the pairwise comparison.
c1 <- c(1, -1, 0, 0)
Psi1 <- sum(Ybar * c1)
var_Psi1 <- sum((c1^2 / n) * s2)
F1 <- Psi1^2 / var_Psi1
df1 <- sum(c1^2 * s2 / n)^2 / sum((c1^2 * s2 / n)^2 / (n - 1))
c(Psi1, sqrt(var_Psi1), sqrt(F1), df1)HideShow
[1] 3.0000000 6.2316397 0.4814142 7.8849599HideShow
[1] 0.6432981HideShow
#> .643 — matches Table 4.4, book p. 177
# Contrast 2: the complex comparison.
# Notice we use fractional c-weights, whereas the book uses whole numbers; the
# scale of the weights cancels out of F and out of the degrees of freedom.
c2 <- c(1/3, 1/3, 1/3, -1)
Psi2 <- sum(Ybar * c2)
var_Psi2 <- sum((c2^2 / n) * s2)
F2 <- Psi2^2 / var_Psi2
df2 <- sum(c2^2 * s2 / n)^2 / sum((c2^2 * s2 / n)^2 / (n - 1))
c(Psi2 * 3, sqrt(var_Psi2) * 3, sqrt(F2), df2)HideShow
[1] 28.000000 9.593401 2.918673 11.034012HideShow
[1] 0.01392933The 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.
The pairwise case in base R: Welch’s test
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.
HideShow
Welch Two Sample t-test
data: drug and bio
t = 0.48141, df = 7.885, p-value = 0.6433
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-11.40676 17.40676
sample estimates:
mean of x mean of y
94 91 The same Welch test in DMAR
DMAR’s welch_t() returns the identical test as a tidy
data.frame rather than as a printed htest
object, which is what it adds: the result composes with
dplyr when many such tests are collected into one table,
and it reports the two group standard deviations and sample sizes
alongside the test.
| 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%
4.8 — Measures of Effect
4.8.1 — Measures of Effect Size
4.8.1.1 — Confidence Intervals
The intervals by hand from Equations 4.40 and 4.41
Equation 4.40 (p. 179) builds the interval from the contrast, the critical , and the standard error of the contrast under homogeneity of variance. The book works both intervals this way on p. 180 from the Table 4.4 output.
HideShow
[1] 5.298388 12.760208HideShow
[1] 3.00000 11.23208HideShow
[1] -8.232081 14.232081HideShow
[1] 9.333333 9.016811HideShow
[1] 0.3165222 18.3501444Equation 4.41 (p. 179) relaxes homogeneity of variance by replacing the error term with the separate-variance denominator and the degrees of freedom with the Satterthwaite value. The book is deliberately slightly conservative on p. 180, using 7 denominator degrees of freedom for the pairwise contrast instead of 7.885.
HideShow
[1] 14.73549HideShow
[1] 7.035665Confidence intervals for contrasts in DMAR
DMAR’s ci_c() computes the two equal-variance intervals
directly from the group summaries.
| term | value |
|---|---|
| ci_lower | -8.232 |
| contrast | 3.000 |
| ci_upper | 14.232 |
Confidence level: 95%
| term | value |
|---|---|
| ci_lower | 0.317 |
| contrast | 9.333 |
| ci_upper | 18.350 |
Confidence level: 95%
4.8.1.2 — Standardized Difference
Equation 4.44 by hand
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.
HideShow
[1] 0.3654869HideShow
[1] 1.13707Confidence intervals for standardized contrasts
DMAR’s ci_sc() inverts the noncentral distribution to give a confidence
interval on the standardized scale.
| term | value |
|---|---|
| ci_lower | -0.911 |
| std_contrast | 0.365 |
| ci_upper | 1.631 |
Confidence level: 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.
Companion scales for the standardized difference in DMAR
For the pairwise comparison, DMAR translates the same standardized difference into scales an applied audience reads more easily: the proportion of superiority (U3), the common-language effect size (CLES), and the number needed to treat (NNT). Each is a function of , 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)
4.8.2 — Measures of Association Strength
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.
HideShow
[1] 21.6HideShow
[1] 324.4138Equation 4.46 (p. 182) divides the contrast’s sum of squares by the between-group sum of squares, which says how much of the difference among the groups that one contrast has captured.
HideShow
[1] 334.55HideShow
[1] 0.06456434 0.96970197Almost 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.
HideShow
[1] 1412.55HideShow
[1] 0.01529149 0.22966535Equation 4.48 (p. 184) divides by the contrast’s own sum of squares plus the within-group sum of squares, which removes the influence of groups that the contrast does not involve.
HideShow
[1] 0.01964351 0.23132530The 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).
HideShow
[1] 0.024445454.9 — Statistical Power
Power for a specific contrast
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.
HideShow
# Population parameters.
mu_Drug <- 90
mu_Bio <- 92
mu_Diet <- 88
mu_Combo <- 81
sigma <- 12
n <- 20
# Define the contrast weights.
c_weights <- c(1/3, 1/3, 1/3, -1)
mu_vector <- c(mu_Drug, mu_Bio, mu_Diet, mu_Combo)
# The value of the contrast in the population.
psi <- sum(c_weights * mu_vector)
psiHideShow
[1] 9HideShow
[1] 8.4375HideShow
[1] 3.96676HideShow
[1] 0.8180309The book contrasts this with the power of the omnibus test under the same population parameters, which is lower.
HideShow
[1] 0.7149725Equation 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.
HideShow
[1] 0.3247595The same power computation in DMAR
DMAR’s ss_power_contrast() takes the expected means, the
within-group variance, and the contrast weights, and returns the power
at a stated per-group sample size together with the noncentral 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.
| term | value |
|---|---|
| specified_n_per_group | 20 |
| total_N | 80 |
| actual_power | 0.818 |
| noncentral_t_parm | 2.905 |
| true_f | 0.325 |
| term | value |
|---|---|
| necessary_n_per_group | 20 |
| total_N | 80 |
| actual_power | 0.818 |
| noncentral_t_parm | 2.905 |
| true_f | 0.325 |
Sample size for a sufficiently narrow interval
For accuracy in parameter estimation, the book asks for 90% assurance
that the full width of the 95% confidence interval is at most 5 points
(half-width 2.5). DMAR’s ss_aipe_c() computes the group
size for each contrast.
| term | value |
|---|---|
| necessary_n_per_group | 190 |
Confidence level: 95%
| term | value |
|---|---|
| necessary_n_per_group | 129 |
Confidence level: 95%
4.10 — Testing More Than One Contrast
4.10.3 — Orthogonality of Contrasts
Checking orthogonality in base R
Equation 4.61 (p. 191) defines two contrasts as orthogonal, with equal sample sizes, when the sum of the products of their coefficients is zero. Here we define a matrix in which the rows represent contrasts of interest, for and two contrasts. These are the and of the book’s Equation 4.60.
HideShow
Psi1 Psi2
0 0 HideShow
[1] 1Replacing with the book’s gives an orthogonal pair instead.
HideShow
Psi1 Psi3
0 0 HideShow
[1] 0Checking a whole set in DMAR
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.
| term | value |
|---|---|
| all_orthogonal | 0 |
| all_contrasts_sum_to_zero | 1 |
| n_contrasts | 2 |
| dot[Psi1 . Psi2] | 1 |
| term | value |
|---|---|
| all_orthogonal | 1 |
| all_contrasts_sum_to_zero | 1 |
| n_contrasts | 2 |
| dot[Psi1 . Psi3] | 0 |
| 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.
| term | value |
|---|---|
| all_orthogonal | 1 |
| all_contrasts_sum_to_zero | 1 |
| n_contrasts | 2 |
| dot[Psi1 . Psi2] | 0 |
| 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.
How to Cite This Page
The book. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.
This page. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Chapter 4: Individual Comparisons of Means (R code and instructions). Companion materials for Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). https://DesigningExperiments.com
These examples use DMAR 1.2.0. The printed book predates DMAR.
References
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.