Skip to main content

Activity: ANCOVA

Covariates

Hands-on activity: analysis of covariance on Partridge & Farquhar’s fruitfly longevity data — testing homogeneity of slopes, what a covariate buys you in power, and adjusted means — then Arctic grayling allometry, where the slopes are not parallel and standard ANCOVA is off the table.
Author

Bill Perry

In-class Activity 17: ANCOVA

Today’s Objectives

  1. Say what a covariate is, and the two different jobs it does
  2. Test homogeneity of slopes, and know why it comes first
  3. Fit an additive ANCOVA and read its ANOVA table
  4. Measure what the covariate bought you — in residual SS and in F
  5. Read adjusted means, and say how they differ from raw means
  6. Recognise heterogeneous slopes and stop before fitting the wrong model
  7. Use emtrends() to compare slopes, and contrast groups at covariate values
  8. Say where an ANCOVA adjustment becomes extrapolation
Tip📂 Files for today

📥 Script skeleton (.R) 📥 Fruitfly data 📥 Grayling data

  • Save the skeleton as scripts/17_ancova.R, and both .csv files in your data/ folder.
  • You already have gray_I3_I8.csv from week 5 — same fish, new question.
ImportantWhat you hand in
  • All of today’s code is right here in this activity. Type it into your script as we go and run it chunk by chunk. The skeleton has the libraries, the two data reads, and the ANCOVA recipe as one comment block — every line of statistics you type yourself.
  • Section 6 has no code here either. By then you will have run the whole workflow once, so you start it again on your own.
  • The Q boxes are things to think about, not inline homework. Read them, talk them over, answer them in your head. You do not have to type answers into the script, and they are not graded.
  • The write-up at the bottom is practice for the homework. Do it, but it is not handed in.
  • Hand in the 🎟️ exit ticket at the bottom of this page, with your script. The script must run top to bottom (Ctrl/Cmd + Shift + Enter) with no errors.
Note🔮 Predict before you run

Today has one decision in it, and everything downstream depends on getting it right: are the slopes parallel? You will meet one dataset where they are and one where they are not. Before each test, look at the plot.

TipThe invisible(NULL) lines in the skeleton

Every section ends with invisible(NULL). It is a bumper. Press Ctrl/Cmd + Enter on a section’s last real line and your cursor jumps to the next line that has code on it — without the bumper, that is the next section, way down past the next heading. With it, the cursor stops right there and you keep your place. It does nothing and prints nothing.

Keep the plots plain today — no labels, colors, or themes. The goal is to read them. The one exception is the final figure in section 10, which is practice for the homework figure.


Where this fits

Week 10 changed the distribution. Week 11 changed the error structure. Today changes neither — it goes back to the ordinary linear model and asks what happens when you have one categorical predictor and one continuous predictor at the same time.

That is an ANCOVA, and it is the model that joins the ANOVA half of this course to the regression half.

What it is Example today
Response continuous fruitfly longevity, days
Factor categorical, the thing you care about mating treatment
Covariate continuous, the thing you adjust for thorax length, mm

A covariate does two different jobs, and they are worth keeping separate in your head:

Job What goes wrong without it Fixed by
Confounding groups sit at different covariate values, so a raw comparison of means confuses the two comparing at a common covariate value
Noise the covariate’s variation sits in the error term, shrinking your F removing it from the residual
Important

The one rule. The covariate must be measured independently of the treatment and must not be affected by it. Adjusting for something your treatment caused deletes the effect you are trying to measure. No diagnostic will catch this — only knowing how the data were collected.


🧩 Block 1 — The data and the critical test (after lecture Parts 1–3)

Sections 1–2: meet the data, see why a covariate is needed, then run the one test that decides everything else.

Section 1 · The data

Written for you in the skeleton — run it and read it.

# ---- Libraries -------------------------------------------
library(janitor)
library(car)          # Anova()
library(emmeans)      # emmeans(), emtrends()
library(lmtest)       # bptest()
library(tidyverse)

options(scipen = 999)
options(contrasts = c("contr.sum", "contr.poly"))  # for Anova(type = 3)

Partridge & Farquhar (1981) asked whether sexual activity shortens a male fruitfly’s life. They housed 125 males, 25 in each of five treatments, and recorded how long each male lived. The response longev is the male’s lifespan in days; the females are only the treatment (what each male lived with), and their lifespans were not recorded.

