library(tidyr) # Data reshaping
library(dplyr) # Data wrangling
library(ggplot2) # Visualization
theme_set(theme_light())5. Hypothesis testing and ANOVA
Packages
Data
We will use the soil data set from Crawley (2012). The data come from an experiment in which crop yields per unit area were measured from 10 randomly selected fields on each of three soil types. All fields were sown with the same variety of seed and provided with the same fertilizer and pest control inputs. The research question is whether mean crop yield differs among soil types.
yields <- read.table("data/yields.txt", sep = ";", header = TRUE)
head(yields) plotid sand clay loam
1 1 6 17 13
2 2 10 15 16
3 3 8 3 9
4 4 6 11 12
5 5 14 14 15
6 6 17 12 16
summary(yields) plotid sand clay loam
Min. : 1.00 Min. : 6.00 Min. : 3.00 Min. : 9.0
1st Qu.: 3.25 1st Qu.: 7.25 1st Qu.:10.25 1st Qu.:13.0
Median : 5.50 Median : 9.50 Median :12.00 Median :14.5
Mean : 5.50 Mean : 9.90 Mean :11.50 Mean :14.3
3rd Qu.: 7.75 3rd Qu.:11.00 3rd Qu.:13.75 3rd Qu.:16.0
Max. :10.00 Max. :17.00 Max. :17.00 Max. :18.0
Reshape the data from wide to long format. Each row in the resulting data frame represents one field and its yield under one soil type.
yields_tidy <- yields |>
pivot_longer(cols = -plotid,
names_to = "soiltype",
values_to = "yield") |>
mutate(soiltype = factor(soiltype, levels = c("clay", "loam", "sand")))
head(yields_tidy)# A tibble: 6 × 3
plotid soiltype yield
<int> <fct> <int>
1 1 sand 6
2 1 clay 17
3 1 loam 13
4 2 sand 10
5 2 clay 15
6 2 loam 16
yields_tidy_summary <- yields_tidy |>
group_by(soiltype) |>
summarize(
n = n(),
mean_yield = mean(yield),
sd_yield = sd(yield),
.groups = "drop"
)
yields_tidy_summary# A tibble: 3 × 4
soiltype n mean_yield sd_yield
<fct> <int> <dbl> <dbl>
1 clay 10 11.5 3.92
2 loam 10 14.3 2.67
3 sand 10 9.9 3.54
Visualize the distributions and group means. The dashed line marks the overall mean; triangles mark the soil-type means.
ggplot(yields_tidy, aes(x = soiltype, y = yield)) +
geom_boxplot() +
geom_hline(yintercept = mean(yields_tidy$yield), linetype = "dashed") +
geom_point(data = yields_tidy_summary,
aes(x = soiltype, y = mean_yield),
shape = 2) +
labs(x = "Soil type", y = "Crop yield")
The plot helps us inspect the group distributions, possible outliers and differences in their centers.
Hypothesis testing
Null hypothesis
Suppose we want to compare mean yields on loam and sand. We formulate a null hypothesis, \(H_0\), and an alternative hypothesis, \(H_A\):
\[ H_0: \mu_{\mathrm{loam}} = \mu_{\mathrm{sand}} \]
\[ H_A: \mu_{\mathrm{loam}} \ne \mu_{\mathrm{sand}} \]
The alternative is two-sided: it allows the mean yield to be either higher or lower on loam than on sand.
A hypothesis test allows us to assess whether the observed data are consistent with the null hypothesis. To do this, we calculate a test statistic that measures the difference between what we observe in our sample and what we would expect if the null hypothesis were true.
We then compare the observed test statistic with the distribution of values expected under the null hypothesis. The p-value tells us how likely it would be to obtain a test statistic at least as extreme as the observed one, assuming that the null hypothesis is true and the assumptions of the test are met.
A small p-value indicates that the observed data would be unusual if the null hypothesis were true, providing evidence against it. If the p-value is smaller than our chosen significance level \(\alpha\), we reject \(H_0\) and conclude that the difference in mean yields is statistically significant.
The p-value
The p-value is often misinterpreted. In particular:
- The p-value is not the probability that the null hypothesis is true, given the observed data.
- It is not the probability that the alternative hypothesis is true.
- A threshold such as \(p < 0.05\) is a convention for making a decision, not a boundary separating true from false hypotheses. Choose \(\alpha\) in advance.
- It is not a measure of effect size or practical importance. A small p-value does not necessarily imply a large or consequential difference, because the p-value also depends on sample size and variability.
A p-value should therefore be interpreted alongside an estimate of the effect and its confidence interval. A confidence interval communicates the range of effect sizes compatible with the data and model assumptions. For a discussion of the misuse of p-values, see Amrhein et al. (2019).
Two-sample t-test
A two-sample t-test assesses whether the population means of two independent groups differ. Under the null hypothesis,
\[ H_0: \mu_1 - \mu_2 = 0, \]
the observed difference between sample means \(\bar{x}_1\) and \(\bar{x}_2\) is evaluated relative to its standard error.
\[ t = \frac{\bar{x}_1 - \bar{x}_2}{SE(\bar{x}_1 - \bar{x}_2)} \]
The test statistic \(t\) expresses the observed difference in means in units of its standard error. Values close to zero are consistent with \(H_0\), whereas large positive or negative values indicate a difference that would be unlikely if the population means were equal. If \(H_0\) is true and the assumptions hold, \(t\) follows a t-distribution. The p-value is the probability, under this distribution, of obtaining a value of \(t\) at least as extreme as the one observed.
The two-sample t-test requires independent observations within and between groups. The classical Student t-test additionally assumes equal population variances. Both Student’s and Welch’s tests rely on the sampling distribution of the means being adequately approximated by the t-distribution. Within-group normality matters most when sample sizes are small or the data are strongly skewed or contain influential outliers.
Welch’s t-test
Welch’s t-test does not assume equal population variances. It is generally a good default for comparing two independent means because it performs well when variances happen to be equal and remains valid when they differ, subject to the other assumptions.
welch_test <- t.test(
x = yields$loam,
y = yields$sand,
alternative = "two.sided"
)
welch_test
Welch Two Sample t-test
data: yields$loam and yields$sand
t = 3.1375, df = 16.728, p-value = 0.006094
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
1.437576 7.362424
sample estimates:
mean of x mean of y
14.3 9.9
The output includes the two sample means, a confidence interval for the difference in means, the test statistic, degrees of freedom and p-value. R defines the difference as the mean of x minus the mean of y. Here this is mean loam yield minus mean sand yield. The sign therefore indicates the direction of the estimated difference. The estimated difference itself is not printed, but it can be computed from the stored sample means:
welch_test$estimate[1] - welch_test$estimate[2]mean of x
4.4
Report the estimated difference and its confidence interval, not only whether the p-value crosses a threshold. A confidence interval that includes zero is consistent with no difference at the corresponding two-sided confidence level. It does not establish that the population means are identical. For the example above, the results could be reported as follows:
Mean yield was higher on loam (14.3) than on sand (9.9). The estimated difference (loam − sand) was 4.4 yield units per area (95% CI: 1.4 to 7.4; Welch’s t-test, t = 3.14, df = 16.7, p = 0.0061).
If a significance level was set in advance, the decision may be stated explicitly, but still alongside the estimate:
Using a significance level of \(\alpha = 0.05\), mean yield differed significantly between loam and sand (Welch’s t-test, t = 3.14, df = 16.7, p = 0.0061). Yield on loam was estimated to be 4.4 yield units per area higher than on sand (95% CI: 1.4 to 7.4).
A good report states the direction and size of the difference, its uncertainty, and which test was used. The test statistic, degrees of freedom and p-value support that statement. Writing only “the difference was significant (p < 0.05)” leaves out what matters most: how large the difference is and how precisely it has been estimated.
Student’s two-sample t-test
For comparison, Student’s pooled-variance t-test assumes equal population variances:
student_test <- t.test(
x = yields$loam,
y = yields$sand,
alternative = "two.sided",
var.equal = TRUE
)
student_test
Two Sample t-test
data: yields$loam and yields$sand
t = 3.1375, df = 18, p-value = 0.005692
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
1.453711 7.346289
sample estimates:
mean of x mean of y
14.3 9.9
A common approach is to first perform a variance test and then choose between Student’s and Welch’s t-test depending on whether the variance test is significant. However, this two-stage procedure is generally not recommended, as it can distort the overall Type I error rate.
Welch’s t-test is generally a sensible default because it does not require the assumption of equal variances. Student’s t-test is appropriate when equal variances can be justified based on the study design and substantive knowledge, rather than solely on the outcome of a preliminary variance test.
Tests for equality of variances
The two-sample F-test
The classical F-test compares the variances of two normally distributed populations. Its null and alternative hypotheses are:
\[ H_0: \sigma^2_{\mathrm{loam}} = \sigma^2_{\mathrm{sand}} \]
\[ H_A: \sigma^2_{\mathrm{loam}} \ne \sigma^2_{\mathrm{sand}} \]
The F-statistic is the ratio of the two sample variances. The function var.test() takes the raw observations of both groups and computes the sample variances internally. With var.test(x = yields$loam, y = yields$sand), the loam variance forms the numerator and the sand variance the denominator:
\[ F_s = \frac{s_{\mathrm{loam}}^{2}}{s_{\mathrm{sand}}^{2}} \]
Under \(H_0\), and assuming independent normally distributed observations, the statistic follows an F-distribution with numerator and denominator degrees of freedom
\[ v_1 = n_{\mathrm{loam}} - 1, \qquad v_2 = n_{\mathrm{sand}} - 1. \]
f_test <- var.test(x = yields$loam, y = yields$sand, alternative = "two.sided")
f_test
F test to compare two variances
data: yields$loam and yields$sand
F = 0.56776, num df = 9, denom df = 9, p-value = 0.4119
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
0.1410233 2.2857947
sample estimates:
ratio of variances
0.5677591
The result could be reported as follows:
The variance of yield on loam was estimated to be 0.57 times the variance on sand (95% CI: 0.14 to 2.29; F-test, F(9, 9) = 0.57, p = 0.41). The data therefore provide no clear evidence of a difference in variances.
Note that a large p-value means that the data do not provide sufficient evidence to reject equal variances. It does not demonstrate that the variances are equal.
The classical F-test is highly sensitive to departures from normality. Consequently, it should not be treated as a general-purpose diagnostic for variance equality.
Bartlett’s test for several groups
Bartlett’s test compares variances across two or more groups. Its null hypothesis is that all population variances are equal. Like the classical F-test, Bartlett’s test is sensitive to departures from normality. Its test statistic, \(K^2\), approximately follows a \(\chi^2\) distribution with \(k - 1\) degrees of freedom under \(H_0\), where \(k\) is the number of groups.
bartlett_test <- bartlett.test(
x = yields_tidy$yield,
g = yields_tidy$soiltype
)
bartlett_test
Bartlett test of homogeneity of variances
data: yields_tidy$yield and yields_tidy$soiltype
Bartlett's K-squared = 1.2764, df = 2, p-value = 0.5283
The result could be reported as follows:
Variances of yield did not differ significantly among the three soil types (Bartlett’s test, \(K^2\) = 1.28, df = 2, p = 0.53). The data therefore provide no clear evidence of a difference in variances.
The equivalent formula interface is:
bartlett.test(yield ~ soiltype, data = yields_tidy)Interpret the p-value as evidence (or lack of evidence) against equal variances, not as proof of homogeneity. Inspect the group distributions and residual plots as well.
Analysis of variance (ANOVA)
A one-way analysis of variance (ANOVA) tests the null hypothesis that all group means are equal:
\[ H_0: \mu_{\mathrm{clay}} = \mu_{\mathrm{loam}} = \mu_{\mathrm{sand}}. \]
The alternative is that at least one population mean differs. A significant ANOVA result therefore does not tell us which pairs of means differ, for example whether clay and sand differ. This is examined with post-hoc tests (see multiple comparisons).
Fit the one-way ANOVA model with aov():
soil.aov <- aov(yield ~ soiltype, data = yields_tidy)
summary(soil.aov) Df Sum Sq Mean Sq F value Pr(>F)
soiltype 2 99.2 49.60 4.245 0.025 *
Residuals 27 315.5 11.69
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
The name analysis of variance describes how the test works. ANOVA splits the total variation in yield into two parts. The soiltype row measures how much the group means vary around the overall mean (between-group variation). The Residuals row measures how much the observations vary around their own group mean (within-group variation). Sum Sq gives each part as a sum of squared deviations, and Mean Sq divides it by its degrees of freedom: \(k - 1 = 2\) for three soil types and \(N - k = 27\) for 30 fields. As in the F-test for variances, the F-statistic is a ratio of two variance estimates, here the two mean squares:
\[ F = \frac{MS_{\mathrm{between}}}{MS_{\mathrm{within}}} = \frac{49.6}{11.7} \approx 4.2 \]
If \(H_0\) is true, the group means differ only by chance and both mean squares estimate the same error variance, so F is close to 1. The more the group means differ relative to the variation within groups, the larger F becomes. Under \(H_0\) and the model assumptions, F follows an F-distribution with 2 and 27 degrees of freedom, which gives the p-value of 0.025.
The result could be reported as shown below. The ANOVA summary does not include the mean yields of the soil types. They were added from the descriptive summary to show the direction of the differences.
Mean yield differed significantly among soil types (one-way ANOVA, F(2, 27) = 4.24, p = 0.025). Mean yield was highest on loam (14.3), intermediate on clay (11.5) and lowest on sand (9.9).
Understanding the linear-model coefficients
ANOVA is a special case of the linear model in which the response variable is continuous and the explanatory variables are categorical (factors). Because aov() fits a linear model, we can inspect its estimated coefficients, standard errors and test statistics with summary.lm():
summary.lm(soil.aov)
Call:
aov(formula = yield ~ soiltype, data = yields_tidy)
Residuals:
Min 1Q Median 3Q Max
-8.5 -1.8 0.3 1.7 7.1
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 11.500 1.081 10.638 3.7e-11 ***
soiltypeloam 2.800 1.529 1.832 0.0781 .
soiltypesand -1.600 1.529 -1.047 0.3046
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 3.418 on 27 degrees of freedom
Multiple R-squared: 0.2392, Adjusted R-squared: 0.1829
F-statistic: 4.245 on 2 and 27 DF, p-value: 0.02495
A linear model needs numbers, not category labels. R therefore converts a factor into numeric indicator (dummy) variables. The rule that defines these variables is called a contrast. It determines what each coefficient compares. R’s default is the treatment contrast. One level serves as the reference category, and each other level receives an indicator variable that is 1 for that level and 0 otherwise. Each coefficient then compares one level with the reference level, as in an experiment in which each treatment is compared with a control.
With clay as the reference category, the model can be written as:
\[ y_i = \beta_0 + \beta_1 I(\mathrm{soiltype}_i = \mathrm{loam}) + \beta_2 I(\mathrm{soiltype}_i = \mathrm{sand}) + \epsilon_i. \]
Here, \(I(\cdot)\) is an indicator variable that equals 1 when the condition is true and 0 otherwise. For clay, both indicators are zero, so the estimated mean is the intercept, \(\beta_0=11.5\). For loam, the estimated mean is \(\beta_0 + \beta_1=14.3\); for sand, it is \(\beta_0 + \beta_2=9.9\). Thus, the coefficients \(\beta_1\) and \(\beta_2\) are differences from the clay mean, not the group means themselves. Their t-tests compare loam and sand with clay only and are not adjusted for multiple testing.
In a one-way ANOVA, the fitted group means equal the sample means of the groups, which we computed earlier:
yields_tidy_summary# A tibble: 3 × 4
soiltype n mean_yield sd_yield
<fct> <int> <dbl> <dbl>
1 clay 10 11.5 3.92
2 loam 10 14.3 2.67
3 sand 10 9.9 3.54
The model-based means can also be extracted with:
model.tables(soil.aov, type = "means")Tables of means
Grand mean
11.9
soiltype
soiltype
clay loam sand
11.5 14.3 9.9
The estimated effects, i.e. the differences between each group mean and the grand mean, can be extracted with the code below. These are descriptive estimates only. The function model.tables() does not test whether individual effects differ from zero. The ANOVA F-test is the joint test that all effects are zero.
model.tables(soil.aov, type = "effects")Tables of effects
soiltype
soiltype
clay loam sand
-0.4 2.4 -2.0
Model diagnostics
The classical one-way ANOVA assumes independent observations, normally distributed model errors within groups, and equal population variances across groups. Independence follows from the study design, while the other two assumptions can be checked with the residuals. In a one-way ANOVA, the fitted values are the group means, so a plot of residuals against fitted values shows one vertical strip per soil type. It reveals whether the spread differs among groups and whether some observations are unusual.
yields_residuals_fitted <- data.frame(res_std = rstandard(soil.aov),
fitted = fitted(soil.aov))
ggplot(data = yields_residuals_fitted,
aes(x = fitted, y = res_std)) +
geom_point() +
geom_hline(yintercept = 0, linetype = "dashed") +
labs(x = "Fitted values", y = "Standardized residuals")
A funnel shape may indicate non-constant variance. Other systematic patterns may indicate model misspecification or dependence. Interpret the plot in the context of the experimental design and the group-wise data.
Normal Q-Q plot
A normal Q-Q plot helps assess whether the residual distribution is approximately normal:
ggplot(yields_residuals_fitted, aes(sample = res_std)) +
stat_qq() +
stat_qq_line() +
labs(x = "Theoretical quantiles", y = "Standardized residuals")
Small departures from the line are not necessarily consequential, especially with modest sample sizes. These plots are diagnostic aids, not automatic pass/fail tests.
Shapiro-Wilk test
The Shapiro-Wilk test provides a formal test of the normality assumption. Its null hypothesis is that the residuals are normally distributed. A small p-value provides evidence against normality. Since the test is sensitive to sample size, interpret its result alongside the Q-Q plot rather than in isolation.
shapiro_test <- shapiro.test(yields_residuals_fitted$res_std)
shapiro_test
Shapiro-Wilk normality test
data: yields_residuals_fitted$res_std
W = 0.99131, p-value = 0.9961
The Shapiro–Wilk test yields a p-value of 0.9961. Since this is above the significance level of 0.05, we do not reject the null hypothesis of normally distributed residuals. Thus, the test provides no evidence of a departure from normality, which is consistent with the Q-Q plot.
The result could be reported as follows:
The standardized residuals of the ANOVA model showed no evidence of a departure from normality (Shapiro–Wilk test, W = 0.99, p = 0.996), consistent with the normal Q-Q plot.
Multiple comparisons
The ANOVA tells us whether the data provide evidence that not all group means are equal. It does not identify the pairs that differ. We could run a t-test for each pair of soil types, but each test carries a 5% chance of a false positive when its null hypothesis is true, and these chances accumulate (XKCD). With three groups and three pairwise tests, the probability of at least one false positive is roughly 14% (\(1-(1-0.05)^{3}\)). With seven groups and 21 pairs, it rises to about 66%. This probability is called the family-wise error rate. Multiple comparison procedures address this problem by adjusting the p-values or confidence intervals for the number of tests, so that the family-wise error rate stays at the chosen significance level.
A common procedure after a one-way ANOVA is Tukey’s Honestly Significant Difference (HSD). It compares all pairs of group means and relies on the same assumptions as the ANOVA. TukeyHSD() takes the fitted ANOVA model as input:
tukey_result <- TukeyHSD(soil.aov)
tukey_result Tukey multiple comparisons of means
95% family-wise confidence level
Fit: aov(formula = yield ~ soiltype, data = yields_tidy)
$soiltype
diff lwr upr p adj
loam-clay 2.8 -0.9903777 6.5903777 0.1785489
sand-clay -1.6 -5.3903777 2.1903777 0.5546301
sand-loam -4.4 -8.1903777 -0.6096223 0.0204414
Each row gives a pairwise difference in means, a simultaneous confidence interval (lwr, upr) and an adjusted p-value (p adj). The sign of the difference depends on the order of the groups in the comparison. A confidence interval that excludes zero corresponds to a statistically significant pairwise difference at the family-wise level used by the procedure.
Only the comparison between sand and loam is statistically significant: its confidence interval excludes zero and its adjusted p-value is below 0.05. The intervals for loam–clay and sand–clay include zero, so the data provide no clear evidence that clay differs from either of the other soil types. Note that the adjusted p-value for sand–loam (0.020) is larger than the p-value of the Welch t-test for the same pair (0.006), mainly because Tukey’s HSD accounts for all three comparisons.
The result could be reported as follows:
Pairwise comparisons (Tukey’s HSD) showed that mean yield was lower on sand than on loam (difference = -4.4; 95% simultaneous CI: -8.2 to -0.6; adjusted p = 0.02). The differences between loam and clay (2.8; adjusted p = 0.18) and between sand and clay (-1.6; adjusted p = 0.55) were not statistically significant.
In addition to Tukey’s HSD, other adjustments such as Bonferroni and Holm are available through p.adjust(). The appropriate method depends on the questions being asked and the analysis plan.
Visualizing pairwise effects
Plot the estimated pairwise differences from Tukey’s HSD with their simultaneous confidence intervals. Intervals crossing zero indicate that the corresponding difference is not statistically significant at the adjusted level.
tukey <- as.data.frame(tukey_result$soiltype)
tukey$comparison <- rownames(tukey)
ggplot(tukey, aes(x = comparison, y = diff)) +
geom_point() +
geom_errorbar(aes(ymin = lwr, ymax = upr), width = 0.25) +
geom_hline(yintercept = 0) +
labs(x = "Comparison", y = "Difference in mean yield")
The plot communicates both direction and uncertainty. Consider the estimated magnitude of each difference and its confidence interval alongside the adjusted p-value; statistical significance alone does not establish practical importance.
The number of comparisons is not the only concern. Decisions made during data collection, preprocessing, model selection and analysis can also affect the false-positive rate. This broader problem is often called the garden of forking paths (Gelman and Loken, 2013). Pre-specifying hypotheses and analytical decisions helps limit selective analysis.