# Akaike weights and evidence ratios
# https://tidyecology.com/posts/akaike-weights/
#
# 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-14

## ---- data ----
set.seed(202)
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)

## ---- allsubsets ----
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          # slopes + intercept + residual variance
  N <- nobs(m)
  AIC(m) + 2 * k * (k + 1) / (N - k - 1)
}

fits   <- lapply(forms, function(f) lm(as.formula(f), data = d))
scores <- vapply(fits, aicc, numeric(1))

## ---- weights ----
delta <- scores - min(scores)
relL  <- exp(-0.5 * delta)
w     <- relL / sum(relL)

tab <- data.frame(model = forms, dAICc = delta, weight = w)
tab <- tab[order(tab$dAICc), ]
head(tab, 4)

## ---- topnums ----
top      <- tab[1, ]
second   <- tab[2, ]
er_1_2   <- top$weight / second$weight
cum2     <- top$weight + second$weight

## ---- er ----
er_best_null <- top$weight / tab$weight[tab$model == "biomass ~ 1"]

## ---- wplus ----
importance <- vapply(vars, function(v) {
  in_model <- vapply(subsets, function(s) v %in% s, logical(1))
  sum(w[in_model])
}, numeric(1))
importance

## ---- wplusnums ----
imp_moist  <- importance["moisture"]
imp_nitro  <- importance["nitrogen"]
imp_aspect <- importance["aspect"]

# the least w+ any predictor can collect in this set: each model containing it
# has a partner without it (2 to 4 parameters) that it can beat only on fit
pen       <- function(k) 2 * k + 2 * k * (k + 1) / (n - k - 1)   # AICc penalty
step_max  <- max(pen(3:5) - pen(2:4))
wplus_min <- exp(-step_max / 2) / (1 + exp(-step_max / 2))

## ---- fig-importance ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
impdf <- data.frame(predictor = names(importance), wplus = as.numeric(importance))
impdf$predictor <- factor(impdf$predictor, levels = impdf$predictor[order(impdf$wplus)])

thumb_tab <- head(tab, 5)
thumb_tab$mod <- gsub("biomass ~ ", "", thumb_tab$model)
thumb_tab$mod <- factor(thumb_tab$mod, levels = rev(thumb_tab$mod))
p_thumb <- ggplot(thumb_tab, aes(weight, mod)) +
  geom_segment(aes(x = 0, xend = weight, yend = mod), colour = "#adbcd9") +
  geom_point(colour = "#4c72b0", size = 4) +
  scale_x_continuous(limits = c(0, NA), expand = expansion(mult = c(0, 0.08))) +
  labs(title = paste(strwrap("Akaike weight by candidate model", 46), collapse = "\n"),
       x = "Akaike weight", y = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(plot.title = element_text(size = 13, face = "bold"),
        plot.subtitle = element_text(size = 9.5),
        plot.margin = margin(8, 14, 8, 8))

ggplot(impdf, aes(wplus, predictor)) +
  geom_col(fill = "#4c72b0", width = 0.6) +
  geom_vline(xintercept = 0.5, linetype = "dashed", colour = "grey55") +
  scale_x_continuous(limits = c(0, 1), expand = expansion(mult = c(0, 0.02))) +
  labs(x = "summed Akaike weight (w+)", y = NULL) +
  theme_minimal(base_size = 12) + te_canvas

## ---- thumb ----
ggsave("thumbnail.png", p_thumb, width = 7.5, height = 5.4, dpi = 100,
       bg = "#f5f4ee")

## ---- fig-samplesize ----
weight_target <- function(N, seed = 202) {
  set.seed(seed)
  mo <- rnorm(N); ni <- rnorm(N); as <- rnorm(N)
  bm <- 2 + 1.0 * mo + 0.22 * ni + 0 * as + rnorm(N, 0, 1.6)
  dd <- data.frame(bm, mo, ni, as)
  vv <- c("mo", "ni", "as")
  ss <- unlist(lapply(0:3, function(k) combn(vv, k, simplify = FALSE)), recursive = FALSE)
  ff <- vapply(ss, function(s)
    if (length(s) == 0) "bm ~ 1" else paste("bm ~", paste(s, collapse = " + ")), character(1))
  sc <- vapply(lapply(ff, function(f) lm(as.formula(f), data = dd)), aicc, numeric(1))
  ww <- exp(-0.5 * (sc - min(sc))); ww <- ww / sum(ww)
  target <- vapply(ss, function(s) setequal(s, c("mo", "ni")), logical(1))
  sum(ww[target])
}
ns <- c(30, 55, 120, 400)
wn <- vapply(ns, weight_target, numeric(1))
ndf <- data.frame(n = ns, weight = wn)
ggplot(ndf, aes(n, weight)) +
  geom_line(colour = "#4c72b0") +
  geom_point(colour = "#4c72b0", size = 2) +
  scale_x_continuous(breaks = ns) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "number of plots", y = "weight on moisture + nitrogen model") +
  theme_minimal(base_size = 12) + te_canvas

## ---- nnums ----
w_small <- wn[1]
w_big   <- wn[length(wn)]
