Activity: Two-Way ANOVA Redux
The same machinery on data that fights back
In-class Activity 14: Two-Way ANOVA Redux
Today’s Objectives
- Write a two-factor model with an interaction, and say what each term is
- Read
Anova(model, type = 3)on an unbalanced design - Use
emmeansfour ways: marginal, simple effects both directions, interaction contrast - Check the model with
check_model()and decide whether a violation mattered
📥 Script skeleton (.R) 📥 Crayfish growth data
- Save the skeleton as
scripts/14_two_way_anova_redux.R. - Save the csv in your project’s
data/folder.
- Each section gives you the shape of the code — the function and its arguments with generic names — and you fill in the names from this dataset.
- The ✏️ Q boxes are to answer out loud as we go. The only thing handed in is the 🎟️ exit ticket at the bottom.
- The skeleton is deliberately written so that you can reuse it on your own two-factor data. Swap the data read and the two factor names and the rest still runs.
Keep the plots plain — no labels, colors or themes. The goal is to read them.
🧩 Block 1 — The design (lecture Parts 1–2)
Section 1 · Libraries and data
Written for you in the skeleton.
library(car) # Anova()
library(emmeans) # emmeans(), emmip(), contrast()
library(effectsize) # eta_squared()
library(performance) # check_model(), check_normality()
library(janitor) # clean_names()
library(tidyverse)
cray_df <- read_csv("data/sargent_lodge_crayfish.csv") %>%
clean_names() %>%
mutate(range = factor(range, levels = c("Native", "Invasive")),
lake = factor(lake, levels = c("Big", "High", "Papoose")))Section 2 · Look at the design before you model it
The cell counts, then the cell means.
# the shape:
# df %>% count(factor_1, factor_2) %>%
# pivot_wider(names_from = factor_2, values_from = n)▶ YOUR CODE: count the cells, and pivot them into a 2 × 3 table.
# the shape:
# df %>% group_by(factor_1, factor_2) %>%
# summarise(n = n(), mean = mean(response), sd = sd(response),
# .groups = "drop")▶ YOUR CODE: build cray_cells — n, mean and sd for all six cells.
✏️ Q1: The smallest cell is 5 and the largest is 20. Is the design proportional — do the cell counts follow the row and column totals?
✏️ Q2: Read the mean column in pairs within each lake. Where is the Native–Invasive gap large, and where has it gone?
✏️ Q3: Read the sd column. Which cell has the smallest spread, which the largest, and roughly what ratio? Does the spread track the means?
Now two plots.
# the shape:
# ggplot(df, aes(factor_2, response, fill = factor_1)) + geom_boxplot()
#
# ggplot(cells, aes(factor_2, mean, color = factor_1, group = factor_1)) +
# geom_line() + geom_point()▶ YOUR CODE: a boxplot of the raw data, then an interaction plot of the cell means.
✏️ Q4: In the interaction plot, are the lines parallel? Do they cross? Describe the shape in one sentence.
Before any model, check the design for confounds.
# the shape:
# df %>% group_by(factor_1) %>%
# summarise(days = paste(sort(unique(days)), collapse = ", "),
# mean_temp = mean(avg_temp), n = n())▶ YOUR CODE: run it, and look at days and avg_temp by range.
✏️ Q5: days is perfectly confounded with range. The response is growth per day — what does that fix, and what does it not fix? Which of the three model terms are unaffected?
🧩 Block 2 — The model and its table (lecture Parts 3–5)
Section 3 · Write the factorial model
A two-factor model with an interaction has three terms. Written out in full:
# the shape, written the long way:
# model <- lm(y ~ x1 + x2 + x1:x2, data = df)
#
# and the shorthand that means exactly the same thing:
# model <- lm(y ~ x1 * x2, data = df)x1— the first main effectx2— the second main effectx1:x2— the interaction, which asks whetherx1’s effect is the same at every level ofx2x1 * x2— shorthand for all three
Type III sums of squares need sum-to-zero contrasts, and contrasts are fixed when lm() runs. So the order is always set → fit → test.
# the shape:
# options(contrasts = c("contr.sum", "contr.poly"))
# model <- lm(y ~ x1 * x2, data = df)▶ YOUR CODE: set the contrasts, then fit cray_model with growth_per_day as the response and range and lake as the two factors.
✏️ Q6: Write out in words what each of the three terms is asking.
Section 4 · Read the ANOVA table
# the shape:
# Anova(model, type = 3)▶ YOUR CODE: run it on cray_model.
✏️ Q7: Account for every df in the table. Where do 1, 2, 2 and 78 come from? (84 crayfish, 6 cells.)
✏️ Q8: Which row do you read first, and why? What does that do to how you read the two main-effect rows?
✏️ Q9: The (Intercept) row has F = 4461 and p < 0.0001. What is it testing, and why does nobody report it?
✏️ Q10: Now run anova(cray_model) — lower-case, base R. That is Type I. Compare the lake row to the Type III one. Which is bigger, and which would you report here?
🧩 Block 3 — Unpacking it, and checking it (lecture Parts 6–7)
Section 5 · emmeans, four ways
The interaction was significant, so the main effects are now conditional statements. These four calls are how you say what actually happened.
Way 1 — marginal means.
# the shape:
# emmeans(model, ~ x1)▶ YOUR CODE: the marginal means for range. Then compute the raw mean by range with group_by() / summarise() and compare.
✏️ Q11: The EMM difference is bigger than the raw difference. Which direction is the raw mean biased, and which cells caused it?
✏️ Q12: R printed a NOTE above the table. What is it warning you about — and is it right?
Way 2 — simple effects of range within each lake.
# the shape:
# pairs(emmeans(model, ~ x1 | x2))▶ YOUR CODE: run it. The | means “separately within each level of”.
✏️ Q13: Write the result of the study in one sentence, using these three numbers.
Way 3 — simple effects of lake within each range.
# the shape:
# pairs(emmeans(model, ~ x2 | x1))▶ YOUR CODE: swap the two factors around.
✏️ Q14: Did lake stop mattering for one range, or does it matter more for one? What shape of interaction is that?
✏️ Q15: Way 3 shows a Tukey adjustment and Way 2 does not. Why?
Way 4 — the interaction contrast.
# the shape:
# contrast(emmeans(model, ~ x1 * x2),
# interaction = c("pairwise", "pairwise"))▶ YOUR CODE: run it. These are differences of differences.
✏️ Q16: Which lake is responsible for the interaction? Which two lakes behave the same?
✏️ Q17: Only one of the four ways tells you where in the design the interaction lives. Which one, and why can the Anova() table never do that?
And the picture.
# the shape:
# emmip(model, x1 ~ x2, CIs = TRUE)▶ YOUR CODE: plot it.
✏️ Q18: Where do the confidence bands overlap, and where do they not? Does the figure agree with Way 4?
Section 6 · Effect size
# the shape:
# eta_squared(Anova(model, type = 3))▶ YOUR CODE: run it.
✏️ Q19: Which term has the largest effect size? Is it the term the study was about? What does that suggest about designing the next experiment?
Section 7 · Check the model
# the shape:
# check_model(model, check = c("qq", "homogeneity", "outliers"))
# check_normality(model)
# check_heteroscedasticity(model)▶ YOUR CODE: all three, on cray_model.
✏️ Q20: Which panels are unhappy, and what are they telling you? Does it match what you saw in the sd column in Q3?
Now find out whether it matters.
# the shape:
# model_log <- lm(log(y) ~ x1 * x2, data = df)
# Anova(model_log, type = 3)
# check_normality(model_log)
# check_heteroscedasticity(model_log)▶ YOUR CODE: refit on the log scale and re-check.
✏️ Q21: Both Warning: lines should now say OK:. Did any conclusion change?
✏️ Q22: You have two analyses that agree. Which do you report, and what one extra sentence do you owe the reader?
Section 8 · The figure
# the shape:
# as.data.frame(emmeans(model, ~ x1 * x2)) %>%
# ggplot(aes(x2, emmean, color = x1)) +
# geom_pointrange(aes(ymin = lower.CL, ymax = upper.CL),
# position = position_dodge(0.3))▶ YOUR CODE: build the figure from the model’s estimated marginal means — points, error bars, axis labels with units, readable legend. This is the one plot worth polishing.
✏️ Q23: Why build the figure from emmeans() output rather than from the raw cell means? On a balanced design, would it have mattered?
Checkpoint — can you do these now?
🎟️ Exit ticket
📥 Download the exit ticket (.docx)
Hand this in on Canvas before you leave. It is how I know you ran the code, so every answer comes from your own output. Upload two files:
scripts/14_two_way_anova_redux.R. It must run top to bottom with no errors.- The exit ticket with these three answers.
✏️ E1. Section 2: in each lake, how big is the Invasive − Native gap in growth per day? Where has it gone?
✏️ E2. Account for the df 1, 2, 2 and 78 in the ANOVA table.
✏️ E3. Which row do you read first, what does it say, and what does that do to the main-effect rows?
Points: 3, one per answer. No script that runs, no points.
Homework
Covers Analysis of Variance and both two-way sessions. Leaf area of shrubs and trees at four locations (Reich et al. 1998): a one-way ANOVA that finds nothing, then a two-way that finds the shrub–tree difference flipping sign between locations. The design is badly unbalanced (2 to 21 plants per cell), so the SS types disagree.
Data: reich_leaf_area.csv, from Quinn & Keough, Box 9-2. Ten questions, answered on the Word answer sheet linked from the homework page.
Start a new script for it.