# Model-averaged predictions
# https://tidyecology.com/posts/model-averaged-predictions/
#
# 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-11-16

## ---- setup ----
set.seed(303)
n  <- 55
moisture <- rnorm(n); nitrogen <- rnorm(n); aspect <- rnorm(n)
biomass  <- 2 + 1.0 * moisture + 0.22 * nitrogen + 0 * aspect + rnorm(n, 0, 1.6)
d <- data.frame(biomass, moisture, nitrogen, aspect)

vars    <- c("moisture", "nitrogen", "aspect")
subsets <- unlist(lapply(0:3, function(k) combn(vars, k, simplify = FALSE)), recursive = FALSE)
forms   <- vapply(subsets, function(s)
  if (length(s) == 0) "biomass ~ 1" else paste("biomass ~", paste(s, collapse = " + ")), character(1))
aicc <- function(m) { k <- length(coef(m)) + 1; N <- nobs(m); AIC(m) + 2 * k * (k + 1) / (N - k - 1) }

fits  <- lapply(forms, function(f) lm(as.formula(f), data = d))
w     <- exp(-0.5 * (vapply(fits, aicc, numeric(1)) - min(vapply(fits, aicc, numeric(1)))))
w     <- w / sum(w)

newplot  <- data.frame(moisture = 1, nitrogen = 1, aspect = 2)
true_mean <- 2 + 1.0 * 1 + 0.22 * 1 + 0 * 2

## ---- permodel ----
pred <- t(vapply(fits, function(m) {
  p <- predict(m, newplot, se.fit = TRUE)
  c(fit = as.numeric(p$fit), se = as.numeric(p$se.fit))
}, numeric(2)))
pred <- as.data.frame(pred)
pred$weight <- w
range_fit <- range(pred$fit)
range_sup <- range(pred$fit[pred$weight > 0.01])   # models with non-negligible weight

## ---- best ----
best_i  <- which.max(w)
pb      <- predict(fits[[best_i]], newplot, se.fit = TRUE)
tcrit   <- qt(0.975, fits[[best_i]]$df.residual)
best_lo <- as.numeric(pb$fit) - tcrit * pb$se.fit
best_hi <- as.numeric(pb$fit) + tcrit * pb$se.fit

## ---- averaged ----
y_avg  <- sum(w * pred$fit)
se_unc <- sum(w * sqrt(pred$se^2 + (pred$fit - y_avg)^2))
avg_lo <- y_avg - 1.96 * se_unc
avg_hi <- y_avg + 1.96 * se_unc

## ---- fig-spread ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
pd <- pred[order(pred$fit), ]
pd$rank <- seq_len(nrow(pd))
ggplot(pd, aes(fit, rank)) +
  geom_vline(xintercept = true_mean, linetype = "dashed", colour = "grey55") +
  geom_point(aes(size = weight), colour = "grey35", alpha = 0.8) +
  annotate("point", x = y_avg, y = max(pd$rank) + 1, colour = "#4c72b0", size = 3) +
  annotate("errorbar", xmin = avg_lo, xmax = avg_hi, y = max(pd$rank) + 1,
           orientation = "y", width = 0.4, colour = "#4c72b0") +
  scale_size(range = c(1.5, 6), guide = "none") +
  scale_y_continuous(breaks = NULL) +
  labs(x = "predicted log biomass at new plot", y = NULL,
       subtitle = "grey: candidate models (size = weight)\nblue: model-averaged with unconditional interval") +
  theme_minimal(base_size = 12) + te_canvas

## ---- coverage ----
cover_sim <- function(reps = 2000, seed = 3033) {
  set.seed(seed)
  cb <- wb <- ca <- wa <- 0
  np <- data.frame(moisture = 1, nitrogen = 1, aspect = 2)
  for (i in seq_len(reps)) {
    moisture <- rnorm(n); nitrogen <- rnorm(n); aspect <- rnorm(n)
    biomass  <- 2 + 1.0 * moisture + 0.22 * nitrogen + 0 * aspect + rnorm(n, 0, 1.6)
    dd <- data.frame(biomass, moisture, nitrogen, aspect)
    fj <- lapply(forms, function(f) lm(as.formula(f), data = dd))
    sj <- vapply(fj, aicc, numeric(1)); wj <- exp(-0.5 * (sj - min(sj))); wj <- wj / sum(wj)
    fj_fit <- vapply(fj, function(m) as.numeric(predict(m, np)), numeric(1))
    fj_se  <- vapply(fj, function(m) as.numeric(predict(m, np, se.fit = TRUE)$se.fit), numeric(1))
    bi <- which.max(wj); tb <- qt(0.975, fj[[bi]]$df.residual)
    lo <- fj_fit[bi] - tb * fj_se[bi]; hi <- fj_fit[bi] + tb * fj_se[bi]
    cb <- cb + (true_mean >= lo && true_mean <= hi); wb <- wb + (hi - lo)
    ya <- sum(wj * fj_fit); su <- sum(wj * sqrt(fj_se^2 + (fj_fit - ya)^2))
    la <- ya - 1.96 * su; ha <- ya + 1.96 * su
    ca <- ca + (true_mean >= la && true_mean <= ha); wa <- wa + (ha - la)
  }
  c(cover_best = cb / reps, width_best = wb / reps,
    cover_avg = ca / reps, width_avg = wa / reps)
}
cov <- cover_sim()
cov

## ---- covnums ----
cb <- cov["cover_best"]; ca <- cov["cover_avg"]
wbst <- cov["width_best"]; wavg <- cov["width_avg"]

## ---- fig-cover ----
covdf <- data.frame(method = c("best model", "model-averaged"),
                    coverage = c(cb, ca) * 100)
ggplot(covdf, aes(method, coverage, fill = method)) +
  geom_col(width = 0.6) +
  geom_hline(yintercept = 95, linetype = "dashed", colour = "grey40") +
  scale_fill_manual(values = c("best model" = "grey55", "model-averaged" = "#4c72b0"),
                    guide = "none") +
  coord_cartesian(ylim = c(80, 100)) +
  labs(x = NULL, y = "coverage of 95% interval (%)") +
  theme_minimal(base_size = 12) + te_canvas
