# Checking a quantile regression
# https://tidyecology.com/posts/checking-a-quantile-regression/
#
# 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))
}
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
}

## ---- crossing ----
set.seed(4205)
n <- 50
x <- runif(n, 0, 10)
y <- 3 + 0.15 * x + rnorm(n, 0, 1.1)     # near-flat slope, homoscedastic
taus <- c(0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95)
co <- t(sapply(taus, function(t) qrfit(x, y, t)))
xg <- seq(min(x), max(x), length.out = 200)
Q  <- sapply(seq_along(taus), function(i) co[i, 1] + co[i, 2] * xg)
viol <- apply(Q, 1, function(r) any(diff(r) < 0))     # any inversion across levels
sum(viol)

## ---- cross-scalars ----
r_nviol <- sum(viol)
r_xlo <- round(min(xg[viol]), 2); r_xhi <- round(max(xg[viol]), 2)
Qr <- t(apply(Q, 1, sort))
r_after <- sum(apply(Qr, 1, function(r) any(diff(r) < 0)))

## ---- rearrange ----
Qr <- t(apply(Q, 1, sort))                 # monotone rearrangement at each x
sum(apply(Qr, 1, function(r) any(diff(r) < 0)))

## ---- fig-crossing ----
raw <- data.frame(x = rep(xg, length(taus)), y = as.vector(Q),
                  tau = factor(rep(taus, each = length(xg))), panel = "as fitted (crossing)")
rea <- data.frame(x = rep(xg, length(taus)), y = as.vector(Qr),
                  tau = factor(rep(taus, each = length(xg))), panel = "after rearrangement")
both <- rbind(raw, rea); both$panel <- factor(both$panel, levels = unique(both$panel))
ggplot(both, aes(x, y, colour = tau, group = tau)) +
  geom_line(linewidth = 0.8) + facet_wrap(~panel) +
  scale_colour_manual(values = colorRampPalette(c(gold, forest, warm))(length(taus)),
                      name = "quantile") +
  labs(x = "resource gradient", y = "response") +
  theme_te() + theme(legend.position = "right")

## ---- calibration ----
calib <- function(seed, curved, t = 0.9) {
  set.seed(seed)
  N <- 800; xx <- runif(N, 0, 10)
  mu <- if (curved) 6 * (1 - exp(-0.35 * xx)) else 1 + 0.4 * xx
  yy <- mu + rnorm(N, 0, 1)
  tr <- 1:400; te <- 401:N
  b  <- qrfit(xx[tr], yy[tr], t)
  pr <- function(idx) b[1] + b[2] * xx[idx]
  tc <- cut(xx[te], quantile(xx[te], c(0, 1/3, 2/3, 1)), include.lowest = TRUE,
            labels = c("low", "mid", "high"))
  c(train = mean(yy[tr] < pr(tr)), test = mean(yy[te] < pr(te)),
    tapply(yy[te] < pr(te), tc, mean))
}
rbind(well_specified = calib(4215, FALSE), misspecified = calib(4216, TRUE))

## ---- calib-scalars ----
cw <- calib(4215, FALSE); cm <- calib(4216, TRUE)
r_wtr <- round(cw["train"], 3); r_wte <- round(cw["test"], 3)
r_mtr <- round(cm["train"], 3); r_mte <- round(cm["test"], 3)
r_mlo <- round(cm["low"], 3); r_mmid <- round(cm["mid"], 3); r_mhi <- round(cm["high"], 3)

## ---- sensitivity ----
set.seed(4225)
n2 <- 250
x2 <- runif(n2, 0, 10)
y2 <- 1 + 0.5 * x2 + rnorm(n2, 0, 1 + 0.12 * x2)   # unbounded, heteroscedastic tails
tset <- c(0.5, 0.9, 0.95, 0.99)
B <- 1000
set.seed(2020)
boot <- sapply(tset, function(t)
  replicate(B, { i <- sample(n2, n2, TRUE); qrfit(x2[i], y2[i], t)[2] }))
w <- apply(boot, 2, function(b) diff(quantile(b, c(.025, .975))))
data.frame(tau = tset, points_above = round(n2 * (1 - tset)), ci_width = round(w, 3))

## ---- sens-scalars ----
r_w <- round(w, 3)
r_e99 <- round(qrfit(x2, y2, 0.99)[2], 3)

## ---- fig-sensitivity ----
sens <- data.frame(tau = factor(tset),
                   est = sapply(tset, function(t) qrfit(x2, y2, t)[2]),
                   lo = apply(boot, 2, quantile, .025),
                   hi = apply(boot, 2, quantile, .975),
                   npts = round(n2 * (1 - tset)))
ggplot(sens, aes(tau, est)) +
  geom_hline(yintercept = 0, colour = line) +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.18, colour = forest, linewidth = 0.9) +
  geom_point(size = 2.6, colour = ink) +
  geom_text(aes(y = hi, label = paste0(npts, " pts")), vjust = -0.9, colour = faint, size = 3.2) +
  labs(x = "quantile", y = "slope (95% bootstrap interval)",
       subtitle = "the tail slope rests on a handful of points") +
  theme_te()
