Chapter 4: Individual Comparisons of Means

R Code and Instructions

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

Code
Results
On this page

Examples follow the book’s section numbers.

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

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

4.4 — A Model Comparison Approach for Testing Individual Comparisons

4.4.4 — Numerical Example

The data of Table 4.1

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

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

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

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

The error term, MSWMS_W

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

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

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

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

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

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

anova(fit_grand, fit_full)
HideShow
Analysis of Variance Table

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

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

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

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


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

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

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

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





    Drug Therapy


— —
    Biofeedback


-3.0 -14, 8.2 0.6
    Diet


-2.0 -14, 9.7 0.7
    Combination


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# From the previously performed ANOVA.
E_F <- SS_w

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

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

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

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

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

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

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

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

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

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

anova(fit_restricted, fit_full_cells)
HideShow
Analysis of Variance Table

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

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

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

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

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

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

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

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

Confidence level: 95%

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

4.5 — Complex Comparisons

4.5.2 — Numerical Example

The complex comparison of Table 4.3

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

HideShow
# Corresponds to the upper half of Table 4.3.

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

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

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

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

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

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

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

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

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

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

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

anova(fit_restricted_complex, fit_full_cells)
HideShow
Analysis of Variance Table

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

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

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

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

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

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

Confidence level: 95%

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

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

Confidence level: 95%

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

4.7 — Unequal Population Variances

4.7.1 — Numerical Example

Separate-variance tests of both contrasts

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

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

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

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

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

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

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

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

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

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

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

    Welch Two Sample t-test

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

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

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

Confidence level: 95%

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

4.8 — Measures of Effect

4.8.1 — Measures of Effect Size

4.8.1.1 — Confidence Intervals

The intervals by hand from Equations 4.40 and 4.41

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

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

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

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

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

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

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

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

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

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

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

Confidence level: 95%

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

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

Confidence level: 95%

HideShow
#> 0.317 to 18.350 — book p. 180 reports 0.32 and 18.34 using rounded components

4.8.1.2 — Standardized Difference

Equation 4.44 by hand

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

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

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

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

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

Confidence level: 95%

HideShow
#> 0.365, limits -0.911 to 1.631

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

Confidence level: 95%

HideShow
#> 1.137, limits 0.033 to 2.210

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

Companion scales for the standardized difference in DMAR

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

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

Confidence level: 95%

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

Confidence level: 95%

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

Confidence level: 95%

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

4.8.2 — Measures of Association Strength

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4.9 — Statistical Power

Power for a specific contrast

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Sample size for a sufficiently narrow interval

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

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

Confidence level: 95%

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

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

Confidence level: 95%

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

4.10 — Testing More Than One Contrast

4.10.3 — Orthogonality of Contrasts

Checking orthogonality in base R

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

How to Cite This Page

The book. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.

This page. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Chapter 4: Individual Comparisons of Means (R code and instructions). Companion materials for Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). https://DesigningExperiments.com

These examples use DMAR 1.2.0. The printed book predates DMAR.

References

Scroll to Top