# Heteroscedasticity and limiting factors
# https://tidyecology.com/posts/heteroscedasticity-and-limiting-factors/
#
# 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

## ---- 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))
qslope <- 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[2]
}

## ---- data ----
set.seed(4203)
n  <- 300
x  <- runif(n, 1, 20)          # resource gradient (for example patch area)
u  <- runif(n)                 # everything else that can limit a site
b0 <- 2; b1 <- 1.5             # ceiling = b0 + b1 * x
y  <- (b0 + b1 * x) * u        # each site sits somewhere below its ceiling

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

## ---- ols-scalars ----
r_ols  <- round(unname(coef(ols)[2]), 3)
r_ratio <- round(unname(coef(ols)[2]) / b1, 3)

## ---- quantiles ----
taus <- c(0.5, 0.75, 0.9, 0.95, 0.99)
qs   <- sapply(taus, function(t) qslope(x, y, t))
names(qs) <- taus
round(qs, 3)

## ---- q-scalars ----
r_qs <- round(qs, 3)
r_qth <- round(taus * b1, 3)

## ---- fig-wedge ----
tt <- c(0.5, 0.9, 0.95)
co <- t(sapply(tt, function(t) { obj <- function(b) sum(rho(y - (b[1] + b[2]*x), t))
  optim(unname(coef(lm(y~x))), obj, control = list(reltol = 1e-12, maxit = 8000))$par }))
xg <- seq(1, 20, length.out = 60)
qdf <- do.call(rbind, lapply(seq_along(tt), function(i)
  data.frame(x = xg, y = co[i, 1] + co[i, 2] * xg, tau = factor(tt[i]))))
ggplot() +
  geom_point(aes(x, y), colour = sage, alpha = 0.6, size = 1.5) +
  geom_line(data = data.frame(x = xg, y = b0 + b1 * xg), aes(x, y),
            colour = ink, linetype = "dotted", linewidth = 0.8) +
  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.5" = gold, "0.9" = forest, "0.95" = warm),
                      name = "quantile") +
  labs(x = "resource gradient", y = "response",
       subtitle = "dotted = true ceiling; dashed = least squares") +
  theme_te()

## ---- bootstrap ----
set.seed(101)
B  <- 1200
bs <- replicate(B, {
  i <- sample(n, n, TRUE)
  c(qslope(x[i], y[i], 0.5), qslope(x[i], y[i], 0.9))
})
diff_ci <- quantile(bs[2, ] - bs[1, ], c(.025, .975))
round(diff_ci, 3)

## ---- boot-scalars ----
r_ci50 <- round(quantile(bs[1, ], c(.025, .975)), 3)
r_ci90 <- round(quantile(bs[2, ], c(.025, .975)), 3)
r_dci  <- round(diff_ci, 3)

## ---- fig-coef-path ----
tg <- seq(0.1, 0.95, 0.05)
sg <- sapply(tg, function(t) qslope(x, y, t))
set.seed(303); Bp <- 400
band <- sapply(tg, function(t)
  quantile(replicate(Bp, { i <- sample(n, n, TRUE); qslope(x[i], y[i], t) }),
           c(.025, .975)))
pdf <- data.frame(tau = tg, slope = sg, lo = band[1, ], hi = band[2, ])
ggplot(pdf, aes(tau, slope)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), fill = sage, alpha = 0.35) +
  geom_line(aes(y = tau * b1), colour = warm, linetype = "dashed", linewidth = 0.8) +
  geom_line(colour = forest, linewidth = 1) +
  geom_hline(yintercept = coef(ols)[2], colour = faint, linetype = "dotted") +
  labs(x = "quantile", y = "slope",
       subtitle = "dashed = tau times ceiling slope; dotted = least-squares slope") +
  theme_te()
