
Lecture: ANCOVA — Analysis of Covariance
Covariates
Part 1 · From GLMs to ANCOVA
Where We Left Off
Covered last time — linear mixed models:
- Fixed vs. random effects, and
(1|group)notation - Variance components, the ICC, and partial pooling
- REML instead of partitioning sums of squares
Covered in week 10 — generalized linear models:
- Distribution, predictors, link
- Poisson, negative binomial, logistic
✅ Where today 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 the predictors are one categorical and one continuous at the same time.
This is the last of the general linear models, and the one that links the ANOVA half of the course to the regression half.
ANCOVA Overview
Overview
- Analysis of covariance (ANCOVA):
Introduction to ANCOVA
The ANCOVA workflow in R
When to use ANCOVA
Building the ANCOVA model in R
Assumptions of ANCOVA
- Homogeneity of slopes (The critical test!)
Interpreting results & “Adjusted Means”
Handling violations (heterogeneous slopes)
Introduction to ANCOVA
ANCOVA = Analysis of COVAriance — regression and ANOVA in one model. You use it when you have:
- a continuous response (Y)
- a categorical predictor (factor A)
- a continuous predictor, the covariate (X)
Two things it is for:
- Compare group means after adjusting for the covariate
- Ask whether two or more regression lines differ — in slope, in intercept, or both
When to Use ANCOVA
Three reasons, and the next slides take them one at a time:
- Power. The covariate soaks up residual “noise,” so the test of the factor gets stronger. (the fruitflies)
- Confounding. The groups sit at different covariate values, so raw means mislead. ANCOVA compares them at a common covariate value.
- Comparing regression lines. Do the groups share a slope at all? (the grayling)
The Motivating Problem — Grayling in Two Lakes
Back to the Arctic grayling from week 5 — the same fish, a new question.
Lake I8 fish weigh more than lake I3 fish. But I8 fish are also longer (mean 364 mm vs 266 mm).
Is there a lake effect on mass at all, or are I8 fish simply bigger?
You cannot answer that by comparing mean masses. The groups differ in the very thing that drives the response.

Two Problems, One Tool
Problem 1 — confounding. The groups differ in the covariate, so a raw comparison of means confuses the treatment with the covariate. This is the grayling problem.
Problem 2 — noise. Even when the groups are balanced on the covariate, the covariate still soaks up residual variation. Removing it shrinks the error term and makes the test of the factor more powerful. This is the fruitfly problem in Part 4.
ANCOVA does both with one model
\[y \sim \underbrace{x}_{\text{covariate}} + \underbrace{A}_{\text{factor}}\]
It compares groups at a common value of the covariate — the “level playing field” comparison — instead of wherever each group happened to sit.
⚠️ One rule before you start
The covariate must be measured independently of the treatment, and must not be affected by it. Adjusting for something the treatment caused removes the very effect you are trying to measure.
Part 2 · The ANCOVA Model
Raw Means vs Adjusted Means
The key idea in ANCOVA is the difference between raw and adjusted group means.
- Stars: raw means. Each group’s average X and average Y. The two groups sit at different X, so comparing their Ys mixes the group effect up with the covariate.
- Diamonds: adjusted means. Slide each raw mean along its own line (dashed) to one shared X, the overall mean of the covariate (dotted line).
- ANCOVA compares the heights of the diamonds: each group’s predicted Y if every group had the same covariate value.

Mathematical Model for ANCOVA
- Single-factor ANCOVA with
- factor A (p levels, i = 1 to p), a continuous covariate (x), and response variable (y): \(Y_{ij} = \mu + \alpha_i + \beta(X_{ij} - \bar{X}) + \varepsilon_{ij}\)
- Where:
- \(Y_{ij}\) = response value for observation j in level i of factor A
- \(\mu\) = overall mean
- \(\alpha_i\) = effect of level i of factor A (what we test in ANOVA)
- \(\beta\) = common regression slope relating Y to X (what we test in Regression)
- \(X_{ij}\) = covariate value for observation j in level i of factor A
- \(\bar{X}\) = mean value of covariate
- \(\varepsilon_{ij}\) = error term
ANCOVA Parameters Interpretation
- Interpretation of Parameters
- \(\mu\) = overall mean response
- \(\alpha_i\) = effect of level i (difference between group’s adjusted mean and overall mean)
- \(\beta\) = pooled within-group regression coefficient (the slope)
- \(X_{ij}\) = covariate value for observation j in group i
- \(\bar{X}\) = overall mean of covariate
- \(\varepsilon_{ij}\) = unexplained error
- Model assumes homogeneous slopes (i.e., \(\beta\) same for all groups) .

