18 Comparing Groups: p-values and ANOVA
By the end of this chapter you should be able to:
- Place statistical testing in the cycle of data analysis.
- Explain what a statistic, a null hypothesis, and a p-value are, and read a test result in three steps.
- Describe how p-values are misused, and what to report alongside them.
- Explain how ANOVA compares variation between groups with variation within groups, using the F statistic.
- Run and interpret an ANOVA in R with
aov(), and follow it with Tukey’s HSD. - Explain why observations of neighboring places make ANOVA’s p-values less trustworthy.
Western North Carolina’s mountain counties are known as a retirement destination. The Piedmont has the big cities, universities, and their young workers. So do men in the west really tend to be older than men in the Piedmont? Or could the difference we see in the numbers be due to chance?
That is the question behind this chapter: do groups of places really differ, or could the difference be chance? We’ll build up the tools in order. First, what data analysis is, and what a statistic and a p-value are. Then variance, the measure of spread that the method is built on. Then analysis of variance (ANOVA), applied to median male age in North Carolina’s 100 counties. We finish with what changes when the observations are places on a map.
18.1 What is data analysis?
Data analysis turns raw observations into evidence. We summarize what the data show, and we test whether the patterns are real or could be due to chance. It is a cycle, not a single test:
| Step | What you do |
|---|---|
| 1. Ask | Pose a question the data can answer. |
| 2. Collect | Gather, clean, and organize the observations. |
| 3. Describe | Summarize center, spread, and shape. |
| 4. Test | Check whether a pattern could be due to chance. |
| 5. Communicate | Report findings, maps, and their uncertainty. |
Chapter 16 covered step 3, describing data. This chapter is about step 4, testing, and about the measure of spread, variance, that connects the two.
18.2 Statistics and p-values
A statistic is a number calculated from a sample that summarizes the data. There are two broad kinds:
- Descriptive statistics summarize: the mean, the median, the standard deviation.
- Test statistics weigh evidence: t, F, chi-square.
Because a statistic comes from a sample, it estimates a value for the whole population, and it would change if you drew a different sample. A test asks whether the pattern in this sample is bigger than that sample-to-sample wobble would produce by chance.
Every test starts from a null hypothesis, written H₀: the boring claim that there is no difference, no relationship, nothing going on. The alternative hypothesis, H₁, is that there is something. The test then works out how surprising your data would be if the null hypothesis were true.
18.2.1 Reading a test result
Read the output of any statistical test in three steps:
- The test statistic. How large the pattern is compared with random variation, for example F.
- The p-value. The probability of a result at least this extreme if the null hypothesis were true, that is, if the groups truly did not differ.
- The decision. By convention, if p < 0.05, reject the null hypothesis: the result is called statistically significant. If p ≥ 0.05, you have no evidence of a difference. That is not the same as evidence of no difference.
Suppose an ANOVA gives p = 0.03. That means: if the groups truly didn’t differ, a result this extreme would happen about 3% of the time. It does not mean there is a 3% chance the null hypothesis is true, or that the difference between the groups is large.
A tiny difference can be statistically significant if you have lots of data, and a large one can miss p < 0.05 if you have little. A p-value says nothing about the size of a difference. Always report the size of the difference too.
18.2.2 p-values and the replication crisis
p-values matter because they are the shared test of “could this be chance?”, and for decades journals have used p < 0.05 as the bar for publication. That bar created bad incentives:
- p-hacking: re-running an analysis in different ways until something crosses 0.05.
- The file drawer: results that don’t reach 0.05 go unpublished, so the published record overstates how often effects are found.
- The bright line: treating 0.049 as “real” and 0.051 as “nothing”, as if they were different worlds.
| Year | Event |
|---|---|
| 1925 | R. A. Fisher suggests p < 0.05 as a convenient guide, not a fixed rule. |
| 1933 | Jerzy Neyman and Egon Pearson add fixed error rates. Textbooks later blend the two ideas. |
| 2005 | John Ioannidis argues that most published research findings are false. |
| 2015 | The Open Science Collaboration repeats 100 psychology studies: 97% of the originals had reported p < 0.05, but only 36% of the repeats did. |
| 2016 | The American Statistical Association warns that p-values are widely misread. |
| 2019 | More than 800 scientists sign a call to retire “statistical significance”. |
The failure of so many published findings to hold up when other researchers repeated them is called the replication crisis. The lesson for your own work: report the p-value with the size of the effect and a confidence interval, never on its own. And treat p = 0.051 and p = 0.049 as what they are: almost exactly the same amount of evidence.
18.3 Variance: measuring spread
ANOVA is built on variance, which you met in Chapter 16. Variance is the average squared distance of each value from the mean:
\[ s^2 = \frac{\sum (x_i - \bar{x})^2}{n - 1} \]
For a sample we divide by n − 1 rather than n. Small variance means values cluster near the mean; large variance means they spread widely. The standard deviation, s, is the square root of the variance, back in the data’s own units.
18.3.1 Two kinds of variation
Now suppose we have three groups, A, B, and C, of six values each (Figure 18.1). There are two kinds of variation:
- Within-group variation: the spread of the values around their own group’s mean.
- Between-group variation: how far the group means sit from the overall mean.
ANOVA compares the two:
\[ F = \frac{\text{between-group variance}}{\text{within-group variance}} \]
If the group means sit far apart relative to the noise inside each group, F is large, and the groups differ more than chance alone would produce. If the groups are really just random draws from one population, F hovers around 1.
18.4 ANOVA: are the group means different?
Analysis of variance, or ANOVA, tests whether the means of three or more groups differ. (With only two groups, you would use a t-test. ANOVA extends the idea to more groups without the extra false positives you’d get from running many t-tests.)
The two hypotheses are:
- H₀: μ₁ = μ₂ = μ₃. All the group means are equal.
- H₁: At least one group mean differs.
ANOVA builds F from sums of squares (SS), the summed squared distances from the means, each divided by its degrees of freedom (df) to give a mean square (MS). With k groups and N observations in all:
| Source | df | Mean square (MS) |
|---|---|---|
| Between groups | k − 1 | SS between ÷ (k − 1) |
| Within groups (residuals) | N − k | SS within ÷ (N − k) |
| F statistic | MS between ÷ MS within |
For the three groups in Figure 18.1, k = 3 and N = 18. The overall mean is 6.33. Work it through:
- SS between = 6 × (5 − 6.33)² + 6 × (8 − 6.33)² + 6 × (6 − 6.33)² = 28. With 3 − 1 = 2 df, MS between = 14.
- SS within: each group’s values are spread around its own mean with a variance of 2, so its squared distances add up to 5 × 2 = 10. Three groups give 30. With 18 − 3 = 15 df, MS within = 2.
- F = 14 ÷ 2 = 7.
aov() fits the model, and summary() prints the ANOVA table. The formula value ~ group reads “value, by group”:
F = 7, with 2 and 15 degrees of freedom, and p = 0.0071. If all three groups came from one population, an F this large would turn up less than 1% of the time, so we reject H₀: at least one group mean differs.
Where does the p-value come from? If H₀ is true, F follows a known shape, the F distribution, which depends on the two degrees of freedom. The p-value is the share of that distribution beyond your F. In R, pf() gives it directly:
18.5 Example: median male age by North Carolina region
Back to the question we started with: is the median age of males different between western, central, and eastern North Carolina?
- Data: American Community Survey 5-year estimates of median age for males (table B01002) for all 100 North Carolina counties, downloaded with tidycensus (Chapter 13).
- Groups: the west (the mountains), the center (the Piedmont), and the east (the coastal plain). Each county belongs to one region (Figure 18.2).
- Unit of analysis: the county, not the person or the census tract.
Before testing anything, look at the data. Each dot in Figure 18.3 is one county, and each box holds the middle half of the counties in its region:
nc_df <- st_drop_geometry(nc)
ggplot(nc_df, aes(region, estimate, fill = region)) +
geom_boxplot(alpha = 0.6, outlier.shape = NA) +
geom_jitter(width = 0.15, size = 1.8, alpha = 0.8) +
scale_fill_manual(values = c("#1b9e77", "#d95f02", "#7570b3")) +
labs(title = "Male Median Age by Region, North Carolina Counties",
x = NULL, y = "Median age (male, years)",
caption = "Source: ACS 5-year estimates, table B01002") +
theme_minimal() +
theme(legend.position = "none")
The table puts numbers on the picture:
nc_df |>
group_by(region) |>
summarize(n = n(),
mean = mean(estimate, na.rm = TRUE),
sd = sd(estimate, na.rm = TRUE),
median = median(estimate, na.rm = TRUE))| Region | Counties | Mean | SD | Median |
|---|---|---|---|---|
| West | 28 | 44.5 | 5.0 | 44.1 |
| Central | 31 | 39.2 | 3.9 | 39.7 |
| East | 41 | 41.8 | 5.6 | 41.2 |
The West is oldest, with a mean of 44.5 years, and the Piedmont youngest, at 39.2. The East sits between, at 41.8, with the widest spread. But the boxes overlap a lot. Is the gap between the regional means large compared with the spread inside each region? That is exactly what ANOVA tests.
18.5.1 The ANOVA
One line fits the model: estimate is the variable we compare, and region defines the groups.
fit <- aov(estimate ~ region, data = nc_df)
summary(fit) Df Sum Sq Mean Sq F value Pr(>F)
region 2 420.8 210.41 8.439 0.000418 ***
Residuals 97 2418.5 24.93
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Read it in three steps:
- Test statistic. F = 210.41 ÷ 24.93 = 8.44. The variation between regions is about eight times the variation within them. With k = 3 regions and N = 100 counties, the degrees of freedom are 2 and 97.
- p-value. 0.000418, far below 0.05. If the three regions really had the same mean, an F this large would almost never happen (Figure 18.4).
- Decision. Reject the null hypothesis. At least two of the regions differ in median male age.
Notice what the result does not say. It doesn’t say all three regions differ, only that some do. And it doesn’t say why: region doesn’t cause age. Retirement migration, college towns, and military bases are all possible explanations that the test can’t tell apart.
Before you saw the data, which region would you have guessed has the oldest men? What features of a county (a university, a military base, a retirement community) would pull its median age down or up?
18.6 After ANOVA: which groups differ?
ANOVA tells us that at least two groups differ, not which ones. To find out, run a post-hoc test. Tukey’s honestly significant difference (HSD) test compares every pair of groups and adjusts the p-values, so that making three comparisons doesn’t inflate the chance of a false positive:
For the three groups, only B and A differ significantly: B’s mean is 3 higher, with an adjusted p-value of 0.006. C and A (p = 0.46) and C and B (p = 0.066) do not. In the North Carolina example, TukeyHSD(fit) on the regional model shows which pairs of regions differ; try it in Exercise 2.
18.6.1 Check the assumptions
ANOVA’s p-value is only trustworthy if three assumptions hold:
- Independence: each observation tells you nothing about the others.
- Normality: the values in each group, or more exactly the model’s residuals, are roughly normal.
- Equal variances: the groups have similar spreads.
The Shapiro-Wilk test checks normality. Its null hypothesis is that the residuals are normal, so a large p-value is good news. For the North Carolina model, shapiro.test(residuals(fit)) gives W = 0.98 and p = 0.18: no evidence that the residuals aren’t normal.
If the assumptions fail, there are standard fallbacks:
- Welch’s ANOVA,
oneway.test(), does not assume equal variances. - The Kruskal-Wallis test,
kruskal.test(), compares the groups by rank, so it does not need normal data.
All three tests agree here: the groups differ (p < 0.05).
18.7 What makes it spatial data science?
The first assumption, independence, is where spatial data cause trouble. The observations in our example are places, and places are connected.
- Nearby places are alike. By the first law of geography, near things are more related than distant things. Neighboring counties share age profiles, so the 100 counties are not 100 independent pieces of evidence. Treating them as independent tends to make ANOVA’s p-value look smaller than it should.
- Boundaries shape the answer. Drawing the three regions differently, or analyzing census tracts instead of counties, could change the result. That is the modifiable areal unit problem.
- Spatial tools account for neighbors. Moran’s I (Chapter 22) tests whether a model’s residuals cluster on the map, and spatial regression and permutation tests build neighbors into the model to give more honest p-values.
The bottom line: before you trust a p-value from map data, map the residuals and check them for spatial autocorrelation. Our ANOVA says median male age differs across North Carolina’s regions (F = 8.44, p < 0.001), with the West oldest. Because the counties are neighbors on a map, treat that p-value with some caution.
18.8 Check your understanding
An ANOVA gives p = 0.03. This means:
The null hypothesis of an ANOVA is that:
A statistically significant result is always a large or important one.
The F statistic is between-group variance divided by:
An ANOVA compares 4 groups with 40 observations in all. How many degrees of freedom does the between-groups row have?
ANOVA gives F = 8.44 and p = 0.0004 for three regions. What can you conclude?
Which test compares every pair of groups after an ANOVA?
Neighboring counties being alike breaks ANOVA’s assumption of:
18.9 Summary
- Data analysis is a cycle: ask, collect, describe, test, and communicate.
- A statistic summarizes a sample. A test starts from a null hypothesis of no difference, and the p-value is the chance of a result at least this extreme if the null hypothesis were true. By convention, p < 0.05 is statistically significant.
- p-values are easy to misuse. Report them with the size of the effect and a confidence interval, and don’t treat 0.05 as a bright line.
- Variance is the average squared distance from the mean. ANOVA compares between-group with within-group variance: F = MS between ÷ MS within. A large F and small p mean at least one group mean differs.
- In R:
fit <- aov(value ~ group, data = d), thensummary(fit). Follow it withTukeyHSD(fit)to find which groups differ. Useoneway.test()orkruskal.test()if the assumptions fail. - In North Carolina, median male age differs by region (F = 8.44, p = 0.0004), with the West oldest. Because neighboring counties are alike, check spatial data for spatial autocorrelation before trusting a p-value.
18.10 Exercises
- By hand. Three groups have the values (2, 4, 6), (5, 7, 9), and (8, 10, 12). Calculate the group means, SS between, SS within, and F by hand, then check your answer with
aov(). - Which regions? Run
TukeyHSD()on the North Carolina regional model. Which pairs of regions differ significantly? Does that match what you see in Figure 18.3? - Female age. Download the median age for females (variable
B01002_003) for North Carolina’s counties with tidycensus, assign each county to the same regions, and run an ANOVA. Do the regions differ for women too? - Draw the lines differently. Move the boundary between the central and eastern regions one tier of counties east or west, and rerun the ANOVA. How much does F change? What does that tell you about the modifiable areal unit problem?
- Births. Using the
ncdata from the sf package (Chapter 16), make a variable for births per square kilometer, group the counties into three regions by the longitude of their centroids, and test whether births per square kilometer differ by region. Check the assumptions, and usekruskal.test()if they fail.
18.11 Further reading
- Wasserstein, R. L., and Lazar, N. A. (2016). “The ASA Statement on p-Values: Context, Process, and Purpose.” The American Statistician 70(2): 129–133. Six short principles for using p-values well.
- Amrhein, V., Greenland, S., and McShane, B. (2019). “Scientists Rise Up Against Statistical Significance.” Nature 567: 305–307.
- Open Science Collaboration (2015). “Estimating the Reproducibility of Psychological Science.” Science 349(6251): aac4716.
- OpenIntro Statistics (4th ed.), by David Diez, Mine Çetinkaya-Rundel, and Christopher Barr, free at https://www.openintro.org/book/os/. Chapter 7 covers ANOVA.
var() in R.
The middle value when values are sorted, so half are above and half
below. Unlike counts, medians can’t be added across areas.
A subset of a population that is surveyed to estimate something about
the whole population. Smaller samples give less certain estimates.
A measure of how spread out values are around their mean, in the same
units as the values. sd() in R.
A statistic that weighs evidence in a hypothesis test, such as
t or F: how large a pattern is compared with random
variation.
The claim that there is a difference or relationship, such as “at least
one group mean differs”.
By convention, a result with p < 0.05. Significant doesn’t
mean large or important.
Re-running an analysis in different ways until a p-value falls below
0.05, which produces false findings.
Doing research so others can check and reuse it: open access papers,
open data, open methods, and open-source software.
The discovery, in the 2010s, that many published findings fail to hold
up when other researchers repeat the studies.
A range that is likely to contain the true value of something estimated
from data. geom_smooth() shades a 95% confidence interval
around its trend line.
The squared distances of values from a mean, added up. ANOVA splits it
into between-group and within-group parts.
The number of values free to vary in a calculation. In ANOVA, k
− 1 between groups and N − k within them.
A sum of squares divided by its degrees of freedom: a variance.
F is the ratio of two mean squares.
An observation’s actual value minus the value a model predicts for it.
Map them to see where a model fits poorly.
The Census Bureau’s continuous survey of a sample of households every
year. It asks many more questions than the decennial census, but every
value is an estimate with a margin of error.
ACS estimates that pool 60 months of responses. They are the most
reliable ACS product and the only one for tracts and block groups. An
estimate labeled 2022 describes 2018 to 2022.
An R package that downloads US Census data through the Census API and
returns it as a tidy data frame, with boundaries attached if you ask.
A small area of about 1,200 to 8,000 people (4,000 on average), drawn to
be fairly stable over time. The workhorse unit for neighborhood
analysis.
In R, a named piece of memory that holds data, such as
months <- 12. In a dataset, a measured characteristic,
such as median income; each Census variable has a code.
The values of F you’d expect if the null hypothesis were true.
Its shape depends on two degrees of freedom. pf() in R.
A test run after an ANOVA to find which pairs of groups differ, such as
Tukey’s HSD.
The assumption, built into most standard statistics, that knowing one
observation tells you nothing about another. Data about places usually
break it, because nearby places tend to be alike.
A test of whether values, such as a model’s residuals, are normally
distributed. A large p-value means no evidence against normality.
A version of ANOVA that doesn’t assume the groups have equal variances.
oneway.test() in R.
A test of whether three or more groups differ, using ranks instead of
values, so it doesn’t need normal data. kruskal.test() in
R.
Waldo Tobler’s statement that “everything is related to everything else,
but near things are more related than distant things.” It is the idea
behind spatial autocorrelation.
The way results can change when the same individual data are grouped
into different areas, either larger or smaller ones or the same size
with different boundaries.
A global measure of spatial autocorrelation, from −1 (dispersed) through
0 (random) to +1 (clustered), with a p-value.
A statistical model of how one variable (such as home price) changes
with one or more others (such as distance to downtown).
A test that shuffles values across locations many times and asks how
often the shuffles beat the observed statistic.
The tendency for things that are close together to be more alike than
things that are far apart, such as neighboring counties having similar
incomes.
“Simple features”: the R package for spatial vector data. An sf object
is a data frame with a geometry column holding each row’s point, line,
or polygon.
A bundle of code, written by other users, that adds new functions to R.
Install it once with install.packages(), then load it in
each session with library().
The angle east or west of the Prime Meridian, from 0° to 180°. Lines of
equal longitude are meridians.
The geometric center of a polygon. st_centroid() in R.
The ability for anyone to rerun an analysis from its code and data and
get the same result.