# Bootstrapping dependent data: blocks and clusters
# https://tidyecology.com/posts/bootstrapping-dependent-data/
#
# 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-08

## ---- setup ----
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.0)),
          plot.subtitle = element_text(colour = "#54655b", size = rel(0.84)),
          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 = "bottom", plot.margin = margin(8, 12, 8, 12))
}

## ---- ts-data ----
set.seed(2440)
phi <- 0.6; n <- 120
x <- as.numeric(arima.sim(list(ar = phi), n = n, sd = 1))   # AR(1) annual index
xbar <- mean(x)
se_iid <- sd(x) / sqrt(n)                                   # naive independence SE

## ---- ts-boot ----
set.seed(717)
B <- 3000
boot_iid <- replicate(B, mean(sample(x, n, replace = TRUE)))     # destroys dependence

cblock_mean <- function(x, l) {
  n <- length(x); k <- ceiling(n / l)
  xc <- c(x, x[seq_len(l)])                                       # wrap the series
  starts <- sample(seq_len(n), k, replace = TRUE)
  idx <- as.vector(sapply(starts, function(s) s:(s + l - 1)))[seq_len(n)]
  mean(xc[idx])
}
boot_block <- replicate(B, cblock_mean(x, 8))                     # blocks of 8 years
se_boot_iid <- sd(boot_iid); se_boot_block <- sd(boot_block)

## ---- fig-ts ----
dts <- data.frame(t = seq_len(n), x = x)
pA <- ggplot(dts, aes(t, x)) +
  geom_hline(yintercept = xbar, colour = te_gold, linewidth = 0.5, linetype = "dashed") +
  geom_line(colour = te_ink, linewidth = 0.5) +
  labs(title = "Autocorrelated index", subtitle = "Drifts in runs, not independent jitter",
       x = "year", y = "index anomaly") +
  theme_te() + theme(legend.position = "none")
dboot <- rbind(data.frame(m = boot_iid, kind = "single points"),
               data.frame(m = boot_block, kind = "blocks of 8"))
pB <- ggplot(dboot, aes(m, fill = kind, colour = kind)) +
  geom_density(alpha = 0.45, linewidth = 0.4) +
  scale_fill_manual(values = c("single points" = "#a5524a", "blocks of 8" = "#275139")) +
  scale_colour_manual(values = c("single points" = "#a5524a", "blocks of 8" = "#275139")) +
  labs(title = "Bootstrap distribution of the mean", subtitle = "Single points understate the spread",
       x = "resampled mean", y = "density", fill = NULL, colour = NULL) +
  theme_te()
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))

## ---- clus-data ----
set.seed(2441)
G <- 20; ng <- 8; N <- G * ng
mu_true <- 5; tau <- 1; sigma <- 1
gen_clustered <- function() {
  b <- rnorm(G, 0, tau)                       # site effect
  grp <- rep(seq_len(G), each = ng)
  data.frame(grp = grp, y = mu_true + b[grp] + rnorm(N, 0, sigma))
}
d <- gen_clustered()
icc <- tau^2 / (tau^2 + sigma^2)              # within-site correlation
se_naive_c <- sd(d$y) / sqrt(N)
se_true_c <- sqrt(tau^2 / G + sigma^2 / N)    # honest SE for a balanced design

## ---- clus-boot ----
set.seed(818)
boot_row <- replicate(B, mean(sample(d$y, N, replace = TRUE)))   # resample rows

cluster_mean <- function(d, G) {
  gg <- sample(unique(d$grp), G, replace = TRUE)
  mean(unlist(lapply(gg, function(g) d$y[d$grp == g])))          # keep whole sites
}
boot_clus <- replicate(B, cluster_mean(d, G))
se_boot_row <- sd(boot_row); se_boot_clus <- sd(boot_clus)

## ---- coverage ----
ar1 <- function() as.numeric(arima.sim(list(ar = phi), n = n, sd = 1))
cov_ts <- function(R = 700, Bb = 400, l = 8) {
  hi <- 0; hb <- 0
  for (r in seq_len(R)) {
    xx <- ar1()
    bi <- replicate(Bb, mean(sample(xx, n, TRUE)))
    bk <- replicate(Bb, cblock_mean(xx, l))
    hi <- hi + (0 >= quantile(bi, .025) & 0 <= quantile(bi, .975))
    hb <- hb + (0 >= quantile(bk, .025) & 0 <= quantile(bk, .975))
  }
  c(iid = hi / R, block = hb / R)
}
cov_cl <- function(R = 700, Bb = 400) {
  hr <- 0; hc <- 0
  for (r in seq_len(R)) {
    dd <- gen_clustered()
    br <- replicate(Bb, mean(sample(dd$y, N, TRUE)))
    bc <- replicate(Bb, cluster_mean(dd, G))
    hr <- hr + (mu_true >= quantile(br, .025) & mu_true <= quantile(br, .975))
    hc <- hc + (mu_true >= quantile(bc, .025) & mu_true <= quantile(bc, .975))
  }
  c(row = hr / R, cluster = hc / R)
}
set.seed(404); cts <- cov_ts()
set.seed(505); ccl <- cov_cl()
ls <- c(1, 4, 8, 12, 16, 24)
set.seed(606)
cvl <- sapply(ls, function(l) {
  h <- 0
  for (r in seq_len(500)) {
    xx <- ar1(); bk <- replicate(300, cblock_mean(xx, l))
    h <- h + (0 >= quantile(bk, .025) & 0 <= quantile(bk, .975))
  }
  h / 500
})

## ---- fig-cov ----
dcov <- data.frame(
  case = factor(rep(c("time series", "clustered"), each = 2), levels = c("time series", "clustered")),
  method = factor(c("naive", "block", "naive", "cluster"), levels = c("naive", "block", "cluster")),
  cov = c(cts[1], cts[2], ccl[1], ccl[2]),
  aware = c("naive", "aware", "naive", "aware"))
pA <- ggplot(dcov, aes(interaction(method, case), cov, fill = aware)) +
  geom_col(width = 0.7) +
  geom_hline(yintercept = 0.95, linetype = "dashed", colour = "#233a2c", linewidth = 0.6) +
  geom_text(aes(label = sprintf("%.2f", cov)), vjust = 1.5, size = 2.9, colour = "#f5f4ee") +
  scale_fill_manual(values = c("naive" = "#a5524a", "aware" = "#275139")) +
  scale_x_discrete(labels = c("iid", "block", "row", "cluster")) +
  coord_cartesian(ylim = c(0, 1.0)) +
  labs(title = "Coverage of 95% intervals", subtitle = "Time series (left pair), clustered (right pair)",
       x = NULL, y = "coverage", fill = NULL) +
  theme_te()
dvl <- data.frame(l = ls, cov = cvl)
pB <- ggplot(dvl, aes(l, cov)) +
  geom_hline(yintercept = 0.95, linetype = "dashed", colour = "#8a8a80", linewidth = 0.5) +
  geom_line(colour = te_ink, linewidth = 0.9) +
  geom_point(colour = te_ink, size = 1.5) +
  labs(title = "Block length is a choice", subtitle = "Series coverage vs block length",
       x = "block length (years)", y = "coverage") +
  theme_te()
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))