The design is cleverer than it first looks:

Treatment Females Do they mate?
No females 0 —
One inseminated female daily 1 no — newly inseminated females will not re-mate
Eight inseminated females daily 8 no
One virgin female daily 1 yes
Eight virgin females daily 8 yes
# ---- 1 The data ------------------------------------------
p_df <- read_csv("data/partridge.csv", show_col_types = FALSE) %>%
  clean_names() %>%
  mutate(
    treat = factor(
      case_when(
        partners == 0               ~ "no females",
        partners == 1 & type == 0   ~ "1 inseminated",
        partners == 8 & type == 0   ~ "8 inseminated",
        partners == 1 & type == 1   ~ "1 virgin",
        partners == 8 & type == 1   ~ "8 virgin"
      ),
      levels = c("no females", "1 inseminated", "8 inseminated",
                 "1 virgin", "8 virgin")
    )
  )

count(p_df, treat)

g_df <- read_csv("data/gray_I3_I8.csv", show_col_types = FALSE) %>%
  clean_names() %>%
  filter(mass_g > 0) %>%
  mutate(log_len  = log10(length_mm),
         log_mass = log10(mass_g))

count(g_df, lake)

You will look at the grayling (g_df) briefly in section 1b and analyse them properly in section 6. Two things in that read: filter(mass_g > 0) drops any fish weighed as 0 g, because the log of 0 is undefined; and log10() puts both length and mass on log scales, because mass grows as a power of length and a power law is a straight line on log-log axes (section 6 explains why that matters).

Tip🧾 The recipe in your skeleton

Right under the data reads is a comment block called THE ANCOVA RECIPE — the whole workflow in four steps, written with y, x and A. Every section today is that recipe with the real names swapped in. When you are stuck, look there first.

Warning

⚠️ Why the labels are built from partners and type, not from treatmen

The file has a treatmen column coded 1–5, but the codes are not in the order you would guess: 1 is eight inseminated, 2 is no females, 3 is one inseminated, 4 is one virgin, 5 is eight virgin.

Labelling them 1→“none”, 2→“one virgin”, 3→“eight virgin” — the obvious guess — reverses the biological conclusion. Building the labels from the design columns (partners and type) instead means they cannot drift out of step with the data.

✏️ Q1: What is the response, what is the factor, and what is the covariate?

✏️ Q2: Why are the inseminated-female groups in this experiment at all? What would you be unable to conclude without them?

✏️ Q3: Thorax length is the covariate. Could the mating treatment have changed a fly’s thorax length? Why does the answer matter?


Section 1b · Why a covariate? The grayling first

Written for you in the skeleton. Run it and read it.

Before any model, here is the problem ANCOVA solves. The Arctic grayling from week 5 come from two lakes. Are the fish in one lake heavier than in the other?

# ---- 1b Why a covariate? Grayling first ------------------
ggplot(g_df, aes(x = lake, y = mass_g)) +
  geom_boxplot()

g_df %>%
  group_by(lake) %>%
  summarise(mean_length = mean(length_mm),
            mean_mass   = mean(mass_g))

ggplot(g_df, aes(x = length_mm, y = mass_g, color = lake)) +
  geom_point()

Reading this:

  • The boxplot is the comparison a one-way ANOVA would make: I8 fish are about three times heavier on average (about 480 g vs 150 g).
  • The summary shows the catch: I8 fish are also about 100 mm longer on average. Longer fish are heavier, whatever lake they live in.
  • The scatterplot is the fair comparison: look at fish of the same length from the two lakes. That gap, not the gap in the boxplot, is the lake difference.

Fish length is the covariate: a continuous variable that affects the response, that the groups differ in, and that is not caused by the lake. Comparing raw means mixes the lake effect up with the length effect. ANCOVA separates them by comparing the groups at a common value of the covariate.

🔮 Talk it over: from the scatterplot alone, at the same length, does lake still seem to matter? Does the gap between the lakes look the same for small fish as for big fish? Hold onto your answer; section 6 tests it.

The fruitflies show the covariate’s other job, which is soaking up noise, so we start the analysis with them.


Section 2 · Look first, then test the slopes

▶ Type this yourself:

# ---- 2 Look first, then test the slopes ------------------
ggplot(p_df, aes(x = thorax, y = longev, color = treat)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)

🔮 Predict first: look at those five lines. Are they parallel? Commit to an answer before you run the test.

