# Model-averaged coefficients: a caution
# https://tidyecology.com/posts/model-averaged-coefficients/
#
# 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-04

## ---- gen ----
gen_data <- function(rho, N = 80, seed = 505) {
  if (!is.na(seed)) set.seed(seed)          # seed = NA gives a fresh draw each call
  z1 <- rnorm(N); z2 <- rnorm(N)
  moisture <- z1
  carbon   <- rho * z1 + sqrt(1 - rho^2) * z2   # correlation with moisture = rho
  aspect   <- rnorm(N)
  biomass  <- 2 + 1.0 * moisture + 1.4 * carbon + 0 * aspect + rnorm(N, 0, 2.0)
  data.frame(biomass, moisture, carbon, aspect)
}

## ---- oneset ----
d09 <- gen_data(rho = 0.9)
b_partial  <- coef(lm(biomass ~ moisture + carbon, data = d09))["moisture"]
b_marginal <- coef(lm(biomass ~ moisture, data = d09))["moisture"]
c(partial = as.numeric(b_partial), marginal = as.numeric(b_marginal))

## ---- avgcoef ----
aicc <- function(m) { k <- length(coef(m)) + 1; N <- nobs(m); AIC(m) + 2 * k * (k + 1) / (N - k - 1) }
vars <- c("moisture", "carbon", "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))

avg_moisture <- function(d) {
  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)
  b <- vapply(fits, function(m) { cc <- coef(m); if ("moisture" %in% names(cc)) cc["moisture"] else 0 }, numeric(1))
  in_m <- vapply(subsets, function(s) "moisture" %in% s, logical(1))
  c(avg_coef = sum(w * b), wplus = sum(w[in_m]))
}
avg_moisture(d09)

## ---- sweep ----
one_rep <- function(rho) {
  d <- gen_data(rho, seed = NA)
  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)
  in_m <- vapply(subsets, function(s) "moisture" %in% s, logical(1))
  bm <- vapply(fits, function(m) { cc <- coef(m); if ("moisture" %in% names(cc)) cc["moisture"] else 0 }, numeric(1))
  x0 <- data.frame(moisture = 1, carbon = 1, aspect = 0)
  c(partial  = as.numeric(coef(fits[[which(forms == "biomass ~ moisture + carbon")]])["moisture"]),
    marginal = as.numeric(coef(fits[[which(forms == "biomass ~ moisture")]])["moisture"]),
    averaged = sum(w * bm),
    wplus    = sum(w[in_m]),
    pred     = sum(w * vapply(fits, function(m) as.numeric(predict(m, x0)), numeric(1))))
}

rhos <- c(0, 0.3, 0.6, 0.9)
set.seed(505)
sweep <- t(vapply(rhos, function(r) {
  colMeans(t(vapply(seq_len(300), function(i) one_rep(r), numeric(5))))
}, numeric(5)))
sweep <- data.frame(rho = rhos, sweep)
round(sweep, 3)

## ---- sweepnums ----
lo <- sweep[sweep$rho == 0, ]
hi <- sweep[sweep$rho == 0.9, ]

## ---- fig-coef ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
long <- data.frame(
  rho = rep(sweep$rho, 3),
  estimate = c(sweep$partial, sweep$marginal, sweep$averaged),
  kind = rep(c("partial (with carbon)", "marginal (moisture only)", "model-averaged"), each = nrow(sweep)))
ggplot(long, aes(rho, estimate, colour = kind)) +
  geom_hline(yintercept = 1.0, linetype = "dashed", colour = "grey55") +
  geom_line(linewidth = 0.8) + geom_point(size = 2) +
  scale_colour_manual(values = c("partial (with carbon)" = "#4c72b0",
                                 "marginal (moisture only)" = "#c44e52",
                                 "model-averaged" = "#55a868"), name = NULL) +
  labs(x = "correlation between moisture and carbon", y = "estimated moisture coefficient") +
  theme_minimal(base_size = 12) + te_canvas + theme(legend.position = "top")

## ---- fig-pred ----
ggplot(sweep, aes(rho, pred)) +
  geom_hline(yintercept = 4.4, linetype = "dashed", colour = "grey55") +
  geom_line(colour = "#4c72b0", linewidth = 0.8) + geom_point(colour = "#4c72b0", size = 2) +
  coord_cartesian(ylim = c(3.8, 5.0)) +
  labs(x = "correlation between moisture and carbon", y = "model-averaged prediction at site") +
  theme_minimal(base_size = 12) + te_canvas

