Skip to main content

Activity 24 — One-Factor ANOVA: Start to Finish

Seven Australian possum sites, eight steps, and the one question F cannot answer

anova
emmeans
car
performance
factors
statistics

Hands-on companion to the one-factor ANOVA lecture. Students read a possum dataset from a published field study, turn site numbers into named groups with case_when() and as.factor(), order them north to south with fct_relevel(), plot before testing, fit with lm(), read car::Anova(type = 2), check assumptions with performance::check_model() and car::leveneTest(), measure the effect with eta-squared, and find which of the seven sites differ using emmeans and a compact letter display from multcomp::cld(). Homework repeats the whole recipe on ear length, where one assumption check fails because of a single animal and students test whether the conclusion depends on it.

Author

Bill Perry

Published

November 30, 2026

In-class Activity 24: One Factor, Seven Groups 🐾

Today’s Objectives

  1. See why twenty-one t-tests is the wrong answer to “do these seven groups differ?”
  2. Turn group codes into named groups with case_when(), then make them a factor
  3. Plot the data before testing it — and predict the answer
  4. Fit with lm() and read the right table: car::Anova(type = 2)
  5. Check the assumptions after the fit — check_model(), leveneTest(), shapiro.test()
  6. Say how big the effect is with eta-squared
  7. Find which groups differ — emmeans(), pairs(), and a compact letter display from multcomp::cld()
  8. Do it again on a different measurement for homework
Important⚠️ Install these BEFORE class

Seven packages, and performance drags in about a dozen dependencies. This is not a two-minute job — do it at home.

install.packages("performance")
install.packages("see")
install.packages("emmeans")
install.packages("multcomp")
install.packages("multcompView")
install.packages("Hmisc")
install.packages("effectsize")

multcomp, multcompView and Hmisc only need to be installed — we never library() them. Windows machines in particular do not always pull the last two in on their own.

Tip📂 Files for today
ImportantWhat you hand in
  • Today is a run-it-and-look-at-it day. Every line is in this activity and in the skeleton. You do not turn in scripts/24_anova_one_factor.R.
  • The Q boxes are things to think about. Not graded, not written down.
  • You turn in scripts/24_anova_one_factor_homework.R — the same recipe on ear length.

Part 1 · Where the data came from

Your final projects need data, so here is how today’s data was actually found.

The measurements were made by four field biologists, who live-trapped every animal and published the work in the Australian Journal of Zoology: Lindenmayer, Viggers, Cunningham & Donnelly (1995). The data were later shared as the possum data set in the R package DAAG. Our file, possum.csv, is that data set with shorter column names — nothing else was changed.

The trail runs: our file → R package → peer-reviewed field study.

The animals are mountain brushtail possums, genus Trichosurus — nocturnal, tree-dwelling Australian marsupials. 104 of them were live-trapped at seven forest sites, from Victoria in the south up to Queensland, and each one was measured.

Our question:

Do possums from different sites differ in total length?

Role Column What it is
Response total_l total length, cm — a number
Factor site which forest it was trapped in — seven groups

One factor, seven levels. That is the entire design, and it is where the test gets its name.

✏️ Q1: A file on the internet is a copy, not a source — anyone can upload anything. How far back could you trace the data you are using for your final project? If you cannot find who collected it, what should that tell you?


Part 2 · Why not just run lots of t-tests?

Seven groups make 21 pairs. We know how to compare two groups, so why not do it 21 times?

Because each test at \(\alpha = 0.05\) carries a 5% chance of a false positive. Run 21 of them on data where nothing at all is going on:

\[1 - 0.95^{21} = 0.66\]

A 66% chance of at least one “significant” result from pure noise. You would find something roughly two times out of three, and it would mean nothing.

ANOVA asks one question instead — is there any difference among these seven means? — for one p-value and one 5% risk. It answers by comparing two kinds of variation:

\[F = \frac{\text{variation between groups}}{\text{variation within groups}}\]

  • \(F \approx 1\) → groups differ about as much as individuals do. Nothing to see.
  • \(F \gg 1\) → groups differ more than individuals within them do. Something is going on.

✏️ Q2: “More tests” sounds more thorough. Explain to someone who has not taken this class why running more tests makes you more likely to be wrong, not less.


Part 3 · Read it in

▶ Run this:

