# From GLM coefficients to predicted values in R
# https://tidyecology.com/posts/predicting-glm-response-scale/
#
# 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

## ---- data ----
library(MASS)
library(ggplot2)

set.seed(53)
n      <- 200
canopy <- runif(n, 0.05, 0.95)        # canopy openness, the focal predictor
elev_z <- rnorm(n)                    # standardised elevation, a covariate
mu     <- exp(1.0 + 2.2 * canopy - 0.5 * elev_z)
count  <- rnbinom(n, size = 2, mu = mu)
dat    <- data.frame(count, canopy, elev_z)

m <- glm.nb(count ~ canopy + elev_z, data = dat)
round(coef(m), 3)

## ---- setup ----
ink<-"#16241d"; body<-"#2c3a31"; forest<-"#275139"; gold<-"#c9b458"
paper<-"#f5f4ee"; line<-"#dad9ca"; faint<-"#5d6b61"
theme_te <- function(){
  theme_minimal(base_size = 12) +
  theme(plot.background=element_rect(fill=paper,colour=NA),
        panel.background=element_rect(fill=paper,colour=NA),
        panel.grid.minor=element_blank(),
        panel.grid.major=element_line(colour=line,linewidth=.3),
        axis.title=element_text(colour=ink), axis.text=element_text(colour=faint),
        plot.title=element_text(colour=ink,size=12,face="bold"),
        strip.text=element_text(colour=ink,face="bold"),
        legend.position="bottom", legend.title=element_text(colour=ink),
        legend.text=element_text(colour=body))
}
crit <- qnorm(0.975)

## ---- predict-grid ----
grid <- data.frame(canopy = seq(0.05, 0.95, length.out = 100), elev_z = 0)
pl   <- predict(m, newdata = grid, type = "link", se.fit = TRUE)

grid$mu <- exp(pl$fit)                          # predicted mean count
grid$lo <- exp(pl$fit - crit * pl$se.fit)       # lower 95% limit
grid$hi <- exp(pl$fit + crit * pl$se.fit)       # upper 95% limit
head(round(grid, 2), 3)

## ---- fig-link-response ----
two <- rbind(
  data.frame(canopy=grid$canopy, fit=pl$fit, lo=pl$fit-crit*pl$se.fit,
             hi=pl$fit+crit*pl$se.fit, scale="link scale: log(mean count)"),
  data.frame(canopy=grid$canopy, fit=grid$mu, lo=grid$lo, hi=grid$hi,
             scale="response scale: mean count"))
two$scale <- factor(two$scale, levels=unique(two$scale))
ggplot(two, aes(canopy, fit)) +
  geom_ribbon(aes(ymin=lo, ymax=hi), fill=forest, alpha=.22) +
  geom_line(colour=forest, linewidth=.9) +
  facet_wrap(~scale, scales="free_y") +
  labs(x="canopy openness", y=NULL) +
  theme_te()

## ---- logistic ----
set.seed(206)
nb_   <- 180
moist <- runif(nb_, 0, 1)
occ   <- rbinom(nb_, 1, plogis(-2.5 + 6.0 * moist))
ml    <- glm(occ ~ moist, family = binomial)

gl  <- data.frame(moist = seq(0, 1, length.out = 100))
plk <- predict(ml, gl, type = "link",     se.fit = TRUE)
prr <- predict(ml, gl, type = "response", se.fit = TRUE)
gl$p   <- plogis(plk$fit)
gl$loc <- plogis(plk$fit - crit * plk$se.fit)   # correct: link CI, then plogis
gl$hic <- plogis(plk$fit + crit * plk$se.fit)
gl$lon <- prr$fit - crit * prr$se.fit           # naive: symmetric on response
gl$hin <- prr$fit + crit * prr$se.fit
c(naive_points_above_1 = sum(gl$hin > 1), max_naive_upper = round(max(gl$hin), 3))

## ---- fig-boundary ----
bandb <- rbind(
  data.frame(moist=gl$moist, lo=gl$loc, hi=gl$hic, kind="link-scale CI, then plogis() (correct)"),
  data.frame(moist=gl$moist, lo=gl$lon, hi=gl$hin, kind="response-scale SE, symmetric (naive)"))
ggplot() +
  geom_hline(yintercept=c(0,1), colour=faint, linewidth=.4, linetype="dotted") +
  geom_point(data=data.frame(moist,occ), aes(moist, occ), colour=faint, alpha=.3, size=1.1) +
  geom_ribbon(data=bandb, aes(moist, ymin=lo, ymax=hi, fill=kind), alpha=.20) +
  geom_line(data=bandb, aes(moist, hi, colour=kind), linewidth=.6) +
  geom_line(data=bandb, aes(moist, lo, colour=kind), linewidth=.6) +
  geom_line(data=gl, aes(moist, p), colour=ink, linewidth=.9) +
  scale_fill_manual(values=c(forest, gold)) +
  scale_colour_manual(values=c(forest, gold)) +
  coord_cartesian(ylim=c(-0.08, 1.08)) +
  labs(x="soil moisture", y="probability of occurrence", fill=NULL, colour=NULL) +
  theme_te()