## ---- ca-rho ----
with_c <- vapply(subsets, function(s) "carbon" %in% s, logical(1))
ca_avg <- function(d, term) {
  fits <- lapply(forms, function(f) lm(as.formula(f), data = d))
  a <- vapply(fits, aicc, numeric(1)); dl <- a - min(a)
  b <- vapply(fits, function(m) { cc <- coef(m); if (term %in% names(cc)) cc[[term]] else 0 }, numeric(1))
  has <- vapply(subsets, function(s) term %in% s, logical(1))
  out <- c()
  for (keep in list(rep(TRUE, 8), dl < 2)) {
    w <- exp(-dl / 2) * keep; w <- w / sum(w); wp <- sum(w[has])
    out <- c(out, sum(w * b), if (wp > 0) sum(w * b) / wp else NA, wp, sum(w[has & !with_c]) / wp)
  }
  names(out) <- paste(rep(c("all", "top"), each = 4), c("full", "cond", "wplus", "nocarbon"), sep = "_")
  c(out, ols = b[8], ols_se = coef(summary(fits[[8]]))[term, 2])
}
ca_d09 <- ca_avg(d09, "moisture")
stopifnot(all.equal(ca_d09[["all_full"]], avg_moisture(d09)[["avg_coef"]]),
          all.equal(ca_d09[["all_full"]], ca_d09[["all_wplus"]] * ca_d09[["all_cond"]]),
          all.equal(ca_d09[["top_full"]], ca_d09[["top_wplus"]] * ca_d09[["top_cond"]]))
set.seed(353)
ca_runs <- lapply(rhos, function(r) t(replicate(400, ca_avg(gen_data(r, seed = NA), "moisture"))))
ca_rho <- data.frame(rho = rhos, t(vapply(ca_runs, colMeans, numeric(10), na.rm = TRUE)))
round(ca_rho[, c("rho", "all_full", "all_cond", "top_full", "top_cond", "ols")], 3)
ca_gap_se <- sd(ca_runs[[4]][, "all_cond"] - ca_runs[[4]][, "all_full"]) / sqrt(400)

## ---- ca-weak ----
ca_b <- c(0, 0.15, 0.25, 0.4)
set.seed(354)
ca_weak <- lapply(ca_b, function(bw) t(replicate(1000, {
  d <- gen_data(0, seed = NA); d$biomass <- d$biomass + bw * d$aspect
  ca_avg(d, "aspect") })))
ca_tab <- data.frame(b = ca_b, t(vapply(seq_along(ca_b), function(i) {
  r <- ca_weak[[i]]; bw <- ca_b[i]; kept <- !is.na(r[, "top_cond"])
  rmse <- function(x) sqrt(mean((x - bw)^2))
  rmse_se <- function(x) sd((x - bw)^2) / sqrt(length(x)) / (2 * rmse(x))
  c(top_cond = mean(r[kept, "top_cond"]), top_full = mean(r[, "top_full"]),
    all_cond = mean(r[, "all_cond"]), ols = mean(r[, "ols"]), ols_kept = mean(r[kept, "ols"]),
    rmse_cond = rmse(r[kept, "top_cond"]), rmse_full = rmse(r[, "top_full"]), rmse_ols = rmse(r[, "ols"]),
    rmse_ols_kept = rmse(r[kept, "ols"]), rmse_full_kept = rmse(r[kept, "top_full"]), absent = mean(!kept), se_cond = sd(r[kept, "top_cond"]) / sqrt(sum(kept)),
    se_full = sd(r[, "top_full"]) / sqrt(nrow(r)), ols_se = mean(r[, "ols_se"]),
    rmse_se = max(rmse_se(r[kept, "top_cond"]), rmse_se(r[, "top_full"])))
}, numeric(15))))
round(ca_tab[, c("b", "top_cond", "top_full", "all_cond", "ols", "absent", "rmse_cond", "rmse_full", "rmse_ols")], 3)
ca_null <- ca_weak[[1]]
ca_pc <- function(col, i) 100 * (ca_tab[i, col] / ca_b[i] - 1)
