Skip to main content

Activity: Linear Mixed Models

Random effects for nested data

Hands-on activity: fitting the sea urchin nested design with lme4::lmer(), reading the patch and residual variances, using the ICC to see what the next experiment needs, testing the treatment with the F-test, and making the final figure. Then two more designs: chick growth through time with random slopes, and a simulated stream experiment blocked by stream.
Author

Bill Perry

In-class Activity 16: Linear Mixed Models

Today’s Objectives

  1. Say why patch is a random effect and treat is fixed
  2. Fit a nested design with lmer() and read the two variances it prints
  3. Use the ICC to say how much patches matter, and what the next experiment needs
  4. Test the treatment with the F-test, and say why not the chi-square
  5. Get treatment means with emmeans() and check the model with DHARMa
  6. Find the real replicate in two more designs: chicks through time, and streams
Tip📂 Files for today

📥 Urchin data 📥 Stream data (simulated) 📥 Script skeleton (.R) 📥 Complete script (.R)

  • Save the skeleton as scripts/16_linear_mixed_models.R, and both .csv files in your data/ folder.
  • The complete script has every line of code already written. Use it if you would rather run and read than type. The write-up ANSWER: lines are still blank for you.
  • The stream data are for section 10 at the end. They are simulated, not a real study.
ImportantWhat you hand in
  • All of today’s code is on this page. Type it into your script and run it chunk by chunk. The skeleton has the libraries, the data reads and the plots for sections 9–10.
  • The Q boxes are things to think about and talk over. 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.
TipThe invisible(NULL) lines in the skeleton

Every section ends with invisible(NULL). It does nothing. It just stops your cursor at the end of the section when you run code with Ctrl/Cmd + Enter, so you keep your place.

Keep the plots plain today (no labels, colours or themes), except the final figure in section 8, which is practice for the homework figure.


Where this fits

16 patches of reef each got one urchin density. 5 quadrats were scored in every patch. The treatment was applied to the patch, so there are 16 real replicates, not 80. In lecture, ignoring that gave p = 0.00003; testing the treatment against patches gave p = 0.091.

A mixed model handles this by naming patch as a random effect.

Fixed effect Random effect
What it is levels you chose levels sampled from many
What you want the difference between them how much they vary
Here treat, the four densities patch, 16 bits of reef

R will print two variances. We call them by R’s names:

  • patch variance: how much patches differ from their own treatment’s mean (among-patch)
  • residual variance: how much quadrats differ from their own patch’s mean (within-patch)

🧩 Block 1: Fit the model and read it (after lecture Parts 1–2)

Section 1 · The sea urchin data

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

# ---- Libraries -------------------------------------------
library(janitor)
library(car)          # Anova()
library(lme4)         # lmer()
library(lmerTest)     # df and p-values for lmer
library(emmeans)
library(performance)  # icc()
library(DHARMa)
library(tidyverse)

options(scipen = 999)
options(contrasts = c("contr.sum", "contr.poly"))  # for Anova(type = 3)
# ---- 1 The sea urchin data -------------------------------
u_df <- read_csv("data/andrew.csv") %>%
  clean_names() %>%
  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)
  )

head(u_df)

✏️ Q1: What was the treatment applied to: a quadrat or a patch? So how many real replicates are there?


Section 2 · Fit the mixed model and read the output

▶ Type this yourself:

# ---- 2 Fit the mixed model -------------------------------
mixed_model <- lmer(algae ~ treat + (1 | patch), data = u_df,
                    control = lmerControl(calc.derivs = FALSE))

summary(mixed_model)

(1 | patch) gives each patch its own baseline: a random intercept. calc.derivs = FALSE just skips a noisy convergence check.

Find the Random effects block:

 Groups   Name        Variance Std.Dev.
 patch    (Intercept) ...
 Residual             ...

✏️ Q2: Write down the patch variance and the residual variance. Which is bigger, or are they about the same?

✏️ Q3: The output says Number of obs: 80, groups: patch, 16. Which number is the real replication for testing treat?

✏️ Q4: Why is patch random and treat fixed? (Hint: would a repeat of the study use the same patches? The same densities?)

💡 Skip the Fixed effects table in summary(). With contr.sum, treat1, treat2 and so on are deviations from the grand mean, which is confusing. You will get the treatment means from emmeans() in section 5.


🧩 Block 2: How much do patches matter? (after lecture Part 3)

Section 3 · The ICC

🔮 Predict first: the four patches with urchins removed have means of 34, 62, 2 and 58% algae. Is more of the variation among patches, or among quadrats within a patch?

