grp <- bw |>
group_by(race) |>
summarise(n = n(), mean = mean(bwt), sd = sd(bwt))
grp# A tibble: 3 × 4
race n mean sd
<fct> <int> <dbl> <dbl>
1 white 96 3103. 728.
2 black 26 2720. 639.
3 other 67 2805. 722.
The t-test compares the means of two groups (Chapter 4). Many questions in medicine have three or more groups, which give a model with several coefficients. The F-test compares the means of all the groups in one test.
Fisher made it at Rothamsted, and Snedecor gave it the letter F (Chapter 1). Chapter 12 and Chapter 14 used the F statistic at the bottom of summary().
The birthwt data in the MASS package come from 189 births at Baystate Medical Center, Massachusetts, in 1986. Mother’s race is white, black or other. Birthweight bwt is in grams.
grp <- bw |>
group_by(race) |>
summarise(n = n(), mean = mean(bwt), sd = sd(bwt))
grp# A tibble: 3 × 4
race n mean sd
<fct> <int> <dbl> <dbl>
1 white 96 3103. 728.
2 black 26 2720. 639.
3 other 67 2805. 722.
The mean birthweight is 3103 g for white mothers, 2720 g for black mothers and 2805 g for other mothers. The overall mean is 2945 g.
Does the mean birthweight differ between the three groups?
A t-test compares only two groups. Three groups give three pairs, and three t-tests at the 5% level give more than a 5% chance of a false positive (Chapter 14). The F-test answers the question in one test.
ggplot(bw, aes(race, bwt)) +
geom_jitter(width = 0.15, colour = "steelblue", alpha = 0.5, size = 1.5) +
geom_hline(yintercept = ybar, linetype = "dashed", colour = "grey50") +
geom_errorbar(data = grp, aes(y = mean, ymin = mean, ymax = mean), width = 0.5,
colour = "firebrick", linewidth = 1.2) +
labs(x = "mother's race", y = "birthweight (g)")
Figure 15.1 shows two types of spread. The between-group spread is the distance of the group means from the overall mean. The within-group spread is the distance of each baby from the mean of its own group.
If race has no effect, the three group means differ only by chance. Then the between-group spread is small compared with the within-group spread. If race has an effect, the group means move apart, and the between-group spread increases. So the ratio of the two spreads measures the evidence.
You need three terms to change each spread into a number.
The F statistic is the ratio of the two mean squares:
\[ \text{MS}_{\text{between}} = \frac{\sum_g n_g(\bar y_g - \bar y)^2}{k - 1}, \qquad \text{MS}_{\text{within}} = \frac{\sum_g \sum_{i \in g} (y_i - \bar y_g)^2}{n - k}, \qquad F = \frac{\text{MS}_{\text{between}}}{\text{MS}_{\text{within}}} . \]
Here \(k\) = 3 is the number of groups and \(n_g\) is the size of group \(g\). We calculate F by hand, one group at a time.
by_hand <- bw |>
group_by(race) |>
summarise(n_g = n(), mean_g = mean(bwt),
between = n_g * (mean_g - mean(bw$bwt))^2, # n_g (group mean - overall mean)^2
within = sum((bwt - mean_g)^2)) # squared distances to own group mean
by_hand# A tibble: 3 × 5
race n_g mean_g between within
<fct> <int> <dbl> <dbl> <dbl>
1 white 96 3103. 2400533. 50332733.
2 black 26 2720. 1315022. 10197928.
3 other 67 2805. 1300170. 34423270.
SS_b <- sum(by_hand$between); SS_w <- sum(by_hand$within)
MS_b <- SS_b / (k - 1); MS_w <- SS_w / (n - k)
c(SS_between = SS_b, SS_within = SS_w, MS_between = MS_b, MS_within = MS_w, F = MS_b / MS_w) SS_between SS_within MS_between MS_within F
5.015725e+06 9.495393e+07 2.507863e+06 5.105050e+05 4.912513e+00
F_obs <- MS_b / MS_wThe between-group mean square is 2,507,863 g². The within-group mean square is 510,505 g². Their ratio is F = 4.91. To decide if this ratio is large, we need the values that F takes when race has no effect.
If race has no effect, the race labels give no information about birthweight. Then a random shuffle of the labels gives data that are as probable as the real data. We shuffle the labels 5,000 times and calculate F each time.
f_stat <- function(y, g) {
ng <- tapply(y, g, length); mg <- tapply(y, g, mean)
ms_b <- sum(ng * (mg - mean(y))^2) / (length(ng) - 1)
ms_w <- sum((y - mg[g])^2) / (length(y) - length(ng))
c(MS_b = ms_b, MS_w = ms_w, F = ms_b / ms_w)
}
set.seed(1925)
shuffled <- t(replicate(5000, f_stat(bw$bwt, sample(bw$race))))
p_perm <- mean(shuffled[, "F"] >= F_obs)
c(mean_F = mean(shuffled[, "F"]), p_perm = p_perm) mean_F p_perm
1.011179 0.010600
ggplot(tibble(F = shuffled[, "F"]), aes(F)) +
geom_histogram(binwidth = 0.25, boundary = 0, fill = "steelblue", colour = "white") +
geom_vline(xintercept = F_obs, colour = "firebrick", linewidth = 1) +
labs(x = "F from shuffled labels", y = "count")
The average of the shuffled F values is 1.01. Of the 5,000 shuffles, 1.1% give an F of 4.91 or more. This proportion is the p-value of a permutation test.
The null hypothesis is \(H_0: \mu_{\text{white}} = \mu_{\text{black}} = \mu_{\text{other}}\). The model assumes that the babies in each group have a normal birthweight with the same standard deviation (SD) \(\sigma\).
The within-group mean square estimates \(\sigma^2\) if \(H_0\) is true and also if \(H_0\) is false. It is the pooled variance of the two-sample t-test (Chapter 4), for \(k\) groups in place of two.
The between-group mean square also estimates \(\sigma^2\), but only if \(H_0\) is true. A group mean of \(n_g\) babies has variance \(\sigma^2/n_g\). So \(n_g(\bar y_g - \bar y)^2\) is about \(\sigma^2\) on average. If the true means differ, the between-group mean square estimates a larger value:
\[ E[\text{MS}_{\text{between}}] = \sigma^2 + \frac{\sum_g n_g(\mu_g - \bar\mu)^2}{k - 1} . \]
So F is close to 1 when \(H_0\) is true, and larger when it is false. Small values of F are no evidence against \(H_0\). The F-test uses only the upper tail.
You can see this in the shuffles. A shuffle breaks the link between race and birthweight, so \(H_0\) is true in the shuffled data. Then the two mean squares estimate the same quantity.
colMeans(shuffled[, c("MS_b", "MS_w")]) MS_b MS_w
531789.9 531753.1
The average between-group mean square is 531,790 g². The average within-group mean square is 531,753 g². They agree, so the average F is close to 1.
If \(U\) and \(V\) are independent chi-square variables with \(d_1\) and \(d_2\) degrees of freedom, then
\[ \frac{U/d_1}{V/d_2} \sim F(d_1, d_2) . \]
Under \(H_0\) and the model assumptions, \(\text{SS}_{\text{between}}/\sigma^2\) is chi-square with \(k - 1\) degrees of freedom. \(\text{SS}_{\text{within}}/\sigma^2\) is chi-square with \(n - k\) degrees of freedom, and the two are independent. In the ratio, the unknown \(\sigma^2\) cancels:
\[ F = \frac{\text{SS}_{\text{between}}/\sigma^2/(k-1)}{\text{SS}_{\text{within}}/\sigma^2/(n-k)} = \frac{\text{MS}_{\text{between}}}{\text{MS}_{\text{within}}} \sim F(k - 1,\, n - k) . \]
So the test needs no value of \(\sigma\). The t-test uses the same method (Chapter 4).
An F distribution has two degrees of freedom. The first comes from the numerator, and the second comes from the denominator. \(F(2, 186)\) and \(F(186, 2)\) are different distributions, so the order is important.
dfs <- tribble(~d1, ~d2, 1, 10, 2, 186, 5, 30, 10, 100) |>
mutate(lab = factor(sprintf("F(%d, %d)", d1, d2), levels = sprintf("F(%d, %d)", d1, d2)))
curves <- dfs |>
mutate(data = map2(d1, d2, \(a, b) tibble(x = seq(0.01, 4, length.out = 300), dens = df(x, a, b)))) |>
unnest(data)
s1 <- ggplot(curves, aes(x, dens, colour = lab)) + geom_line(linewidth = 0.9) +
scale_colour_manual(values = c("grey60", "firebrick", "steelblue", "black"), name = NULL) +
coord_cartesian(ylim = c(0, 1.2)) + labs(x = "F", y = "density")
crit <- qf(0.95, k - 1, n - k)
s2 <- ggplot(tibble(F = shuffled[, "F"]), aes(F)) +
geom_histogram(aes(y = after_stat(density)), binwidth = 0.25, boundary = 0, fill = "grey80", colour = "white") +
stat_function(fun = df, args = list(df1 = k - 1, df2 = n - k), colour = "firebrick", linewidth = 1, n = 400) +
stat_function(fun = df, args = list(df1 = k - 1, df2 = n - k), xlim = c(crit, 8), geom = "area",
fill = "firebrick", alpha = 0.3) +
geom_vline(xintercept = F_obs, colour = "steelblue", linewidth = 1) +
coord_cartesian(xlim = c(0, 8)) + labs(x = "F", y = "density")
s1 + s2
The shuffled values follow the \(F(2, 186)\) curve. The 5% critical value is 3.04. The real F of 4.91 (blue line) lies beyond it.
c(critical_5pct = qf(0.95, k - 1, n - k),
p_F_dist = pf(F_obs, k - 1, n - k, lower.tail = FALSE),
p_shuffle = p_perm)critical_5pct p_F_dist p_shuffle
3.044504073 0.008336077 0.010600000
The F distribution gives p = 0.0083. The shuffles gave 0.011. The two answers agree.
anova() on a linear model, or summary(aov()), prints the same numbers in a table.
fit_race <- lm(bwt ~ race, data = bw)
anova(fit_race)Analysis of Variance Table
Response: bwt
Df Sum Sq Mean Sq F value Pr(>F)
race 2 5015725 2507863 4.9125 0.008336 **
Residuals 186 94953931 510505
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Df: 2 for race (\(k - 1\)) and 186 for the residuals (\(n - k\)). Together they add to \(n - 1\) = 188.Sum Sq: 5,015,725 is the between-group sum of squares, and 94,953,931 is the within-group sum of squares. They match our hand values.Mean Sq: each sum of squares divided by its Df.F value: the ratio of the two mean squares, 4.913.Pr(>F): the upper tail of \(F(2, 186)\) beyond the observed F.The residual mean square is \(\hat\sigma^2\). Its square root, 714.5 g, is the residual standard error in summary(fit_race). The last line of summary(fit_race) gives the same F and p-value.
The race test is one case of a general rule. Each F-test compares two nested models. The full model has \(p\) coefficients. The reduced model sets \(q\) of them to zero. RSS is the residual sum of squares of a model:
\[ F = \frac{(\text{RSS}_{\text{reduced}} - \text{RSS}_{\text{full}})/q}{\text{RSS}_{\text{full}}/(n - p)} \sim F(q,\, n - p) . \]
The numerator is the decrease in RSS for each extra coefficient. The denominator is \(\hat\sigma^2\) from the full model. A useless coefficient decreases the RSS by about \(\hat\sigma^2\), because it fits noise. So F is close to 1 if the \(q\) extra coefficients are useless. A large F shows that they remove more variation than noise can.
For the race test, the reduced model has only an intercept, lm(bwt ~ 1). Its RSS is the total sum of squares. The full model has \(p\) = 3 coefficients, and \(q\) = 2.
rss <- function(fit) sum(residuals(fit)^2)
fit_0 <- lm(bwt ~ 1, data = bw)
F_nested <- ((rss(fit_0) - rss(fit_race)) / 2) / (rss(fit_race) / (n - 3))
c(by_hand = F_nested, anova = anova(fit_0, fit_race)$F[2]) by_hand anova
4.912513 4.912513
The same rule tests race after we allow for smoking. Smoking differs between the race groups, so it can hide or exaggerate the race difference.
fit_s <- lm(bwt ~ smoke, data = bw)
fit_sr <- lm(bwt ~ smoke + race, data = bw)
F_adj <- ((rss(fit_s) - rss(fit_sr)) / 2) / (rss(fit_sr) / (n - 4))
c(by_hand = F_adj, anova = anova(fit_s, fit_sr)$F[2]) by_hand anova
9.196397 9.196397
anova(fit_s, fit_sr)Analysis of Variance Table
Model 1: bwt ~ smoke
Model 2: bwt ~ smoke + race
Res.Df RSS Df Sum of Sq F Pr(>F)
1 187 96343710
2 185 87631356 2 8712354 9.1964 0.0001557 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
With smoking in the model, the F for race is 9.2 on 2 and 185 degrees of freedom, with p = 0.00016. Without smoking it was 4.91. Most of the change is in the numerator. The sum of squares for race grows from 5.02 million to 8.71 million g².
54% of white mothers smoke, against 38% of black mothers and 18% of other mothers. Smoking lowers birthweight, so it hides part of the advantage of the white babies. Once smoking is in the model, the race difference is larger and the evidence for it is stronger.
If \(q\) = 1, the F-test and the t-test for that one coefficient are the same test, and \(F = t^2\). For smoking alone, \(t\) = -2.653 and \(t^2\) = 7.038.
c(t_squared = t_smoke^2, F = anova(fit_0, fit_s)$F[2])t_squared F
7.037843 7.037843
For the overall test of a model with \(k\) predictors, F is a function of \(R^2\):
\[ F = \frac{R^2/k}{(1 - R^2)/(n - k - 1)} . \]
R2 <- summary(fit_race)$r.squared
c(R2 = R2, F_from_R2 = (R2 / 2) / ((1 - R2) / (n - 3))) R2 F_from_R2
0.05017248 4.91251332
Race explains 5% of the variation in birthweight, but the F-test rejects \(H_0\). With 189 births, the denominator has 186 degrees of freedom, and a small \(R^2\) is sufficient. A small p-value is evidence that the group means differ. The group means and \(R^2\) give the size of the difference.
The F-test assumes independent subjects, normal errors and equal variance in every group. It is sensitive to unequal variance, most of all when the groups have different sizes.
oneway.test(bwt ~ race, data = bw) # Welch: no equal-variance assumption
One-way analysis of means (not assuming equal variances)
data: bwt and race
F = 5.06, num df = 2.000, denom df = 72.428, p-value = 0.008771
kruskal.test(bwt ~ race, data = bw) # ranks: no normality assumption
Kruskal-Wallis rank sum test
data: bwt by race
Kruskal-Wallis chi-squared = 8.5199, df = 2, p-value = 0.01412
pairwise.t.test(bw$bwt, bw$race, p.adjust.method = "holm")
Pairwise comparisons using t tests with pooled SD
data: bw$bwt and bw$race
white black
black 0.033 -
other 0.029 0.605
P value adjustment method: holm
oneway.test(), drops the equal-variance assumption, as Welch’s t-test does for two groups. Here p = 0.0088.kruskal.test(), uses ranks. It extends the Wilcoxon rank-sum test (Chapter 6) to \(k\) groups. Here p = 0.014.A significant F shows that at least one mean differs. To find which means differ, use pairwise t-tests with a Holm correction. The Holm correction adjusts the p-values for the number of tests. In the output above, the white group differs from the black group and from the other group at the 5% level. The black and other groups do not differ at the 5% level.