Skip to main content

ANCOVA

Analysis of covariance

Testing homogeneity of slopes, fitting an ANCOVA, and comparing covariate-adjusted means with emmeans, using the Partridge & Farquhar fruit fly longevity data from lecture.
Author

Bill Perry

📥 Download the R script 📊 Download the data

What ANCOVA does

ANCOVA compares group means (like ANOVA) while adjusting for a continuous covariate (like regression). The covariate soaks up variation that would otherwise sit in the error term, so group differences are easier to detect, and groups are compared at the same covariate value.

\[Y_{ij} = \mu + \alpha_i + \beta(X_{ij} - \bar{X}) + \varepsilon_{ij}\]

The key extra assumption: homogeneity of slopes. The covariate must have the same slope in every group (parallel lines). Test this first with a group × covariate interaction.

Data: Partridge & Farquhar (1981). Male fruit fly longevity (days) under five mating treatments, with thorax length (mm) as the covariate. Bigger flies live longer, so we adjust for size.

Step 1: Load packages and data

library(tidyverse)
library(car)       # Anova()
library(emmeans)   # adjusted means

# PARTNERS = number of females (0/1/8); TYPE = 0 inseminated, 1 virgin
partridge <- read_csv("data/partridge.csv") %>%
  mutate(treatment = case_when(
    PARTNERS == 0               ~ "No females",
    PARTNERS == 1 & TYPE == 0   ~ "One inseminated female daily",
    PARTNERS == 8 & TYPE == 0   ~ "Eight inseminated females daily",
    PARTNERS == 1 & TYPE == 1   ~ "One virgin female daily",
    PARTNERS == 8 & TYPE == 1   ~ "Eight virgin females daily"),
    treatment = factor(treatment, levels = c(
      "No females",
      "One inseminated female daily", "Eight inseminated females daily",
      "One virgin female daily", "Eight virgin females daily")))

count(partridge, treatment)
# A tibble: 5 × 2
  treatment                           n
  <fct>                           <int>
1 No females                         25
2 One inseminated female daily       25
3 Eight inseminated females daily    25
4 One virgin female daily            25
5 Eight virgin females daily         25

Step 2: Plot the covariate against the response

partridge %>%
  ggplot(aes(THORAX, LONGEV, color = treatment)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  labs(x = "Thorax length (mm)", y = "Longevity (days)", color = NULL) +
  theme_bw()

Lines that are roughly parallel suggest the slopes are homogeneous.

Step 3: Test homogeneity of slopes

options(contrasts = c("contr.sum", "contr.poly"))

homo_slopes_model <- lm(LONGEV ~ THORAX * treatment, data = partridge)
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 1.349e-06 ***
THORAX           12805.8   1 112.3988 < 2.2e-16 ***
treatment           36.9   4   0.0810    0.9881    
THORAX:treatment    42.5   4   0.0933    0.9844    
Residuals        13102.1 115                       
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Look only at the THORAX:treatment row. p > 0.05 means the slopes do not differ, so we can drop the interaction and fit the ANCOVA. (If it were significant, the treatment effect would depend on size; see the ANCOVA lecture for emtrends().)

Step 4: Fit the ANCOVA

ancova_model <- lm(LONGEV ~ THORAX + treatment, data = partridge)
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 6.123e-07 ***
THORAX      13168.9   1 119.219 < 2.2e-16 ***
treatment    9611.5   4  21.753 1.719e-13 ***
Residuals   13144.7 119                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Step 5: Check the assumptions

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

par(mfrow = c(1, 1))

shapiro.test(residuals(ancova_model))

    Shapiro-Wilk normality test

data:  residuals(ancova_model)
W = 0.99174, p-value = 0.6689

Step 6: Why the covariate helps

Compare the ANOVA without the covariate to the ANCOVA:

Anova(lm(LONGEV ~ treatment, data = partridge), type = "III")
Anova Table (Type III tests)

Response: LONGEV
            Sum Sq  Df  F value    Pr(>F)    
(Intercept) 412419   1 1880.794 < 2.2e-16 ***
treatment    11939   4   13.612 3.516e-09 ***
Residuals    26314 120                       
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The residual sum of squares is much larger without thorax length. The covariate removes size-related noise, so the F for treatment is larger in the ANCOVA.

Step 7: Adjusted means and pairwise comparisons

emmeans() gives each treatment’s mean at the average thorax length.

adjusted_means <- emmeans(ancova_model, ~ treatment)
adjusted_means
 treatment                       emmean   SE  df lower.CL upper.CL
 No females                        61.5 2.11 119     57.3     65.7
 One inseminated female daily      64.2 2.10 119     60.0     68.3
 Eight inseminated females daily   65.4 2.11 119     61.3     69.6
 One virgin female daily           54.5 2.11 119     50.3     58.7
 Eight virgin females daily        41.6 2.12 119     37.4     45.8

Confidence level used: 0.95 
pairs(adjusted_means, adjust = "tukey")
 contrast                                                       estimate   SE
 No females - One inseminated female daily                         -2.65 2.98
 No females - Eight inseminated females daily                      -3.93 3.00
 No females - One virgin female daily                               7.02 2.97
 No females - Eight virgin females daily                           19.95 3.01
 One inseminated female daily - Eight inseminated females daily    -1.28 2.98
 One inseminated female daily - One virgin female daily             9.67 2.98
 One inseminated female daily - Eight virgin females daily         22.60 2.99
 Eight inseminated females daily - One virgin female daily         10.95 3.00
 Eight inseminated females daily - Eight virgin females daily      23.88 2.97
 One virgin female daily - Eight virgin females daily              12.93 3.01
  df t.ratio p.value
 119  -0.891  0.8996
 119  -1.311  0.6849
 119   2.361  0.1336
 119   6.636 <0.0001
 119  -0.428  0.9929
 119   3.249  0.0129
 119   7.560 <0.0001
 119   3.650  0.0035
 119   8.031 <0.0001
 119   4.298  0.0003

P value adjustment: tukey method for comparing a family of 5 estimates 
multcomp::cld(adjusted_means, Letters = letters, adjust = "sidak")
 treatment                       emmean   SE  df lower.CL upper.CL .group
 Eight virgin females daily        41.6 2.12 119     36.0     47.1  a    
 One virgin female daily           54.5 2.11 119     49.0     60.0   b   
 No females                        61.5 2.11 119     56.0     67.0   bc  
 One inseminated female daily      64.2 2.10 119     58.7     69.7    c  
 Eight inseminated females daily   65.4 2.11 119     59.9     71.0    c  

Confidence level used: 0.95 
Conf-level adjustment: sidak method for 5 estimates 
P value adjustment: sidak method for 10 tests 
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. 
# put R's default contrasts back
options(contrasts = c("contr.treatment", "contr.poly"))

Step 8: Write it up

anc_aov   <- Anova(ancova_model, type = "III")
slope_aov <- Anova(homo_slopes_model, type = "III")

After adjusting for thorax length (F1,119 = 119.2, p < 0.001), longevity differed among mating treatments (ANCOVA: F4,119 = 21.8, p < 0.001). Slopes were homogeneous (thorax × treatment: p = 0.98). Males housed with eight virgin females had the shortest adjusted lifespan.

Report the slopes test, both F-tests from the ANCOVA, and the adjusted means (not the raw means).