▶ Type this yourself — the homogeneity-of-slopes test:

slopes_model <- lm(longev ~ thorax * treat, data = p_df)

Anova(slopes_model, type = 3)

Reading this: thorax * treat is shorthand for thorax + treat + thorax:treat, so this model gives every treatment its own slope. The thorax:treat row tests whether those five slopes differ. We use type = 3 because the model has an interaction in it; that is what the options(contrasts = ...) line in your libraries is for.

✏️ Q4: Write down the F and p for the thorax:treat interaction. Are the slopes homogeneous?

✏️ Q5: Look at the treat row in this table. Is it significant? Hold onto that — you are about to fit a different model and get a very different answer.

💡 Key idea: the interaction term asks whether the groups share one slope. If they do not, there is no single “difference between the groups” to report — the difference depends on where you are along the covariate. That is why this test comes first, before the model you intend to publish.


🧩 Block 2 — The additive model (after lecture Part 4)

Sections 3–5: fit it, measure what the covariate bought, then read the adjusted means.

Section 3 · Fit the ANCOVA

Slopes are homogeneous, so drop the interaction.

▶ Type this yourself:

# ---- 3 Fit the ANCOVA ------------------------------------
ancova_model <- lm(longev ~ thorax + treat, data = p_df)

summary(ancova_model)

Anova(ancova_model, type = 2)

Reading this: thorax + treat (a +, not a *) forces one shared slope, so the five lines are parallel.

  • summary() gives the coefficients. The one you need is thorax, the shared slope (Q7). Ignore the treat rows there; section 5 gives you group means you can actually read.
  • Anova() gives one F test per term: thorax asks “does body size predict lifespan, once treatment is accounted for?” and treat asks “do the treatments differ, once body size is accounted for?”
  • type = 2 here: with no interaction in the model, type 2 and type 3 give the same F tests, and type 2 leaves out the intercept row you do not need.

✏️ Q6: Both thorax and treat are significant now. In Q5 the treat row was not. Same data, same question — what changed?

✏️ Q7: The thorax coefficient is about 136. What are its units, and what does it mean in fruitflies?

▶ Type this yourself — check the assumptions on the final model:

par(mfrow = c(2, 2))
plot(ancova_model)
par(mfrow = c(1, 1))

shapiro.test(residuals(ancova_model))

bptest(ancova_model)

✏️ Q8: Do the diagnostics look acceptable? Which plot tells you about equal variances?


Section 4 · What did the covariate buy you?

This is the whole power argument, in two models.

🔮 Predict first: run the same question with no covariate at all. Will the treatment effect get stronger, weaker, or stay the same?

▶ Type this yourself:

# ---- 4 What did the covariate buy you? -------------------
no_cov_model <- lm(longev ~ treat, data = p_df)

Anova(no_cov_model, type = 2)

Anova(ancova_model, type = 2)

p_df %>%
  group_by(treat) %>%
  summarise(mean_thorax = mean(thorax))

✏️ Q9: Fill this in from the two tables (the residual SS and df are in the Residuals row of each). What fraction of the residual SS did one df of thorax remove?

                  residual SS   residual df   treat F
no covariate
ANCOVA

✏️ Q10: The five groups have almost identical mean thorax lengths. So which of the covariate’s two jobs — confounding or noise — is it doing here?

💡 Key idea: a covariate earns its place even when your groups are perfectly balanced on it. Balance kills the confounding problem; it does nothing about the noise problem. Measure the covariate anyway.


Section 5 · Adjusted means

▶ Type this yourself:

# ---- 5 Adjusted means ------------------------------------
p_emm <- emmeans(ancova_model, "treat")
p_emm

p_df %>%
  group_by(treat) %>%
  summarise(raw_mean = mean(longev), mean_thorax = mean(thorax))

Reading this: emmeans() takes the fitted parallel lines and reads off each group’s predicted longevity at one common thorax length. That is the adjusted mean. The group_by() table gives the raw means next to it so you can compare.

▶ Type this yourself — the comparisons:

pairs(p_emm, adjust = "tukey")

multcomp::cld(p_emm, Letters = letters)

plot(p_emm, comparisons = TRUE)

Reading this:

  • pairs() tests all 10 pairs of treatments, with a Tukey adjustment for making 10 comparisons.
  • cld() (the compact letter display) summarises those 10 tests: groups that share a letter were not shown to differ.
  • In the plot(), the blue bars are the confidence intervals and the red arrows are for comparisons: two groups differ when their arrows do not overlap.

