Skip to main content

Linear Mixed Models

Random intercepts for nested data

Fitting a random-intercept mixed model with lme4, testing the fixed effect, reading the variance components, and checking diagnostics, using the urchin grazing data from lecture.
Author

Bill Perry

📥 Download the R script 📊 Download the data

What a mixed model does

When measurements are grouped (quadrats within patches, fish within lakes, repeated measures on one animal), observations in the same group are not independent. Treating them as independent is pseudoreplication: it inflates the df and makes p-values too small.

A linear mixed model has two kinds of effects:

  • Fixed effects: the treatments you care about and want to compare (urchin density).
  • Random effects: the grouping units you sampled from a larger population (patches). The model estimates one variance for them, not a separate mean for each.

\[algae_{ijk} = \mu + \alpha_i + b_{j(i)} + \varepsilon_{ijk}\]

Data: Andrew & Underwood’s urchin experiment. Urchin density was set to 0, 33, 66, or 100% in 16 patches (4 per treatment), and algal cover was measured in 5 quadrats per patch. The patch is the experimental unit, not the quadrat.

Step 1: Load packages and data

library(tidyverse)
library(janitor)       # clean_names()
library(car)           # Anova()
library(lme4)          # lmer()
library(lmerTest)      # Kenward-Roger F-tests
library(emmeans)       # post-hoc comparisons
library(performance)   # check_model(), icc()

# sum-to-zero contrasts for Type III tests
options(contrasts = c("contr.sum", "contr.poly"))

u_df <- read_csv("data/andrew.csv") %>%
  clean_names() %>%
  # the file's dens_33 / dens_66 labels are reversed relative to the book
  mutate(treat = case_when(
           treat == "removal" ~ "0%",
           treat == "dens_66" ~ "33%",
           treat == "dens_33" ~ "66%",
           treat == "control" ~ "100%"),
         treat = factor(treat, levels = c("0%", "33%", "66%", "100%")),
         patch = as_factor(patch))

count(u_df, treat, patch) %>% head()
# A tibble: 6 × 3
  treat patch     n
  <fct> <fct> <int>
1 0%    13        5
2 0%    14        5
3 0%    15        5
4 0%    16        5
5 33%   9         5
6 33%   10        5

Step 2: Plot quadrats within patches

u_df %>%
  ggplot(aes(patch, algae, color = treat)) +
  geom_point(alpha = 0.6) +
  stat_summary(fun = mean, geom = "point", size = 3, shape = 18) +
  labs(x = "Patch", y = "Algal cover (%)", color = "Urchin density") +
  theme_bw()

Quadrats in the same patch cluster together. That clustering is what the random effect models.

Step 3: The wrong model (for comparison)

wrong_model <- lm(algae ~ treat, data = u_df)
anova(wrong_model)
Analysis of Variance Table

Response: algae
          Df Sum Sq Mean Sq F value    Pr(>F)    
treat      3  14429  4809.7  9.0587 3.362e-05 ***
Residuals 76  40352   531.0                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

This uses 76 residual df, as if all 80 quadrats were independent, and gives p < 0.001. There are really only 16 patches. Compare this p-value with Step 6.

Step 4: Fit the mixed model

(1 | patch) adds a random intercept for each patch.

u_lmer_model <- lmer(algae ~ treat + (1 | patch), data = u_df)

summary(u_lmer_model)
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: algae ~ treat + (1 | patch)
   Data: u_df

REML criterion at convergence: 684.9

Scaled residuals: 
    Min      1Q  Median      3Q     Max 
-1.9808 -0.3106 -0.1093  0.2831  2.5910 

Random effects:
 Groups   Name        Variance Std.Dev.
 patch    (Intercept) 294.3    17.16   
 Residual             298.6    17.28   
Number of obs: 80, groups:  patch, 16

Fixed effects:
            Estimate Std. Error     df t value Pr(>|t|)   
(Intercept)   20.263      4.704 12.000   4.308  0.00102 **
treat1        18.938      8.147 12.000   2.324  0.03846 * 
treat2        -1.262      8.147 12.000  -0.155  0.87943   
treat3         1.287      8.147 12.000   0.158  0.87707   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
       (Intr) treat1 treat2
treat1  0.000              
treat2  0.000 -0.333       
treat3  0.000 -0.333 -0.333

Step 5: Variance components

VarCorr(u_lmer_model)
 Groups   Name        Std.Dev.
 patch    (Intercept) 17.156  
 Residual             17.280  
icc(u_lmer_model)
# Intraclass Correlation Coefficient

    Adjusted ICC: 0.496
  Unadjusted ICC: 0.379

The ICC (intraclass correlation) is the share of the variance that lies between patches. Here about half the variation is among patches, so ignoring them would be a serious mistake.

Step 6: Test the fixed effect

Use F-tests with Kenward-Roger df. Notice the denominator df: 12 (16 patches − 4 treatments), not 76.

Anova(u_lmer_model, type = 3, test.statistic = "F")
Analysis of Deviance Table (Type III Wald F tests with Kenward-Roger df)

Response: algae
                  F Df Df.res   Pr(>F)   
(Intercept) 18.5551  1     12 0.001018 **
treat        2.7171  3     12 0.091262 . 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Step 7: Post-hoc comparisons

u_emm <- emmeans(u_lmer_model, ~ treat)
u_emm
 treat emmean   SE df lower.CL upper.CL
 0%      39.2 9.41 12    18.70     59.7
 33%     19.0 9.41 12    -1.50     39.5
 66%     21.6 9.41 12     1.05     42.0
 100%     1.3 9.41 12   -19.20     21.8

Degrees-of-freedom method: kenward-roger 
Confidence level used: 0.95 
pairs(u_emm, adjust = "tukey")
 contrast   estimate   SE df t.ratio p.value
 0% - 33%      20.20 13.3 12   1.518  0.4573
 0% - 66%      17.65 13.3 12   1.327  0.5646
 0% - 100%     37.90 13.3 12   2.849  0.0615
 33% - 66%     -2.55 13.3 12  -0.192  0.9974
 33% - 100%    17.70 13.3 12   1.330  0.5625
 66% - 100%    20.25 13.3 12   1.522  0.4553

Degrees-of-freedom method: kenward-roger 
P value adjustment: tukey method for comparing a family of 4 estimates 

Step 8: Check the assumptions

A mixed model assumes normal residuals and normal random effects. The reqq panel checks the 16 patch intercepts.

check_model(u_lmer_model, check = c("qq", "reqq", "homogeneity"))

Algal cover is bounded at 0 and many quadrats are 0, so the residuals are not perfect. Report that, and note that 16 patches cannot support strong claims either way.

# put R's default contrasts back
options(contrasts = c("contr.treatment", "contr.poly"))

Step 9: Write it up

u_aov <- Anova(u_lmer_model, type = 3, test.statistic = "F")

Algal cover tended to decline with urchin density, but the effect was not significant once patch-to-patch variation was accounted for (linear mixed model with patch as a random intercept: F3,12 = 2.72, p = 0.091, Kenward-Roger df). Patches accounted for about 50% of the variance in algal cover.

Report the fixed-effect test with its (correct) df, the random-effect structure, and the variance components or ICC.

For random slopes and correlated residuals over time, see the Mixed Model Structures vignette. For where the variance components and p-values come from (REML, the nested ANOVA by hand, the bootstrap), see Mixed Models Under the Hood.