# Random slopes in mixed models with nlme
# https://tidyecology.com/posts/random-slopes-mixed-models/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-15

## ---- simulate ----
library(nlme)

set.seed(20)
nsite <- 12
nrep  <- 8
sites <- factor(sprintf("S%02d", 1:nsite))

sd_int <- 3.0; sd_slope <- 1.3; rho <- -0.45; sd_resid <- 1.6
Sigma <- matrix(c(sd_int^2,            rho*sd_int*sd_slope,
                  rho*sd_int*sd_slope, sd_slope^2), 2, 2)
z   <- matrix(rnorm(nsite * 2), nsite, 2) %*% chol(Sigma)
b0i <- 10 + z[, 1]   # site intercepts
b1i <- 2  + z[, 2]   # site slopes (population slope = 2)

dat <- do.call(rbind, lapply(1:nsite, function(i) {
  x <- round(runif(nrep, -2, 2), 2)
  y <- b0i[i] + b1i[i] * x + rnorm(nrep, 0, sd_resid)
  data.frame(site = sites[i], nutrient = x, growth = y)
}))

c(rows = nrow(dat), sites = nlevels(dat$site))

## ---- fig-spaghetti ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))

m_slope <- lme(growth ~ nutrient, random = ~ nutrient | site,
               data = dat, method = "REML")

grid <- expand.grid(nutrient = c(-2, 2), site = levels(dat$site))
grid$fit <- predict(m_slope, newdata = grid)
pop <- data.frame(nutrient = c(-2, 2))
pop$fit <- fixef(m_slope)[1] + fixef(m_slope)[2] * pop$nutrient

ggplot(dat, aes(nutrient, growth)) +
  geom_line(data = grid, aes(y = fit, group = site),
            colour = "#275139", alpha = 0.45, linewidth = 0.5) +
  geom_point(colour = "#5d6b61", size = 1.1, alpha = 0.7) +
  geom_line(data = pop, aes(y = fit), colour = "#c9b458", linewidth = 1.6) +
  labs(x = "Nutrient (centred)", y = "Growth") +
  theme_minimal(base_size = 12) + te_canvas

## ---- fit-compare ----
m_int   <- lme(growth ~ nutrient, random = ~ 1        | site,
               data = dat, method = "REML")
m_slope <- lme(growth ~ nutrient, random = ~ nutrient | site,
               data = dat, method = "REML")

AIC(m_int, m_slope)
anova(m_int, m_slope)

## ---- varcorr ----
VarCorr(m_slope)

## ---- se-cost ----
rbind(
  intercept_only = summary(m_int)$tTable["nutrient",   c("Value", "Std.Error")],
  random_slopes  = summary(m_slope)$tTable["nutrient", c("Value", "Std.Error")]
)

## ---- fig-shrinkage ----
ols  <- sapply(levels(dat$site),
               function(s) coef(lm(growth ~ nutrient, dat[dat$site == s, ]))["nutrient"])
blup <- coef(m_slope)[, "nutrient"]
pop_slope <- fixef(m_slope)["nutrient"]

sh <- data.frame(site = levels(dat$site),
                 ols = as.numeric(ols), blup = as.numeric(blup))
sh <- sh[order(sh$ols), ]
sh$site <- factor(sh$site, levels = sh$site)

c(pop_slope = round(pop_slope, 3),
  sd_ols = round(sd(sh$ols), 3), sd_blup = round(sd(sh$blup), 3))

ggplot(sh) +
  geom_hline(yintercept = pop_slope, colour = "#c9b458",
             linetype = "dashed", linewidth = 0.7) +
  geom_segment(aes(x = site, xend = site, y = ols, yend = blup),
               colour = "#dad9ca", linewidth = 1.2) +
  geom_point(aes(site, ols),  colour = "#b5534e", size = 2.3) +
  geom_point(aes(site, blup), colour = "#275139", size = 2.3) +
  labs(x = "Site (ordered by per-site OLS slope)", y = "Nutrient slope") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