✏️ Q11: Put the adjusted means next to the raw means. Why is the gap small here, and what thorax length are the means adjusted to? (Check mean(p_df$thorax).)

✏️ Q12: Read the letter display. Which groups form one block, and what do they have in common? Say the result in one sentence about fruitflies — what is costing them their lifespan?

💡 Key idea: adjusted means are what ANCOVA compares — every group’s predicted response at the same covariate value. When the groups are already balanced on the covariate, they land close to the raw means and the covariate is pure power. When the groups are not balanced, the two can differ a lot, and the raw means are the misleading ones.


🧩 Block 3 — When the slopes are not parallel (after lecture Part 5)

Sections 6–7: the same workflow on data that refuses to cooperate.

Section 6 · Grayling allometry (you start this one)

No code for part of this page. You have just run the first two steps of the workflow once. Do them again.

Back to the Arctic grayling from week 5 — lakes I3 and I8. Fish mass scales with length as a power law, so on log-log axes the relationship is a straight line and its slope is the allometric exponent: mass ∝ lengthb. Why 3? Mass tracks volume, and volume is length × width × depth. A fish that keeps its shape gets wider and deeper in step with getting longer, so doubling its length multiplies its mass by 2³ = 8. A slope of 3 (isometry) means the fish keeps its shape as it grows; a slope below 3 means it gets thinner as it lengthens, and above 3 means it gets plumper.

Question: do grayling in the two lakes have the same length–mass relationship?

You already read the data in section 1 (g_df).

Now you:

  1. Plot log_mass against log_len, colored by lake, with a line per lake.
  2. Run the homogeneity-of-slopes test — the interaction model, then Anova(type = 3).
  3. Decide whether you are allowed to fit log_mass ~ log_len + lake.

💡 Hint: follow the recipe in your skeleton. Only the data frame and the three variable names change from sections 2–3.

✏️ Q13: What is the F and p for the interaction? What does that forbid you from doing?

✏️ Q14: Fit lm(log_mass ~ log_len + lake) anyway and look at the lake term. It is wildly significant. Why is that number not reportable?

✏️ Q15: Compare the two lakes’ length ranges (group_by(lake) %>% summarise(min(length_mm), max(length_mm))). What does that tell you about where you are allowed to compare them?


Section 7 · Reporting heterogeneous slopes

When slopes differ, the slopes are the result.

▶ Type this yourself:

# ---- 7 Reporting heterogeneous slopes --------------------
g_int <- lm(log_mass ~ log_len * lake, data = g_df)

emtrends(g_int, "lake", var = "log_len")

pairs(emtrends(g_int, "lake", var = "log_len"))

Reading this: emtrends() is emmeans() for slopes: "lake" asks for one slope per lake, and var = "log_len" says which variable the slope is taken with respect to. It only estimates; there is no test in it. pairs() then tests whether the two slopes differ. With two lakes that is the same test as the log_len:lake row in section 6: square its t and you get that F.

▶ Type this yourself — is each slope different from 3, the isometric value?

emtrends() on its own only estimates the slopes. Wrapping it in test() with null = 3 tests each slope against 3, with t = (slope − 3) / SE. Without null =, test() would test against 0, which is meaningless here.

test(emtrends(g_int, "lake", var = "log_len"), null = 3)

▶ Type this yourself — where along the covariate do the lakes actually differ?

lens <- log10(c(200, 250, 300))

pairs(emmeans(g_int, ~ lake | log_len, at = list(log_len = lens)))

Reading this:

  • The model was fit on log_len, so the lengths you ask about must be on the log scale too. log10(c(200, 250, 300)) is 2.30, 2.40 and 2.48, and that is how the output labels them.
  • at = list(log_len = lens) says where along the covariate to compare. ~ lake | log_len says “compare the lakes, separately at each of those lengths.”
  • Each estimate is a difference in log10 mass (I3 − I8). Back-transform it with 10^estimate to get a mass ratio: 10^-0.086 = 0.82 means an I3 fish is about 18% lighter than an I8 fish of the same length.

✏️ Q16: Write down each lake’s slope with its SE. Which one is indistinguishable from 3 (isometry — the fish keeps its shape), and what happens to the other lake’s fish as they get longer?