# Load packages ---------------------------------------
library(tidyverse)
library(car)          # Anova(), leveneTest()
library(performance)  # check_model(), check_normality()
library(emmeans)      # follow-up comparisons
library(effectsize)   # eta_squared()

# NOT loaded on purpose: multcomp. We call multcomp::cld()
# later instead - see Part 14.

# Read the file ---------------------------------------
possum_raw <- read_csv("data/possum.csv")

dim(possum_raw)
names(possum_raw)
  • 104 rows, 14 columns
  • head_l, skull_w, total_l, tail_l, foot_l, ear_l, eye, chest, belly are the measurements
  • animal, site, pop, sex, age describe the animal

Part 4 · The site column is a trap

▶ Run this:

possum_raw %>% count(site)

Seven groups, 7 to 33 animals each. But look at what those group names are.

They are the integers 1 to 7. To R, that is a quantity — as if site 6 were “twice site 3”. It is not. It is a name that happens to be written with a digit.

Leave it like that and lm() will fit a straight line through site number, which is nonsense. There is no error. There is no warning. You get a p-value, and it is meaningless.

✏️ Q3: Somebody numbered the sites 1–7 when they typed the data in. Does that make site a number? What would the model be claiming if you fit a line through it?


Part 5 · Name the sites, then make them a factor

Two small steps. First, swap each code for a name with case_when().

▶ Run this:

possum_df <- possum_raw %>%
  filter(!is.na(total_l)) %>%
  mutate(site_name = case_when(
    site == 1 ~ "Cambarville",
    site == 2 ~ "Bellbird",
    site == 3 ~ "Whian Whian",
    site == 4 ~ "Byrangery",
    site == 5 ~ "Conondale",
    site == 6 ~ "Allyn River",
    site == 7 ~ "Bulburin"))

possum_df %>% count(site, site_name)
  • Read each line as a sentence: “when site is 1, call it Cambarville”
  • Left of the ~ is the test, right of it is the name
  • We keep site and add a new column, site_name
  • A site you forget to list becomes NA — which is why we count() to check

Second, tell R those names are groups.

▶ Run this:

possum_df <- possum_df %>%
  mutate(site_name = as.factor(site_name))

levels(possum_df$site_name)
  • A factor is a column of group names that R knows are groups — not numbers, not free text
  • The groups are its levels
  • as.factor() puts the levels in alphabetical order unless you say otherwise

The site names come from the original study — we did not invent them. They sit in three states:

State Sites
Queensland Bulburin, Conondale
New South Wales Whian Whian, Byrangery, Allyn River
Victoria Cambarville, Bellbird

✏️ Q4: Suppose you typed two of the names on the wrong lines. What would R tell you? (Nothing.) What would happen to every result for the rest of the session?

🧭 Side trip · put the sites in your order

Alphabetical order means nothing here. North to south does. fct_relevel() lets you list the levels in the order you want.

▶ Run this:

possum_df <- possum_df %>%
  mutate(site_name = fct_relevel(site_name,
                                 "Bulburin", "Conondale",
                                 "Whian Whian", "Byrangery",
                                 "Allyn River", "Cambarville",
                                 "Bellbird"))

levels(possum_df$site_name)
  • It changes the order of the groups and nothing else — not one number in the data moves
  • Every plot and table from here on runs north → south
  • The first level (Bulburin) also becomes the model’s baseline — you will see that in Part 9
Site State Latitude
Bulburin Queensland 24.6° S
Conondale Queensland 26.4° S
Whian Whian New South Wales 28.6° S
Byrangery New South Wales 28.6° S
Allyn River New South Wales 32.1° S
Cambarville Victoria 37.6° S
Bellbird Victoria 37.6° S

Part 6 · Look at it before you test it

▶ Run this:

ggplot(possum_df, aes(x = site_name, y = total_l)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(width = 0.15, alpha = 0.5)
  • outlier.shape = NA stops the boxplot drawing outlier dots, because geom_jitter() is already drawing every point
  • width = 0.15 keeps the jitter tight enough that you can still tell which group is which

Read it before you test anything:

  • Bellbird sits low
  • Byrangery sits high
  • The middle five overlap heavily
  • The boxes are about equally tall — spread looks similar across sites
  • No wild outliers

✏️ Q5: Predict the result now, out loud: significant or not? Driven by which sites? Will the middle five separate from each other? Write your prediction down — you will check it in Part 12.

✏️ Q6: Why is predicting the answer before you test not cheating? (What would you do if the test came back disagreeing with the picture?)


Part 7 · The group means

▶ Run this:

possum_df %>%
  group_by(site_name) %>%
  summarise(n = n(),
            mean_total = round(mean(total_l), 1),
            sd_total   = round(sd(total_l), 2))
Site n Mean total length (cm)
Bulburin 18 85.7
Conondale 13 86.9
Whian Whian 7 88.1
Byrangery 7 92.2
Allyn River 13 84.5
Cambarville 33 89.7
Bellbird 13 81.8

There is an obvious story here, and it is wrong. Seven sites listed north to south invites:

Colder in the south → bigger animals. Bergmann’s rule.

Look again. The means do not climb steadily down that table, and the two Victorian sites — the southernmost — are at opposite extremes — Cambarville 89.7 cm, Bellbird 81.8 cm. Two forests, same state, 8 cm apart. Latitude cannot explain that.

✏️ Q7: A significant F will tell you the sites differ. What will it tell you about why? What else would you need to measure to test a latitude explanation?


Part 8 · Fit the model

▶ Run this:

total_model <- lm(total_l ~ site_name, data = possum_df)

response ~ predictor, exactly as in regression. The only change is that the predictor is a factor with seven levels instead of a number.

There is no separate ANOVA function. ANOVA is a linear model — not a simplification, literally the same machinery you used for regression.


Part 9 · Do not read summary() first

▶ Run this:

summary(total_model)

Look at the Estimate column. These are not slopes — there is no line here. They are means:

Row Estimate What it is
(Intercept) 85.7 the mean of Bulburin, the first level
site_nameConondale 1.2 Conondale’s mean minus Bulburin’s
site_nameWhian Whian 2.4 Whian Whian’s mean minus Bulburin’s
site_nameByrangery 6.5 Byrangery’s mean minus Bulburin’s → 85.7 + 6.5 = 92.2 cm
site_nameAllyn River −1.2 Allyn River’s mean minus Bulburin’s
site_nameCambarville 4.0 Cambarville’s mean minus Bulburin’s
site_nameBellbird −3.9 Bellbird’s mean minus Bulburin’s → 85.7 − 3.9 = 81.8 cm

Check them against the table of means in Part 7 — they match.

So each of the six p-values asks “is this site different from Bulburin?” — only because Bulburin is the first level. Nobody asked about Bulburin.

✏️ Q8: Put a different site first with fct_relevel() and all six of those p-values change. Does the real answer depend on which site happens to be listed first? So what does that tell you about this table?


Part 10 · The right table

▶ Run this:

Anova(total_model, type = 2)

F(6, 97) = 14.58, p = 8.45 × 10⁻¹²

One line, one p-value, one question answered: the seven site means are not all the same.

In the table Value What it is
Sum Sq (site) 907.6 variation explained by site
Sum Sq (resid) 1006.2 variation left over within sites
Df (site) 6 7 groups − 1
Df (resid) 97 104 possums − 7 groups
F value 14.58 the ratio, after dividing each Sum Sq by its Df

Between-site variation is 14 and a half times within-site variation.

NoteWhy type = 2?

With one factor, Types I, II and III give the identical answer — it genuinely does not matter here. We write type = 2 as a habit, because the moment you add a second factor it starts mattering a great deal.


Part 11 · How big is it? F does not say

▶ Run this:

eta_squared(Anova(total_model, type = 2), partial = FALSE)

Eta-squared (\(\eta^2\)) = 0.47. Which site a possum came from accounts for 47% of all the variation in total length. The other 53% is possums being individuals.

✏️ Q9: p answers “is it real?” and \(\eta^2\) answers “is it big?”. With a big enough sample, a difference far too small to care about gets a tiny p. Why must a results section report both?


Part 12 · Check the assumptions — after fitting

ANOVA assumes two things you can test, and one you check by thinking:

  1. Equal variances across groups
  2. Normal residuals — what the model missed is normally distributed
  3. Independence — each possum is one animal, trapped once, measured once ✅

You cannot check residuals before you have residuals. Fit first, then check.

▶ Run this:

check_model(total_model)

Five panels, read like this:

  • Posterior predictive check — simulated data should sit on top of real data
  • Linearity — flat line, no funnel
  • Homogeneity of variance — flat line; a slope or wedge means trouble
  • Influential observations — points inside the dashed contours
  • Normality of residuals — dots hugging the diagonal

All five look healthy here. That is a boring plot, and boring is exactly what you want.

▶ Then run this:

# Equal variances across sites?
leveneTest(total_l ~ site_name, data = possum_df)

# Normal residuals?
shapiro.test(residuals(total_model))

# The same two checks, in English:
check_homogeneity(total_model)
check_normality(total_model)
  • Levene p = 0.805 → no evidence variances differ. PASS
  • Shapiro–Wilk p = 0.588 → no evidence of non-normality. PASS
Warning⚠️ These tests run backwards

For the main test, a small p was the interesting result. For assumption tests it is the opposite — a small p means your test is in trouble.

Say it out loud every time: “Levene p = 0.805. Big. Variances are fine. Carry on.”

✏️ Q10: With small groups these tests are weak and pass almost anything; with huge samples they are brutal and fail on differences too small to matter. So why look at check_model() as well, every time?

✏️ Q11: Go back to your Part 6 prediction. Did the picture and the test agree?


Part 13 · F said “not all equal” — that is all it said

We have F(6, 97) = 14.58, p < 0.001: at least one site differs from at least one other. It does not say which, how many, or in which direction.

For that you need post-hoc comparisons — “after the fact”.

Running 21 comparisons was wrong as a first move. Running them after a significant F, with the p-values adjusted, is the standard, defensible approach. The gate came first.

▶ Run this:

site_means <- emmeans(total_model, ~ site_name)
site_means

pairs(site_means, adjust = "tukey")

emmeans gives each site’s estimated mean with a standard error and confidence interval. pairs() then compares all 21 pairs, and Tukey widens every p-value to pay for running 21 tests.

10 of the 21 pairs come back significant — the ends separate, the middle mostly does not. Exactly what the boxplot said.

✏️ Q12: What would these 21 p-values look like with adjust = "none"? Which pairs would flip? Is that the 66% problem from Part 2, back again?


Part 14 · The letters

Nobody wants 21 p-values in a results section. They want to know which groups cluster together.

The function that makes the letters is cld(), and it lives in the multcomp package — not in emmeans. We do not load multcomp. We borrow the one function with multcomp::.

▶ Run this:

multcomp::cld(site_means, Letters = letters)
NoteWhy multcomp::cld() and never library(multcomp)

package::function() means “use this one function from that package”. The package only has to be installed.

library(multcomp) drags in another package, MASS, which has its own select(). That hides the select() you have used all semester, and code that worked last week starts failing with strange errors. multcomp::cld() gets the letters with no side effects.

Share a letter → not shown to differ. No letter in common → they differ.

Site Mean (cm) Letters
Bellbird 81.8 a
Allyn River 84.5 ab
Bulburin 85.7 b
Conondale 86.9 bc
Whian Whian 88.1 bcd
Cambarville 89.7 cd
Byrangery 92.2 d

A clean ladder from 81.8 cm up to 92.2 cm. Bellbird (a) and Byrangery (d) share nothing, so they differ. Allyn River (ab) cannot be told apart from either neighbour.

Warning⚠️ Read R’s own note

“If two or more means share the same grouping symbol, then we cannot show them to be different. But we also did not show them to be the same.”

Sharing a letter is a failure to detect a difference — not evidence of equality. Byrangery has n = 7.

✏️ Q13: Byrangery has the highest mean and only 7 animals. If someone trapped 70 more there, what would you expect to happen to its letters — and why?


Part 15 · Put the letters on the plot

▶ Run this:

letters_df <- as.data.frame(multcomp::cld(site_means, Letters = letters)) %>%
  mutate(group = trimws(.group))

ggplot(possum_df, aes(x = site_name, y = total_l)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(width = 0.15, alpha = 0.4) +
  geom_text(data = letters_df,
            aes(x = site_name, y = 97, label = group),
            size = 5)
  • multcomp::cld() returns an object, so as.data.frame() makes it plottable
  • .group arrives padded with spaces for alignment, so trimws() strips them
  • y = 97 just parks the letters above the tallest point

This single figure now carries the whole result: the raw data, the group spread, and which groups differ.


Part 16 · Write it up

Important📝 The whole result, in three sentences

Total length differed significantly among the seven trapping sites (one-way ANOVA, F(6, 97) = 14.58, p < 0.001), and site accounted for 47% of the variation in length (η² = 0.47). Residuals were normally distributed (Shapiro–Wilk p = 0.59) with homogeneous variances across sites (Levene’s test p = 0.81). Tukey-adjusted comparisons separated Bellbird (mean 81.8 cm) from Byrangery (92.2 cm), with the remaining five sites forming an overlapping middle group.

Every number has a job: the test, F with both df (so a reader can reconstruct your design), p written as p < 0.001 and never p = 0.000, the effect size, the assumption checks so the reader knows you looked, and the pattern with real means attached.

✏️ Q14: That paragraph never uses the word “proves”, and never says two sites are “the same”. Find the places where it would have been tempting to say either, and explain what it says instead.


Part 17 · Break it on purpose

Remember Part 4 — site left as a number. Let us actually do it and compare.

▶ Run this:

broken_model <- lm(total_l ~ site, data = possum_df)

Anova(broken_model, type = 2)
Anova(total_model, type = 2)

The broken one reports Df = 1, not 6, and comes back p = 0.0075 — still “significant”!

It fit a single straight line through site ID and asked “does length go up as site number goes up?” — a question about the order someone typed the sites in. It still prints a p-value. Nothing warns you.

✏️ Q15: The broken model is significant. If you had never checked, you would have reported it. What in the output would have given it away?


The recipe, for next time

  1. case_when() the names → as.factor() (→ fct_relevel() if the order matters)
  2. Plot it, and predict the answer
  3. lm()
  4. Anova(type = 2)
  5. check_model() + leveneTest() + shapiro.test()
  6. eta_squared()
  7. emmeans() → pairs() → multcomp::cld()
  8. Write the sentence

Extension (homework) — the same possums, a different ruler

This is what you turn in: scripts/24_anova_one_factor_homework.R

The file carries nine measurements on every animal. The ones that matter to you:

Column What it is
total_l total length, cm — what we used today
ear_l ear length, mm — your homework
animal the animal’s ID number, 1–104 — you will need it

You run all eight steps again on ear_l. Same 104 animals, same seven sites, same recipe — a different ruler.

Today the sites formed a ladder: Bellbird at the bottom, Byrangery at the top, everything else overlapping in the middle. The question is whether ears tell the same story — or a different one.

Note📖 One check will fail — on purpose

Every assumption check you ran today passed, which makes it easy to think the check is a formality. It is not.

In the homework, one of the two checks fails. You will track down why, run the model a second way, and find out whether the conclusion depends on it. That is what a failed check is for: it tells you where to look.

Note📖 The data and the papers behind it
  • The data: the possum data set in the R package DAAG — https://cran.r-project.org/package=DAAG (description of every column)
  • Where the measurements came from: Lindenmayer, Viggers, Cunningham & Donnelly (1995). Morphological variation among populations of the mountain brushtail possum, Trichosurus caninus Ogilby (Phalangeridae: Marsupialia). Australian Journal of Zoology 43: 449–458. https://doi.org/10.1071/ZO9950449
  • Read this one after you finish the homework: Lindenmayer, Dubach & Viggers (2002). Geographic dimorphism in the mountain brushtail possum (Trichosurus caninus): the case for a new species. Australian Journal of Zoology 50: 369–393. https://doi.org/10.1071/ZO01047

The same researchers asked the question you are asking — do these sites differ? — and what they found changed how these animals are classified.

Next class — New Zealand tree wētā 🦗

Wellington tree wētā, Hemideina crassidens, is a large flightless relative of crickets found only in New Zealand. Its adult males come in three distinct forms: small-jawed sneaks, intermediates, and huge-jawed fighters that hold harems.

We will find the three forms differ enormously in ear size — wētā hear through a membrane on the foreleg. Then we will divide ear size by body size, run the identical test, and watch the answer change.

ANOVA answers the question you asked it. Making sure that is the question you meant is the whole job of next class.

ImportantBefore you hand in

Session > Restart R, then run the whole file top to bottom. It must run clean, and your plots must draw.