# The nonparametric bootstrap from scratch
# https://tidyecology.com/posts/the-nonparametric-bootstrap/
#
# 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

## ---- data ----
set.seed(34)
mlc <- log(26); slc <- 0.62          # control: meanlog, sdlog
mli <- log(52); sli <- 0.78          # impact: larger and more variable
rr_true <- exp(mli + sli^2/2) / exp(mlc + slc^2/2)   # ratio of population means

nc <- 20; ni <- 22
xc <- rlnorm(nc, mlc, slc)           # control abundances
xi <- rlnorm(ni, mli, sli)           # impact abundances
resp_ratio <- function(a, b) mean(b) / mean(a)
theta_hat <- resp_ratio(xc, xi)

## ---- boot ----
set.seed(101)
B <- 4000
boot <- replicate(B, mean(sample(xi, ni, replace = TRUE)) /
                     mean(sample(xc, nc, replace = TRUE)))
se_boot   <- sd(boot)
bias_boot <- mean(boot) - theta_hat
skew_boot <- mean((boot - mean(boot))^3) / sd(boot)^3

## ---- intervals ----
ci_norm  <- theta_hat + c(-1, 1) * qnorm(0.975) * se_boot
ci_perc  <- as.numeric(quantile(boot, c(0.025, 0.975)))
ci_basic <- as.numeric(2 * theta_hat - quantile(boot, c(0.975, 0.025)))

# BCa: bias-correction z0 and acceleration a (jackknife)
z0   <- qnorm(mean(boot < theta_hat))
jack <- c(sapply(seq_len(nc), function(i) resp_ratio(xc[-i], xi)),
          sapply(seq_len(ni), function(i) resp_ratio(xc, xi[-i])))
jbar <- mean(jack)
acc  <- sum((jbar - jack)^3) / (6 * (sum((jbar - jack)^2))^1.5)
zc   <- qnorm(c(0.025, 0.975))
adj  <- pnorm(z0 + (z0 + zc) / (1 - acc * (z0 + zc)))
ci_bca <- as.numeric(quantile(boot, adj))

## ---- fig-dist ----
suppressMessages(library(ggplot2))
te_ink <- "#275139"; te_green <- "#4e7a5a"; te_gold <- "#c98a1b"
te_rose <- "#a5524a"; te_slate <- "#3f5c7a"; te_grey <- "#8a8a80"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(text = element_text(colour = "#2f3e35"),
          plot.title = element_text(face = "bold", colour = "#233a2c", size = rel(1.02)),
          plot.subtitle = element_text(colour = "#54655b", size = rel(0.86)),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e3d8", linewidth = 0.3),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          axis.text = element_text(colour = "#54655b"),
          legend.position = "none",
          plot.margin = margin(8, 12, 8, 12))
}
ints <- data.frame(
  method = factor(c("normal", "percentile", "basic", "BCa"),
                  levels = c("BCa", "basic", "percentile", "normal")),
  lo = c(ci_norm[1], ci_perc[1], ci_basic[1], ci_bca[1]),
  hi = c(ci_norm[2], ci_perc[2], ci_basic[2], ci_bca[2]),
  col = c(te_slate, te_green, te_grey, te_ink))
ymax <- max(hist(boot, breaks = 40, plot = FALSE)$density)
yb <- -ymax * c(0.10, 0.20, 0.30, 0.40)
ints$y <- yb[as.integer(factor(ints$method, levels = c("normal","percentile","basic","BCa")))]
ggplot() +
  geom_histogram(aes(x = boot, y = after_stat(density)), bins = 40,
                 fill = "#dfe8e0", colour = "#c4d3c6", linewidth = 0.2) +
  geom_vline(xintercept = theta_hat, colour = te_ink, linewidth = 0.7) +
  geom_vline(xintercept = rr_true, colour = te_rose, linewidth = 0.6, linetype = "dashed") +
  geom_segment(data = ints, aes(x = lo, xend = hi, y = y, yend = y, colour = col), linewidth = 1.6) +
  geom_point(data = ints, aes(x = theta_hat, y = y, colour = col), size = 1.6) +
  geom_text(data = ints, aes(x = lo, y = y, label = method, colour = col),
            hjust = 1.08, size = 3.1) +
  scale_colour_identity() +
  # the outermost bin edges land just outside these limits, and the default oob rule
  # would censor both end bins (they are empty, so only the warning is visible)
  scale_x_continuous(limits = c(0.4, 5.2), oob = scales::oob_keep) +
  labs(title = "One estimate, four confidence intervals",
       subtitle = "Solid line: estimate. Dashed line: true ratio. Bars: 95% intervals by method.",
       x = "Response ratio (impact mean / control mean)", y = "Density") +
  theme_te()