▶ Type this yourself:

# ---- 3 The ICC -------------------------------------------
icc(mixed_model)

The ICC is

\[ICC = \frac{\text{patch variance}}{\text{patch variance} + \text{residual variance}}\]

the share of the variation that is among patches. Use the adjusted ICC.

✏️ Q5: Check it by hand from your Q2 numbers. Do you get the same value?

✏️ Q6: Finish this sentence about the reef: “About % of the differences in algae cover come from .”

✏️ Q7: An ICC near 0 would mean what about the patches? Near 1?

✏️ Q8: Next year you can afford either twice as many quadrats per patch or twice as many patches. Which one helps more, and why? (Think about patch 15, which was nearly bare.)

▶ Type this yourself: R², how much of the variation each part explains:

r2(mixed_model)

A mixed model gets two R² values:

  • Marginal R²: explained by the fixed effects only (treat)
  • Conditional R²: explained by fixed and random effects (treat + patch)

✏️ Q8b: What share of the variation in algae cover does the treatment explain? What share do treatment and patch explain together? So what share is due to patches alone (conditional − marginal)?

✏️ Q8c: Which explains more of the variation: urchin density or which patch a quadrat was in? Why would reporting only “R² = 0.62” be misleading?


🧩 Block 3: Test, means and checks (after lecture Part 4)

Section 4 · Test the treatment

▶ Type this yourself:

# ---- 4 Test the treatment --------------------------------
Anova(mixed_model, type = 3, test.statistic = "F")

Anova(mixed_model, type = 3, test.statistic = "Chisq")

✏️ Q9: Write down the p-value from each. Which side of 0.05 does each fall on?

✏️ Q10: The F-test’s denominator df is 12. Where does 12 come from? (Patches, treatments.)

✏️ Q11: The chi-square test assumes you have infinite replicates. You have 16 patches. Which test do you report?

💡 Key idea: with few groups, which is nearly always the case in ecology, report the F-test (Kenward-Roger df). The chi-square is over-confident, and if you had run only that one you would have reported a “significant” effect and never known.


Section 5 · Treatment means

▶ Type this yourself:

# ---- 5 Treatment means -----------------------------------
emm <- emmeans(mixed_model, ~ treat)
emm

pairs(emm, adjust = "sidak")

✏️ Q12: What is the mean algae cover with urchins removed (0%) and at natural density (100%)? Is that a big difference?

✏️ Q13: Some confidence limits go below zero. Algae cover can’t be negative. What is the model assuming that isn’t true? (Last week’s lecture has the fix.)


Section 6 · Diagnostics

▶ Type this yourself:

# ---- 6 Diagnostics ---------------------------------------
set.seed(123)
sim_mixed <- simulateResiduals(mixed_model, plot = FALSE)

plotQQunif(sim_mixed)
plotResiduals(sim_mixed)

✏️ Q14: Do the plots look acceptable, roughly? Percent cover with lots of zeros won’t be perfect. What would you say in a methods section?


Note🚀 Optional challenge (not graded)

Want to see where the patch variance comes from, the old way? Or check that lmer() gives the same F as aov(algae ~ treat + Error(patch))? Both are worked through, with code, in the Mixed Models Under the Hood vignette (Steps 2, 3 and 6). The complete script has the comparison at the bottom of section 6.


🎟️ 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/16_linear_mixed_models.R. It must run top to bottom with no errors.
  2. The exit ticket with these three answers.

✏️ E1. Section 2: write the patch variance and the residual variance. Which is bigger?

✏️ E2. Section 2: Number of obs: 80, groups: patch, 16. Which number is the real replication for treat, and why?

✏️ E3. Section 3: finish the sentence: “About % of the differences in algae cover come from .”

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


Homework

Homework 6 — Linear Mixed Models

The rusty crayfish growth experiment, but now lake is a random effect rather than a fixed factor. Same data as the Two-Way ANOVA Redux, on purpose: comparing the fixed and random analyses is the assignment. Lecture Part 7 walks through it.

Data: sargent_lodge_crayfish.csv from Sargent & Lodge (2014), Evolutionary Applications 7: 949–961.

Start a new script for it. Do not add it to 16_linear_mixed_models.R.


Write-up (practice for the homework)

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

Section 7 · Report the model

✏️ Q15: Fill in the table:

test                      F or Chisq   df      p
F (Kenward-Roger)
chi-square

✏️ Q16: The patch variance, the residual variance, the ICC, and the marginal and conditional R², plus one plain sentence about what the ICC means for this reef.

