# Quantile regression in ecology: beyond the mean
# https://tidyecology.com/posts/quantile-regression-in-ecology/
#
# 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

## ---- setup ----
library(ggplot2); library(dplyr); library(tidyr)
ink <- "#16241d"; body <- "#2c3a31"; forest <- "#275139"
sage <- "#93a87f"; paper <- "#f5f4ee"; line <- "#dad9ca"
faint <- "#5d6b61"; warm <- "#b5534e"; gold <- "#c9b458"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(plot.background = element_rect(fill = paper, colour = NA),
          panel.background = element_rect(fill = paper, colour = NA),
          panel.grid.major = element_line(colour = line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          axis.text = element_text(colour = faint),
          axis.title = element_text(colour = body),
          plot.subtitle = element_text(colour = "#46604a"),
          legend.position = "top", legend.key = element_blank(),
          legend.text = element_text(colour = body),
          legend.title = element_text(colour = body))
}

## ---- data ----
set.seed(4202)
n   <- 200
x   <- runif(n, 0, 10)                 # resource gradient
sdx <- 0.5 + 0.35 * x                  # spread grows with the gradient
y   <- 2 + 0.6 * x + rnorm(n, 0, sdx)  # true conditional-mean slope 0.6

ols <- lm(y ~ x)
coef(ols)[2]

## ---- spread ----
lo <- x < quantile(x, 1/3); hi <- x > quantile(x, 2/3)
r_ols_slope <- round(unname(coef(ols)[2]), 3)
r_ols_se    <- round(summary(ols)$coefficients[2, 2], 3)
r_sd_lo <- round(sd(y[lo]), 2); r_sd_hi <- round(sd(y[hi]), 2)

## ---- qr ----
rho <- function(u, tau) u * (tau - (u < 0))
qrfit <- function(x, y, tau) {
  obj <- function(b) sum(rho(y - (b[1] + b[2] * x), tau))
  optim(unname(coef(lm(y ~ x))), obj, method = "Nelder-Mead",
        control = list(reltol = 1e-12, maxit = 8000))$par
}
taus <- c(0.1, 0.5, 0.9)
qest <- t(sapply(taus, function(t) qrfit(x, y, t)))
rownames(qest) <- taus; colnames(qest) <- c("intercept", "slope")
round(qest, 3)

## ---- qr-scalars ----
r_q <- round(qest[, "slope"], 3)
r_qth <- round(0.6 + 0.35 * qnorm(taus), 3)
fb <- sapply(seq_along(taus), function(i) mean(y < qest[i, 1] + qest[i, 2] * x))
r_fb <- round(fb, 2)

## ---- fig-quantile-fan ----
xg <- seq(0, 10, length.out = 50)
qdf <- do.call(rbind, lapply(seq_along(taus), function(i)
  data.frame(x = xg, y = qest[i, 1] + qest[i, 2] * xg, tau = factor(taus[i]))))
ggplot() +
  geom_point(aes(x, y), colour = sage, alpha = 0.6, size = 1.5) +
  geom_abline(intercept = coef(ols)[1], slope = coef(ols)[2],
              colour = faint, linetype = "dashed", linewidth = 0.9) +
  geom_line(data = qdf, aes(x, y, colour = tau), linewidth = 1) +
  scale_colour_manual(values = c("0.1" = gold, "0.5" = forest, "0.9" = warm),
                      name = "quantile") +
  labs(x = "resource gradient", y = "response",
       subtitle = "dashed = least squares (mean); coloured = quantile fits") +
  theme_te()

## ---- outlier ----
yo <- y; io <- which.max(x); yo[io] <- yo[io] + 40
c(ols = unname(coef(lm(yo ~ x))[2]),
  median_qr = qrfit(x, yo, 0.5)[2])

## ---- outlier-scalars ----
r_ols_out <- round(unname(coef(lm(yo ~ x))[2]), 3)
r_med_out <- round(qrfit(x, yo, 0.5)[2], 3)

## ---- fig-check-loss ----
u <- seq(-3, 3, length.out = 300)
ldf <- do.call(rbind, lapply(taus, function(t)
  data.frame(u = u, loss = rho(u, t), tau = factor(t))))
ggplot(ldf, aes(u, loss, colour = tau)) +
  geom_vline(xintercept = 0, colour = line) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("0.1" = gold, "0.5" = forest, "0.9" = warm),
                      name = "quantile") +
  labs(x = "residual", y = "check loss",
       subtitle = "asymmetric absolute loss; the tilt selects the quantile") +
  theme_te()