## ---- coverage ----
covsim <- function(R = 1500, Bb = 800) {
  hit <- matrix(0, R, 4); mlo <- matrix(0, R, 4); mhi <- matrix(0, R, 4)
  for (r in seq_len(R)) {
    a <- rlnorm(nc, mlc, slc); b <- rlnorm(ni, mli, sli)
    th <- resp_ratio(a, b)
    bt <- replicate(Bb, mean(sample(b, ni, TRUE)) / mean(sample(a, nc, TRUE)))
    se <- sd(bt)
    c_n <- th + c(-1, 1) * qnorm(0.975) * se
    c_p <- quantile(bt, c(0.025, 0.975))
    c_b <- 2 * th - quantile(bt, c(0.975, 0.025))
    z0b <- qnorm(mean(bt < th))
    jk  <- c(sapply(seq_len(nc), function(i) resp_ratio(a[-i], b)),
             sapply(seq_len(ni), function(i) resp_ratio(a, b[-i])))
    jbb <- mean(jk); ac <- sum((jbb - jk)^3) / (6 * (sum((jbb - jk)^2))^1.5)
    ad  <- pnorm(z0b + (z0b + zc) / (1 - ac * (z0b + zc)))
    c_c <- quantile(bt, ad)
    L <- list(c_n, as.numeric(c_p), as.numeric(c_b), as.numeric(c_c))
    for (k in 1:4) {
      hit[r, k] <- (rr_true >= L[[k]][1] & rr_true <= L[[k]][2])
      mlo[r, k] <- (rr_true <  L[[k]][1])          # missed below
      mhi[r, k] <- (rr_true >  L[[k]][2])          # missed above
    }
  }
  list(cov = colMeans(hit), miss_lo = colMeans(mlo), miss_hi = colMeans(mhi))
}
set.seed(202)
cvr <- covsim(R = 1500, Bb = 800)
cov_norm <- cvr$cov[1]; cov_perc <- cvr$cov[2]; cov_basic <- cvr$cov[3]; cov_bca <- cvr$cov[4]
hi_norm <- cvr$miss_hi[1]; lo_norm <- cvr$miss_lo[1]
hi_basic <- cvr$miss_hi[3]; lo_basic <- cvr$miss_lo[3]
lo_bca <- cvr$miss_lo[4]; hi_bca <- cvr$miss_hi[4]

## ---- fig-coverage ----
methods <- c("normal", "percentile", "basic", "BCa")
cols <- c("#3f5c7a", "#4e7a5a", "#8a8a80", "#275139")
dcov <- data.frame(method = factor(methods, levels = methods),
                   cov = as.numeric(cvr$cov), col = cols)
pA <- ggplot(dcov, aes(method, cov, fill = col)) +
  geom_col(width = 0.68) +
  geom_hline(yintercept = 0.95, linetype = "dashed", colour = "#a5524a", linewidth = 0.6) +
  geom_text(aes(label = sprintf("%.3f", cov)), vjust = -0.5, size = 3, colour = "#233a2c") +
  scale_fill_identity() +
  coord_cartesian(ylim = c(0.80, 0.965)) +
  labs(title = "Overall coverage", subtitle = "Nominal 95% (dashed)",
       x = NULL, y = "coverage") +
  theme_te() + theme(axis.text.x = element_text(angle = 20, hjust = 1))
dmiss <- data.frame(
  method = factor(rep(methods, 2), levels = methods),
  side = rep(c("misses below", "misses above"), each = 4),
  rate = c(as.numeric(cvr$miss_lo), as.numeric(cvr$miss_hi)))
pB <- ggplot(dmiss, aes(method, rate, fill = side)) +
  geom_col(position = position_dodge(width = 0.72), width = 0.66) +
  geom_hline(yintercept = 0.025, linetype = "dotted", colour = "#8a8a80", linewidth = 0.5) +
  scale_fill_manual(values = c("misses below" = "#c98a1b", "misses above" = "#a5524a")) +
  labs(title = "Where the misses land", subtitle = "Target: 2.5% each side (dotted)",
       x = NULL, y = "miss rate", fill = NULL) +
  theme_te() + theme(axis.text.x = element_text(angle = 20, hjust = 1),
                     legend.position = "bottom")
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