✏️ Q17: A 2–3 sentence results paragraph. Report the F-test, the variance components and both R² values. (The lecture’s “Reporting the Result” slide is a model.)

✏️ Q18: Does this experiment show urchins have no effect on algae cover? Use the treatment means and the ICC in your answer.

✏️ Q19: If you repeated this experiment, would you add more quadrats or more patches? Use the ICC to justify it.

Section 8 · The final figure

One publication-quality figure showing both levels of variation: the treatment means with their 95% intervals from the model, and the 16 patch means behind them. Proper axis labels, a real theme, readable sizing. Treat it like the homework figure. Export it with ggsave().

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

💡 You’ll need the patch means: u_df %>% group_by(treat, patch) %>% summarise(algae = mean(algae), .groups = "drop"), and the model means: as_tibble(emm).

✏️ Q20: Your figure shows two kinds of spread: among patches within a treatment, and among the treatment means. Which one does the treatment have to beat?


🧩 Block 4: Two designs you will actually run (after lecture Part 6)

Not graded.

Section 9 · Animals through time: chick growth

ChickWeight ships with R: 50 chicks on 4 diets, each weighed up to 12 times over 21 days.

Written for you in the skeleton. Run it and look at the plot.

# ---- 9 Animals through time - chick growth ---------------
ck_df <- as_tibble(ChickWeight) %>%
  clean_names() %>%
  mutate(chick = factor(chick, ordered = FALSE))

ggplot(ck_df, aes(x = time, y = weight, group = chick)) +
  geom_line() +
  facet_wrap(~ diet)

✏️ Q21: The diet was given to a chick. How many chicks are there, and how many rows? Which is the replication for a diet effect? Do the lines run parallel or fan out?

▶ Type this yourself: the question is whether chicks grow at different rates on different diets (time:diet), fitted three ways:

ck_lm <- lm(weight ~ time * diet, data = ck_df)
ck_ri <- lmer(weight ~ time * diet + (1 | chick), data = ck_df)
ck_rs <- lmer(weight ~ time * diet + (1 + time | chick), data = ck_df)

Anova(ck_lm, type = 3)
anova(ck_ri)
anova(ck_rs)

✏️ Q22: Write down the denominator df for time:diet in all three. Which one is close to the number of chicks?

▶ Type this yourself:

VarCorr(ck_rs)

emtrends(ck_rs, ~ diet, var = "time")

✏️ Q23: emtrends() gives the average growth rate on each diet (the time.trend column, in g/day). The time SD in VarCorr() is how much individual chicks vary around that average. Using both: what growth rate would a typical chick on diet 1 have, give or take one SD?

✏️ Q24: You tag 30 fish and re-measure each one every summer for five years. Write the lmer() formula for growth.


Section 10 · A treatment blocked by stream

These data are simulated. 3 streams; in each a reference reach, a crack willow reach, and a reach where willow was removed. 15 samples per reach. The truth is known: willow cuts insect numbers by 30%.

Written for you in the skeleton. Run it and look at the plot.

# ---- 10 A treatment blocked by stream --------------------
w_df <- read_csv("data/willow_streams_simulated.csv") %>%
  mutate(
    reach = factor(reach, levels = c("reference", "willow", "removed")),
    stream = factor(stream),
    log_insects = log(insects)
  )

w_means <- w_df %>%
  group_by(stream, reach) %>%
  summarise(log_insects = mean(log_insects), .groups = "drop")

ggplot(w_df, aes(x = reach, y = log_insects)) +
  geom_point() +
  geom_line(data = w_means, aes(group = stream)) +
  facet_wrap(~ stream)

✏️ Q25: What was the treatment applied to: a sample, a reach or a stream? How many of each kind are there?

▶ Type this yourself: the wrong way and the right way:

w_naive <- lm(log_insects ~ reach, data = w_df)
w_mixed <- lmer(log_insects ~ reach + (1 | stream) + (1 | stream:reach),
                data = w_df,
                control = lmerControl(calc.derivs = FALSE))

anova(w_naive)
anova(w_mixed)

✏️ Q26: Denominator df and p for reach in each. Why is (1 | stream:reach) the urchin (1 | patch) under another name?

✏️ Q27: The effect was real and the mixed model gave p ≈ 0.10. A lab-mate suggests 30 samples per reach next year instead of 15. Is that the right fix? What would you do instead?

💡 Key idea: before fitting anything, ask what the treatment was applied to and count those. That number, not the number of rows, is your replication.


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.