## ---- fig-conditioning ----
elev_levels <- unname(quantile(dat$elev_z, c(0.1, 0.5, 0.9)))
elev_lab    <- c("low elevation","median","high elevation")
cond <- do.call(rbind, lapply(seq_along(elev_levels), function(k){
  g <- data.frame(canopy = seq(0.05, 0.95, length.out = 100), elev_z = elev_levels[k])
  p <- predict(m, newdata = g, type = "link", se.fit = TRUE)
  data.frame(canopy=g$canopy, elev_set=elev_lab[k], mu=exp(p$fit),
             lo=exp(p$fit-crit*p$se.fit), hi=exp(p$fit+crit*p$se.fit))
}))
cond$elev_set <- factor(cond$elev_set, levels=elev_lab)
ggplot(cond, aes(canopy, mu, colour=elev_set, fill=elev_set)) +
  geom_ribbon(aes(ymin=lo, ymax=hi), alpha=.16, colour=NA) +
  geom_line(linewidth=.9) +
  scale_colour_manual(values=c(forest, gold, "#b5534e")) +
  scale_fill_manual(values=c(forest, gold, "#b5534e")) +
  labs(x="canopy openness", y="predicted mean count",
       colour="elevation held at", fill="elevation held at") +
  theme_te()

## ---- new-sites ----
dat$elev_m <- 900 + 250 * dat$elev_z                # elevation in metres behind elev_z
stopifnot(isTRUE(all.equal(dat$elev_z, (dat$elev_m - 900) / 250)))

set.seed(530)
new_sites <- data.frame(canopy = runif(25, 0.05, 0.95), elev_m = runif(25, 1150, 1400))
truth <- mean(exp(1.0 + 2.2 * new_sites$canopy - 0.5 * (new_sites$elev_m - 900) / 250))

z_own <- as.numeric(scale(new_sites$elev_m))        # the new plots' own mean and SD
z_fit <- (new_sites$elev_m - 900) / 250             # the constants the model was fitted with
p_own <- predict(m, data.frame(canopy = new_sites$canopy, elev_z = z_own), type = "response")
p_fit <- predict(m, data.frame(canopy = new_sites$canopy, elev_z = z_fit), type = "response")

m_sc  <- glm.nb(count ~ canopy + scale(elev_m), data = dat)   # scale() in the formula
p_in  <- predict(m_sc, newdata = new_sites, type = "response")
sc_call <- attr(terms(m_sc), "predvars")[[4]]
sc_call
stopifnot(isTRUE(all.equal(unname(p_in), unname(p_fit))), mean(p_own) > mean(p_fit), coef(m)[["elev_z"]] < 0,
          isTRUE(all.equal(as.numeric(logLik(m_sc)), as.numeric(logLik(m)))),
          isTRUE(all.equal(coef(m_sc)[[3]], coef(m)[["elev_z"]] * sc_call$scale / 250)),
          isTRUE(all.equal(c(sc_call$center, sc_call$scale), c(mean(dat$elev_m), sd(dat$elev_m)))))
round(c(true_mean = truth, own_scale = mean(p_own), fitted_scale = mean(p_fit),
        scale_in_formula = mean(p_in)), 2)

## ---- fp-guard-1 ----
stopifnot(max(abs(p_in - p_fit)) / max(abs(p_fit)) < 1e-10)

## ---- uniform-shift ----
up <- dat$elev_m + 200                                  # every original plot 200 m higher
pred_at <- function(z) predict(m, data.frame(canopy = dat$canopy, elev_z = z), type = "response")
own_now <- pred_at(as.numeric(scale(dat$elev_m)))       # standardised on themselves
own_up  <- pred_at(as.numeric(scale(up)))
fit_up  <- pred_at((up - 900) / 250)                    # the fitted constants
round(c(own_scale_change = max(abs(own_up - own_now)),
        fitted_scale_change = mean(fit_up) - mean(fitted(m))), 3)

## ---- fp-guard-2 ----
stopifnot(max(abs(own_up - own_now)) / max(abs(own_now)) < 1e-10)

## ---- exp-coef ----
round(exp(cbind(estimate = coef(m), confint.default(m))), 2)

## ---- multiplicative ----
g2 <- data.frame(canopy = c(0.3, 0.4, 0.7, 0.8), elev_z = 0)
p2 <- predict(m, newdata = g2, type = "response")
c(ratio_0.3_to_0.4 = unname(round(p2[2]/p2[1], 3)),
  ratio_0.7_to_0.8 = unname(round(p2[4]/p2[3], 3)),
  jump_0.3_to_0.4  = unname(round(p2[2]-p2[1], 2)),
  jump_0.7_to_0.8  = unname(round(p2[4]-p2[3], 2)))
