# Model selection with AIC in R for ecology
# https://tidyecology.com/posts/model-selection-aic/
#
# 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-07

## ---- data ----
library(MASS)
library(mgcv)
library(dplyr)
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))

set.seed(48)
n   <- 180
env <- runif(n, 0, 10)
b0  <- -0.23; b1 <- 1.20; b2 <- -0.12     # peak at env = 5
mu  <- exp(b0 + b1 * env + b2 * env^2)
y   <- rnbinom(n, mu = mu, size = 2.0)
dat <- data.frame(env, y)

c(peak = -b1 / (2 * b2), mean_count = mean(y), max = max(y), zeros = sum(y == 0))

## ---- fit ----
m0 <- glm.nb(y ~ 1, dat)
m1 <- glm.nb(y ~ env, dat)
m2 <- glm.nb(y ~ env + I(env^2), dat)
m3 <- gam(y ~ s(env), family = nb(), data = dat, method = "REML")

## ---- aic-table ----
aic  <- c(null = AIC(m0), linear = AIC(m1),
          quadratic = AIC(m2), smooth = AIC(m3))
dAIC <- aic - min(aic)
w    <- exp(-dAIC / 2); w <- w / sum(w)

tab <- data.frame(
  model    = names(aic),
  k        = c(2, 3, 4, round(attr(logLik(m3), "df"), 1)),
  AIC      = round(aic, 2),
  dAIC     = round(dAIC, 2),
  weight   = round(w, 3),
  ev_ratio = round(max(w) / w, 1))
tab[order(tab$AIC), ]

## ---- fig-curves ----
te_forest <- "#275139"; te_gold <- "#c9b458"; te_red <- "#b5534e"
te_sage   <- "#93a87f"; te_ink  <- "#16241d"; te_line <- "#dad9ca"; te_high <- "#1d5b4e"
base_t <- theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(colour = te_line, linewidth = .3),
        plot.title = element_text(face = "bold", colour = te_ink),
        plot.subtitle = element_text(colour = "#5d6b61"),
        axis.title = element_text(colour = te_ink), legend.position = "top")

grid <- data.frame(env = seq(0, 10, length.out = 200))
pr   <- sapply(list(m0, m1, m2, m3),
               function(m) predict(m, grid, type = "response"))
colnames(pr) <- names(aic)
fitdf <- bind_rows(lapply(names(aic), function(nm)
  data.frame(env = grid$env, fit = pr[, nm], model = nm)))
fitdf$model <- factor(fitdf$model,
                      levels = c("null", "linear", "quadratic", "smooth"))

ggplot() +
  geom_point(data = dat, aes(env, y), colour = te_sage, alpha = .55, size = 1.6) +
  geom_line(data = fitdf, aes(env, fit, colour = model, linetype = model), linewidth = 1) +
  scale_colour_manual(values = c(null = "grey55", linear = te_gold,
                                 quadratic = te_forest, smooth = te_red)) +
  scale_linetype_manual(values = c(null = "dotted", linear = "dashed",
                                   quadratic = "solid", smooth = "solid")) +
  labs(title = "One dataset, four candidate models",
       x = "Environmental gradient", y = "Abundance (count)",
       colour = NULL, linetype = NULL) + base_t

## ---- lrt ----
a <- anova(m0, m1, m2, test = "Chisq")
cat("null -> linear: LR =", round(a$`LR stat.`[2], 2),
    " p =", round(a$`Pr(Chi)`[2], 3), "\n")
cat("linear -> quadratic: LR =", round(a$`LR stat.`[3], 1),
    " p =", signif(a$`Pr(Chi)`[3], 2), "\n")

## ---- aicc ----
extra <- function(k, N) 2 * k * (k + 1) / (N - k - 1)
cat("extra penalty for k = 4 at n = 180:", round(extra(4, 180), 2), "\n")
cat("extra penalty for k = 4 at n = 24: ", round(extra(4, 24), 2), "\n")
cat("ratio of the two penalties:", round(extra(4, 24) / extra(4, 180), 1), "\n")

## ---- aicc-subset ----
AICc <- function(mod, N) {
  ll <- as.numeric(logLik(mod)); kk <- attr(logLik(mod), "df")
  -2 * ll + 2 * kk + 2 * kk * (kk + 1) / (N - kk - 1)
}
set.seed(7); idx <- sample(n, 24); ds <- dat[idx, ]
s0 <- glm.nb(y ~ 1, ds); s2 <- glm.nb(y ~ env + I(env^2), ds)
cat("quadratic minus null, delta AIC: ",  round(AIC(s2) - AIC(s0), 2), "\n")
cat("quadratic minus null, delta AICc:", round(AICc(s2, 24) - AICc(s0, 24), 2), "\n")

## ---- bic ----
c(null = BIC(m0), linear = BIC(m1), quadratic = BIC(m2))

## ---- pois-vs-nb ----
mp <- glm(y ~ env + I(env^2), poisson, data = dat)
cat("Poisson minus NB, delta AIC:", round(AIC(mp) - AIC(m2), 0), "\n")
cat("Poisson Pearson dispersion: ",
    round(sum(residuals(mp, "pearson")^2) / df.residual(mp), 2), "\n")
cat("negative binomial theta:    ", round(m2$theta, 2), "\n")

## ---- model-average ----
avg <- as.numeric(pr %*% w)             # Akaike-weighted average prediction
at5 <- which.min(abs(grid$env - 5))
cat("model-averaged mean at env = 5:", round(avg[at5], 2), "\n")
cat("quadratic-only mean at env = 5:", round(pr[at5, "quadratic"], 2), "\n")

## ---- fig-average ----
avgdf <- data.frame(env = grid$env, avg = avg)
faded <- fitdf %>% filter(model %in% c("quadratic", "smooth"))
ggplot() +
  geom_point(data = dat, aes(env, y), colour = te_sage, alpha = .4, size = 1.4) +
  geom_line(data = faded, aes(env, fit, group = model),
            colour = te_gold, linewidth = .7, alpha = .9) +
  geom_line(data = avgdf, aes(env, avg), colour = te_high, linewidth = 1.4) +
  annotate("text", x = 8.2, y = max(avg) * 0.97, label = "weighted average",
           colour = te_high, size = 3.4, hjust = 0) +
  annotate("text", x = 8.2, y = max(avg) * 0.80, label = "candidate models",
           colour = te_gold, size = 3.4, hjust = 0) +
  labs(title = "Model-averaged prediction (weighted by Akaike weights)",
       x = "Environmental gradient", y = "Predicted abundance") + base_t

## ---- fig-weights ----
lol <- tab[order(tab$AIC), ]
lol$model <- factor(lol$model, levels = rev(lol$model))
ggplot(lol, aes(dAIC, model)) +
  geom_segment(aes(x = 0, xend = dAIC, yend = model),
               colour = te_line, linewidth = 1.2) +
  geom_point(aes(size = weight), colour = te_forest) +
  geom_text(aes(label = sprintf("w = %.3f", weight)),
            hjust = -0.25, vjust = -0.7, size = 3.3, colour = te_ink) +
  scale_size(range = c(2.5, 9), guide = "none") +
  scale_x_continuous(expand = expansion(mult = c(.02, .18))) +
  labs(title = expression(paste(Delta, "AIC and Akaike weights")),
       x = expression(paste(Delta, "AIC (distance from best model)")),
       y = NULL) + base_t + theme(legend.position = "none")