Where Along X Are the Groups Compared?
A regression intercept is the line’s height at x = 0. lm() builds an ANCOVA the same way, so its group coefficients describe the fruitflies at thorax = 0 mm: a fly with no thorax, predicted to live about -54 days.
That is why the textbook model writes \(\beta(X_{ij} - \bar{X})\). Centering moves “zero” to the mean thorax length, 0.82 mm, so \(\mu + \alpha_i\) becomes each group’s adjusted mean (the diamonds).
With parallel lines this does not change the test. Two parallel lines are the same distance apart at every x, so the treatment F is 21.75 whether or not you center. Only the meaning of the intercepts changes, and emmeans() reports the groups at the mean of x for you.

Non-parallel lines are different. In lm(y ~ x * A) the A row tests the gap at x = 0. More in Part 4.
Building the ANCOVA Model in R
ANCOVA is just the two lm() models you already know, added together.
| Model | Formula | Predictors |
|---|---|---|
| Regression | lm(y ~ x) |
one continuous |
| One-way ANOVA | lm(y ~ A) |
one factor |
| ANCOVA, slopes test | lm(y ~ x * A) |
both, plus x:A |
| ANCOVA, additive | lm(y ~ x + A) |
both, one shared slope |
x * A is shorthand for x + A + x:A. The x:A term asks one question: do the groups have different slopes?
The ANCOVA Recipe
# 1 Plot it - one line per group
ggplot(df, aes(x = x, y = y, color = A)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
# 2 Test the slopes - look at the x:A row
slopes_model <- lm(y ~ x * A, data = df)
Anova(slopes_model, type = 3)
# 3a x:A NOT significant - drop it
ancova_model <- lm(y ~ x + A, data = df)
Anova(ancova_model, type = 2)
emmeans(ancova_model, ~ A) # adjusted means
# 3b x:A significant - keep it, report slopes
emtrends(slopes_model, ~ A, var = "x")Step 2 decides everything.
- p > 0.05 → slopes are parallel → fit the additive model and compare adjusted means (3a)
- p < 0.05 → slopes differ → there is no single group difference. The slopes are the result (3b)
Check the residuals on whichever model you end up reporting.
This same recipe sits at the top of today’s script skeleton.
Part 3 · Partitioning Variance & the ANOVA Table
Three Models: Null, Covariate, Full
Each model adds one term to the one before it. Grey segments show how far each fly sits from what that model predicts.

| Model | R formula | What it predicts for each fly | Residual SS | SS it removes |
|---|---|---|---|---|
| Null | lm(longev ~ 1) |
the grand mean, 57.4 days, for every fly; no predictors at all | 38,253 | none: this is \(SS_{total}\) |
| Covariate | lm(longev ~ thorax) |
one line: longevity from body size alone, treatment ignored | 22,756 | 15,497 = \(SS_{x}\) |
| Full | lm(longev ~ thorax + treat) |
five parallel lines: body size, plus a shift up or down for each treatment | 13,145 | 9,611 = \(SS_{A(adj)}\) |
What the full model still cannot explain is \(SS_{residual}\). Every F test in ANCOVA asks the same thing: did adding this term remove more variation than chance would?
Where the Variation Goes in ANCOVA
Same idea as one-way ANOVA, with one more piece. Each fly’s distance from the grand mean splits three ways:
\[\underbrace{(Y - \bar{Y})}_{\text{total}} = \underbrace{(\hat{Y}_{x} - \bar{Y})}_{\text{covariate}} + \underbrace{(\hat{Y}_{x+A} - \hat{Y}_{x})}_{\text{treatment}} + \underbrace{(Y - \hat{Y}_{x+A})}_{\text{residual}}\]
\[SS_{total} = SS_{x} + SS_{A(adj)} + SS_{residual}\]
38,253 = 15,497 + 9,611 + 13,145
Dashed line = grand mean; grey line = one common slope; coloured lines = five parallel group lines.
In one-way ANOVA the covariate piece was buried inside the residual.

Reading the Partition
These are the sequential pieces — thorax entered first, then treatment given thorax — so they add exactly to \(SS_{total}\). It is what anova(lm(longev ~ thorax + treat)) reports.
Anova(..., type = "III") credits thorax only 13,169, not 15,497: the part of the thorax signal that overlaps treatment is not given to either term. The treatment and residual pieces are identical either way.
The residual is the denominator of every F.
Drop thorax and most of that covariate piece falls back into the residual: a one-way ANOVA on the same flies leaves 26,314, the ANCOVA only 13,145. A smaller denominator means a bigger F for treatment — the payoff you’ll see in Part 4.
ANOVA Table for ANCOVA
The general layout for one factor A with p groups, one covariate X, and n observations:
| Source | df | Sum of squares | Mean square | F | Expected mean square |
|---|---|---|---|---|---|
| Factor A (adjusted) | \(p - 1\) | \(SS_{A(adj)}\) | \(SS_{A(adj)} / (p - 1)\) | \(MS_{A(adj)} / MS_{residual}\) | \(\sigma^2 + n\sum\alpha_i^2 / (p - 1)\) |
| Covariate X | \(1\) | \(SS_{x}\) | \(SS_{x} / 1\) | \(MS_{x} / MS_{residual}\) | \(\sigma^2 + \beta^2 \sum (X - \bar{X})^2\) |
| Residual | \(n - p - 1\) | \(SS_{residual}\) | \(SS_{residual} / (n - p - 1)\) | \(\sigma^2\) | |
| Total | \(n - 1\) | \(SS_{total}\) |
For the fruitflies (n = 125, p = 5), as Anova(lm(longev ~ thorax + treat), type = "III") reports it:
| Source | df | Sum of squares | Mean square | F | p |
|---|---|---|---|---|---|
| treat (adjusted) | 4 | 9,611 | 2,403 | 21.75 | < 0.0001 |
| thorax | 1 | 13,169 | 13,169 | 119.22 | < 0.0001 |
| Residual | 119 | 13,145 | 110.5 |
Reading the expected mean squares: when H0 is true (all \(\alpha_i = 0\), or \(\beta = 0\)) the extra term drops out, the numerator estimates \(\sigma^2\) just as the residual does, and F ≈ 1. A big F means the term explained more than noise.
Null Hypotheses in ANCOVA
Homogeneity of Slopes (Test this first!)
\[H_0: \beta_1 = \beta_2 = ... = \beta_p\]
Are the regression slopes the same for all groups?
Test with the x:A interaction term in lm(y ~ x * A).
This one is an assumption check, not a result. You want to fail to reject it before going any further.
Null Hypotheses in ANCOVA: the Two Results
Once the slopes are parallel, the additive model lm(longev ~ thorax + treat) gives two tests. Each asks something different about the parallel lines.
Treatment effect, adjusted: the treat row
In words: if every fly had the same thorax length, would the treatments still differ in longevity?
In the picture: are the parallel lines at different heights?
\(H_0: \alpha_1 = \alpha_2 = \dots = \alpha_p = 0\), so all the lines collapse onto one. “Adjusted” means thorax has already taken its share, so groups are compared at the same body size.
Covariate effect: the thorax row
In words: within a treatment group, do bigger flies live longer?
In the picture: do the parallel lines slope?
\(H_0: \beta = 0\), so the lines are flat. Usually this is not the question you came for. It is the reason the covariate is in the model, and a big F here is what shrinks the residual.

Visualization of Homogeneity of Slopes
The first test in every ANCOVA is the x:A interaction in lm(y ~ x * A).
Left: parallel. Each group gains the same amount of Y per unit of X. The interaction is not significant, so drop it and fit the additive model.
Right: not parallel. Group A climbs much faster than group B, so the gap between them depends on where you look along X. There is no single “group effect” to adjust; the slopes are the result (Part 5).
The shaded bands are 95% confidence bands for each line.

Part 4 · Worked Example — Fruitfly Longevity
Fruitfly Example: Data Overview
Does mating shorten a male fruitfly’s life? Partridge & Farquhar (1981), Quinn & Keough Box 12-1.
- Response (
longev): each male’s lifespan in days, 125 males. The females are only the treatment. - Treatment (
treat): what each male lived with, 25 per group:
| Group | Male housed with | Can he mate? |
|---|---|---|
| no females | no females | no |
| 1 / 8 inseminated | 1 or 8 newly pregnant females | no: they won’t re-mate |
| 1 / 8 virgin | 1 or 8 virgin females | yes |
- Covariate (
thorax): each male’s thorax length (mm), i.e. body size. Bigger males live longer in every group, and the lines look parallel.

Fruitfly Example: Steps 1–2 — Test Homogeneity of Slopes
homo_slopes_model <- lm(longev ~ thorax * treat,
data = p_df)
Anova(homo_slopes_model, type = "III")
## Anova Table (Type III tests)
##
## Response: longev
## Sum Sq Df F value Pr(>F)
## (Intercept) 2963.8 1 26.0142 0.000001349 ***
## thorax 12805.8 1 112.3988 < 0.00000000000000022 ***
## treat 36.9 4 0.0810 0.9881
## thorax:treat 42.5 4 0.0933 0.9844
## Residuals 13102.1 115
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1The interaction thorax:treat has p = 0.984 — about as far from significant as it gets.
The five treatment groups share a common slope: body size buys the same amount of extra life in every group.
✅ Proceed to Step 3. Drop the interaction and fit the additive model.
Don’t Read the treat Row of the Interaction Model
Same model, but with thorax centered at its mean:
p_df_c <- p_df %>%
mutate(thorax_c = thorax - mean(thorax))
Anova(lm(longev ~ thorax_c * treat,
data = p_df_c), type = "III")
## Anova Table (Type III tests)
##
## Response: longev
## Sum Sq Df F value Pr(>F)
## (Intercept) 395872 1 3474.6454 < 0.00000000000000022 ***
## thorax_c 12806 1 112.3988 < 0.00000000000000022 ***
## treat 9387 4 20.5969 0.0000000000008076 ***
## thorax_c:treat 43 4 0.0933 0.9844
## Residuals 13102 115
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1On the last slide treat had F = 0.08, p = 0.99. That does not mean treatment does nothing.
With thorax * treat the lines may have different slopes, so the gap between groups can change along x. The treat row then tests the gap at thorax = 0 mm, far outside the data (0.64 to 0.94 mm).
Center thorax and the same row tests the gap at the mean thorax length, where the flies actually are: F = 20.6, p < 0.0001. The thorax_c:treat row does not change at all.
In the interaction model, read only the x:A row. That is why the recipe drops to the additive model before testing treatment. With parallel lines, centering changes nothing.
Fruitfly Example: Step 3 — Fit the Additive ANCOVA
- Since the interaction was not significant, we re-run the model without it.
- Interpretation:
- thorax: covariate highly significant
- thorax length explains significant amount of variance in longevity
- treat: treatment effect, after adjusting for thorax length, is highly significant
- Interpretation:
# Step 3: Fit the ANCOVA model (additive model)
ancova_model <- lm(longev ~ thorax + treat, data = p_df)
# View the final ANCOVA table
Anova(ancova_model, type = "III")
## Anova Table (Type III tests)
##
## Response: longev
## Sum Sq Df F value Pr(>F)
## (Intercept) 3069.7 1 27.791 0.0000006122893158 ***
## thorax 13168.9 1 119.219 < 0.00000000000000022 ***
## treat 9611.5 4 21.753 0.0000000000001719 ***
## Residuals 13144.7 119
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1What the Covariate Bought You
Run the same question without the covariate, and compare:
# one-way ANOVA, covariate ignored
Anova(lm(longev ~ treat, data = p_df),
type = 2)
## Anova Table (Type II tests)
##
## Response: longev
## Sum Sq Df F value Pr(>F)
## treat 11939 4 13.612 0.000000003516 ***
## Residuals 26314 120
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1# ANCOVA, thorax length included
Anova(lm(longev ~ thorax + treat, data = p_df),
type = 2)
## Anova Table (Type II tests)
##
## Response: longev
## Sum Sq Df F value Pr(>F)
## thorax 13168.9 1 119.219 < 0.00000000000000022 ***
## treat 9611.5 4 21.753 0.0000000000001719 ***
## Residuals 13144.7 119
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1| one-way ANOVA | ANCOVA | |
|---|---|---|
| residual SS | 26,314 | 13,145 |
| residual df | 120 | 119 |
| treatment F | 13.61 | 21.75 |
Thorax length absorbed half the residual variation.
One degree of freedom spent on the covariate cut the error term from 26,314 to 13,145, and the test of treat got 60% bigger (F 13.6 → 21.8) — on identical data and an identical question.
That is the power argument, and it is why you measure a covariate even when your groups are perfectly balanced on it.
Here the treatment effect was significant either way. On a smaller or noisier dataset, that difference is the difference between finding the effect and missing it.
Fruitfly Example: Getting Adjusted Means
- The ANOVA table tells us the treatments are different, but not which ones.
Use
emmeanspackage to get the adjusted means / perform pairwise comparisonsThe “estimated marginal mean” (or adjusted mean)
predicted longevity for each group, assuming an average thorax length
This is the “level playing field” comparison.
# Get adjusted means using emmeans
library(emmeans)
adjusted_means <- emmeans(ancova_model, "treat")
adjusted_means
## treat emmean SE df lower.CL upper.CL
## no females 61.5 2.11 119 57.3 65.7
## 1 inseminated 64.2 2.10 119 60.0 68.3
## 8 inseminated 65.4 2.11 119 61.3 69.6
## 1 virgin 54.5 2.11 119 50.3 58.7
## 8 virgin 41.6 2.12 119 37.4 45.8
##
## Confidence level used: 0.95Fruitfly Example: Pairwise Comparisons
pairs(adjusted_means, adjust = "tukey")
## contrast estimate SE df t.ratio p.value
## no females - 1 inseminated -2.65 2.98 119 -0.891 0.8996
## no females - 8 inseminated -3.93 3.00 119 -1.311 0.6849
## no females - 1 virgin 7.02 2.97 119 2.361 0.1336
## no females - 8 virgin 19.95 3.01 119 6.636 <0.0001
## 1 inseminated - 8 inseminated -1.28 2.98 119 -0.428 0.9929
## 1 inseminated - 1 virgin 9.67 2.98 119 3.249 0.0129
## 1 inseminated - 8 virgin 22.60 2.99 119 7.560 <0.0001
## 8 inseminated - 1 virgin 10.95 3.00 119 3.650 0.0035
## 8 inseminated - 8 virgin 23.88 2.97 119 8.031 <0.0001
## 1 virgin - 8 virgin 12.93 3.01 119 4.298 0.0003
##
## P value adjustment: tukey method for comparing a family of 5 estimatesSix of the ten are significant. The four that are not:
- No females vs. one inseminated — p = 0.90
- No females vs. eight inseminated — p = 0.68
- One vs. eight inseminated — p = 0.99
- No females vs. one virgin — p = 0.13
Every group that actually mated differs from the groups that did not, except the single-virgin group — the mildest treatment.
Fruitfly Example: Pairwise Comparisons — Compact Letters
## treat emmean SE df lower.CL upper.CL .group
## 8 virgin 41.6 2.12 119 37.4 45.8 a
## 1 virgin 54.5 2.11 119 50.3 58.7 b
## no females 61.5 2.11 119 57.3 65.7 bc
## 1 inseminated 64.2 2.10 119 60.0 68.3 c
## 8 inseminated 65.4 2.11 119 61.3 69.6 c
##
## Confidence level used: 0.95
## P value adjustment: tukey method for comparing a family of 5 estimates
## significance level used: alpha = 0.05
## 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.

Groups sharing a letter are not distinguishable. The red arrows say the same thing — overlapping arrows mean no significant difference.
Read the pattern, not the ranking
The three non-mating groups are one block. One virgin female pulls longevity down a little; eight pulls it down a lot.
The dose that matters is matings, not company.
Visualizing ANCOVA Results
Four ways to show one result:
- Raw data + lines: the covariate effect, and parallel slopes.
- Mean covariate (dashed): where ANCOVA compares the groups.
- Adjusted means: diamonds where each line crosses the dashed line.
- Bars ± 95% CI: what readers want, but the covariate is hidden.
Panels 3 + 4 together are the publication figure in Part 6.

Part 5 · Heterogeneous Slopes & Assumptions
What if the Slopes Are HETEROGENEOUS?
Back to the grayling. Fit the interaction model first, as always:
g_int <- lm(log_mass ~ log_len * lake, data = g_df)
Anova(g_int, type = 3)
## Anova Table (Type III tests)
##
## Response: log_mass
## Sum Sq Df F value Pr(>F)
## (Intercept) 1.8929 1 1337.5062 < 0.00000000000000022 ***
## log_len 4.0602 1 2868.9446 < 0.00000000000000022 ***
## lake 0.0094 1 6.6452 0.010833 *
## log_len:lake 0.0117 1 8.2518 0.004617 **
## Residuals 0.2293 162
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1The interaction is significant (p = 0.0046). The two lakes do not share a slope.
Stop. Do not fit the additive model.
log_mass ~ log_len + lake would force one common slope through two populations that do not have one, and then report a single “lake effect” that is true at no particular length.
There is no such thing as the difference between the lakes here. The difference depends on how big the fish is.
📖 This is not a failure
A significant interaction is usually the more interesting result. It says the groups differ in how the response scales, not merely in where it sits.
Reading Heterogeneous Slopes — emtrends()
emtrends(g_int, "lake", var = "log_len")
## lake log_len.trend SE df lower.CL upper.CL
## I3 2.79 0.0943 162 2.61 2.98
## I8 3.11 0.0569 162 3.00 3.22
##
## Confidence level used: 0.95
pairs(emtrends(g_int, "lake", var = "log_len"))
## contrast estimate SE df t.ratio p.value
## I3 - I8 -0.316 0.11 162 -2.873 0.0046
test(emtrends(g_int, "lake", var = "log_len"), null = 3)
## lake log_len.trend SE df null t.ratio p.value
## I3 2.79 0.0943 162 3 -2.203 0.0290
## I8 3.11 0.0569 162 3 1.910 0.0579emtrends() only estimates one slope per group, with its SE. pairs() tests the slopes against each other; test(..., null = 3) tests each against 3, t = (b − 3)/SE. On log-log axes the slope is the allometric exponent: mass ∝ lengthb.
Why 3? Mass tracks volume (length × width × depth). A fish that keeps its shape gets wider and deeper as it gets longer, so mass ∝ length³.
The biology is in the exponent
- I8: b = 3.11 — not distinguishable from 3 (p = 0.058). Isometric: these fish keep their shape as they grow.
- I3: b = 2.79 — significantly below 3 (p = 0.029). I3 grayling get relatively lighter as they lengthen.
An additive ANCOVA would have hidden this condition difference.
Where Do the Groups Actually Differ?
With non-parallel lines, the gap between groups changes along the covariate. So ask for the contrast at specific covariate values:
lens <- log10(c(200, 250, 300))
pairs(emmeans(g_int, ~ lake | log_len,
at = list(log_len = lens)))
## log_len = 2.30:
## contrast estimate SE df t.ratio p.value
## I3 - I8 -0.0299 0.01940 162 -1.540 0.1256
##
## log_len = 2.40:
## contrast estimate SE df t.ratio p.value
## I3 - I8 -0.0605 0.01110 162 -5.479 <0.0001
##
## log_len = 2.48:
## contrast estimate SE df t.ratio p.value
## I3 - I8 -0.0856 0.00914 162 -9.370 <0.0001| Length | I3 − I8 (log mass) | p |
|---|---|---|
| 200 mm | −0.030 | 0.13 |
| 250 mm | −0.061 | <0.0001 |
| 300 mm | −0.086 | <0.0001 |
At 200 mm the two lakes are indistinguishable. The gap opens as the fish get longer, and by 300 mm an I3 grayling is about 18% lighter than an I8 grayling of the same length (10−0.086 = 0.82). The lengths go in as log10() because the model is on log_len.
⚠️ johnson_neyman = TRUE does not work here
The Johnson–Neyman procedure needs a continuous moderator. interactions::sim_slopes() will warn “Johnson-Neyman intervals are not available for factor predictors or moderators” and give you nothing. With a categorical factor, the contrast-at-covariate-values above is the right tool.
Handling Heterogeneous Slopes — the Options
When the interaction is significant:
- Report the interaction. It is the result. Give the slopes, not an adjusted mean.
emtrends()for a slope per group, withpairs()to test them.- Contrast at chosen covariate values —
emmeans(~ A | x, at = ...)— to say where along the covariate the groups separate. - Johnson–Neyman, but only when the moderator is continuous.
- Separate regressions per group. Simple, honest, least powerful, and it gives up the shared error term.
⚠️ Mind the covariate ranges
I3 fish run 191–320 mm; I8 fish run 207–440 mm. The lines can only be compared where both groups have data.
Reporting a lake difference at 400 mm would mean extrapolating the I3 line past every I3 fish ever measured. ANCOVA will do that arithmetic without complaint. You have to be the one who refuses.
This caution applies to the additive model too — an “adjusted mean” at \(\bar{x}\) is an extrapolation for any group whose data does not reach \(\bar{x}\).
Assumptions of ANCOVA
| # | Assumption | How you check it |
|---|---|---|
| 1 | Independence | design, not a test |
| 2 | Normal residuals | Q-Q plot |
| 3 | Equal variances | residuals vs. fitted |
| 4 | Linearity of Y on X within each group | scatterplot |
| 5 | Homogeneity of slopes | the x:A interaction |
#5 is the one that is special to ANCOVA, and the only one you test before fitting the model you will report. The other four are the ordinary linear-model assumptions you have been checking since week 7.
⚠️ And one that is not on the list
The covariate must be independent of the treatment. No test will catch a violation — only knowing how the data were collected will.
Checking Assumptions in R

Check assumptions 2 and 3 on the final model — the additive one, if the slopes let you fit it.
- Residuals vs. fitted — red line roughly flat at 0 ✅
- Normal Q-Q — points on the dashed line ✅
- Scale-location — red line flat ✅
- Residuals vs. leverage — nothing stranded in the right-hand corners ✅
Conclusion: the assumptions are met, so the ANCOVA table on the previous slides can be reported as it stands.
Robust ANCOVA Approaches
When the assumptions are badly violated — not marginally:
- Rank transformation — rank both Y and X, then run the ordinary ANCOVA on the ranks:
lm(rank(y) ~ rank(x) + A) - Bootstrapping — resample to get intervals without assuming normality
- Quantile regression — model the median, or any quantile, instead of the mean
- Permutation tests — randomise the treatment labels to build the null distribution
🖐 Run it as a sensitivity check. If the robust version agrees with the parametric one, report the parametric one and say you checked.
rank_ancova <- lm(rank(longev) ~ rank(thorax) + treat,
data = p_df)
signif(c(
parametric = Anova(ancova_model, type = "III")["treat", "Pr(>F)"],
rank_based = Anova(rank_ancova, type = "III")["treat", "Pr(>F)"]), 3)
## parametric rank_based
## 0.000000000000172 0.000000000000654Both vanishingly small — the parametric result stands.
Part 6 · Reporting Results
Writing Up ANCOVA Results
Scientific Writing Example
Here’s how you might write up ANCOVA results for publication:
“We analyzed the effects of mating opportunity on male fruitfly longevity using analysis of covariance (ANCOVA), with thorax length as a covariate. Before conducting the main analysis, we tested the homogeneity-of-slopes assumption and found no significant treatment × thorax length interaction (F₄,₁₁₅ = 0.09, P = 0.98), indicating that the effect of body size on longevity was consistent across treatments.
The ANCOVA revealed significant effects of both treatment (F₄,₁₁₉ = 21.75, P < 0.001) and thorax length (F₁,₁₁₉ = 119.22, P < 0.001) on longevity. Thorax length was positively associated with longevity.
After adjusting for body size, longevity declined with the number of virgin females a male was housed with (adjusted mean ± SE: 54.5 ± 2.11 days for one virgin female and 41.6 ± 2.12 days for eight, versus 61.5 ± 2.11 days for males housed alone). Males housed with inseminated females — which do not mate — did not differ from males housed alone (64.2 ± 2.10 and 65.4 ± 2.11 days; Tukey P = 0.90 and P = 0.68). Six of the ten pairwise comparisons were significant at P < 0.05; the four that were not were the three comparisons among the non-mating groups and the no-females vs. one-virgin-female comparison (P = 0.13).”
Why the Inseminated-Female Groups Are the Design
The control that makes the experiment work
Newly inseminated females will not mate. Males housed with them get the presence of females without the mating.
Those groups isolate the cost of mating itself from the cost of simply having company — and they show no reduction in longevity at all (65.4 and 64.2 days, against 61.5 for males housed alone).
📖 What this buys the write-up
Without those two groups you could only say “males near females die younger,” which has at least three explanations. With them, the conclusion narrows to one.
Design, not statistics, is what rules out the alternatives. ANCOVA just made the comparison fair on body size.
Publication Quality Figure
Left: the data, the five parallel ANCOVA lines, and each adjusted mean ± 95% CI at the mean thorax length (dashed). Right: the same adjusted means as bars, for readers who only want the comparison.

Summary
What it is for
- Combines regression and ANOVA
- Increases power by soaking up residual variation with a covariate
- Adjusts for confounds by comparing groups at a common covariate value
The workflow
- Always test homogeneity of slopes first —
lm(y ~ x * A) - Slopes homogeneous (p > 0.05) → fit the additive model,
lm(y ~ x + A), and report adjusted means - Slopes heterogeneous (p < 0.05) → stop. Interpret the interaction and report slopes
Summary — Interpreting and Reporting
Interpretation
car::Anova(model, type = "III")for the tableemmeans()for adjusted means and pairwise comparisonsemtrends()for slopes, when the interaction is the result- Report adjusted means, and say what covariate value they are adjusted to
The five assumptions
- Independence
- Normal residuals
- Equal variances
- Linearity within groups
- Homogeneity of slopes — the one you test first
And the one no test will find: the covariate must not be affected by the treatment.
Readings
- Quinn & Keough (2002), Experimental Design and Data Analysis for Biologists, Ch. 12 — Analysis of Covariance. This is the source of today’s fruitfly example (Box 12-1, Table 12-2).
- Gotelli & Ellison, Ch. 9 (Regression) and Ch. 10 (The Analysis of Variance) — ANCOVA sits across the two frameworks.
- Whitlock & Schluter, Ch. 17 — Regression, for the diagnostics that carry over.
- Partridge, L., & Farquhar, M. (1981). Sexual activity reduces lifespan of male fruitflies. Nature, 294, 580–582.
📖 On the datasets
The fruitfly data are Partridge & Farquhar’s, reproduced in Quinn & Keough Box 12-1. The Arctic grayling are from the Arctic LTER — the same lakes you met in week 5.
The textbook PDFs are on Canvas.
🖐 The homework plants
Homework 7 is Crawley’s Ipomopsis grazing data. The groups are not balanced on the covariate, so this time it does the confounding job, and an ANOVA and an ANCOVA disagree about the direction of the effect.