✏️ Q17: Look at the contrasts at 200, 250 and 300 mm. At which length are the lakes indistinguishable, and what happens to the gap as fish get bigger?

✏️ Q18: An additive ANCOVA would have reported one “lake effect.” Name the biological finding it would have thrown away.

💡 Key idea: a significant interaction is not a failed analysis — it is usually the more interesting one. “These groups differ by a constant amount” is a weaker, less informative claim than “these groups differ in how they scale.” When the data offer you the second, do not flatten it into the first.

Where is the lake row tested? In Section 6, the lake row of the interaction model’s Anova(type = 3) came out at p = 0.011. When a model contains an interaction, that main effect is the lake difference where the covariate equals 0. Here that’s log_len = 0, a 1 mm fish. You move the zero by centering: subtract a value you care about from the covariate. Below, log_len - log10(250) makes 0 mean a 250 mm fish, so the new lake row compares the lakes at 250 mm.

▶ Type this yourself:

g_df <- g_df %>%
  mutate(log_len_c = log_len - log10(250))

Anova(g_int, type = 3)

Anova(lm(log_mass ~ log_len_c * lake, data = g_df), type = 3)

✏️ Q19: Which rows changed between the two tables, and which stayed the same? What fish length is each lake row comparing the lakes at? Square the t ratio at 250 mm from Q17 and compare it with the new lake F.


Write-up (practice for the homework)

Answer these in your script as # comments after ANSWER:. Not handed in.

Section 8 · Report the fruitfly model

✏️ Q20: Fill in:

homogeneity of slopes   F(  ,  ) =        p =
covariate (thorax)      F(  ,  ) =        p =
treatment               F(  ,  ) =        p =
adjusted mean, 8 virgin        ±
adjusted mean, no females      ±

✏️ Q21: A 3–4 sentence results paragraph. Report the slopes test, then the ANCOVA, then the adjusted means with the letter display. Say what value the means are adjusted to.

✏️ Q22: One sentence on the biology: what does this experiment show costs a male fruitfly its lifespan, and which treatment groups let you rule out the alternative?

Section 9 · Report the grayling model

✏️ Q23: The interaction test, both slopes with their SEs, and the contrast at 250 mm.

✏️ Q24: Two or three sentences reporting it. You are reporting an interaction, so report slopes — not an adjusted mean.

✏️ Q25: Why would it have been wrong to report a single “lake effect” for these fish? Answer in a way a reviewer would accept.

Section 10 · The final figure

One publication-quality figure. Pick either the fruitfly adjusted means with their intervals, or the grayling log-log regression lines by lake with the raw points. Proper axis labels, a real theme, readable sizing. Treat it like the homework figure. Export it with ggsave().

# ---- 10 The final figure ---------------------------------
# ... your plot here, then:
# ggsave("figures/17_ancova.pdf", width = 7, height = 5)

✏️ Q26: If you drew the grayling figure, why must the two lines stop where the data stop? If you drew the fruitfly figure, why does the caption have to name the thorax length the means were adjusted to?


Review and checkpoint

At this point you should be able to:

Run your whole script top to bottom with Ctrl/Cmd + Shift + Enter. It must run clean.

💡 Key idea: every model this semester has been the same linear model with different pieces swapped in. ANCOVA swaps in a continuous predictor alongside a categorical one — and the only genuinely new question it asks is whether those two predictors interact.


🎟️ 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:

  1. scripts/17_ancova.R. It must run top to bottom with no errors.
  2. The exit ticket with these three answers.

✏️ E1. Section 2: write the F and p for the thorax:treat interaction. Are the slopes homogeneous?

✏️ E2. Section 4: residual SS without thorax and with it. What fraction of the residual SS did one df of thorax remove?

✏️ E3. Section 5: read the letter display. Which groups share a letter, and what is the result in one sentence?

Points: 3, one per answer. No script that runs, no points.


Homework

Homework 7 — ANCOVA

Does grazing help or hurt scarlet gilia (Ipomopsis)? You run the ANOVA you would have run last month, then the ANCOVA, and the two disagree about the direction of the effect. Today’s fruitflies had groups balanced on body size. These plants are not, and that is the twist.

Data: ipomopsis.csv — Crawley (2007) The R Book, Ch. 12; the argument behind it is Paige & Whitham (1987) vs Bergelson & Crawley (1992).

Start a new script for it. Do not add it to 17_ancova.R.