# Stratified random sampling in ecology
# https://tidyecology.com/posts/stratified-random-sampling/
#
# 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

## ---- frame ----
set.seed(371)

Nh   <- c(meadow = 600, wetland = 300, woodland = 300)
mu_h <- c(meadow = 12,  wetland = 26,  woodland = 5)
sd_h <- c(meadow = 4,   wetland = 9,   woodland = 2)

N       <- sum(Nh)
H       <- length(Nh)
stratum <- rep(names(Nh), Nh)
y       <- round(pmax(0, rnorm(N, rep(mu_h, Nh), rep(sd_h, Nh))), 2)

W   <- Nh / N                                    # stratum weights, known
mu  <- mean(y)                                   # population mean (we get to peek)
S2  <- var(y)                                    # population variance, divisor N - 1
S2h <- tapply(y, stratum, var)[names(Nh)]        # within-stratum variances
muh <- tapply(y, stratum, mean)[names(Nh)]
round(rbind(W = W, mean = muh, sd = sqrt(S2h)), 3)

## ---- fig-frame ----
library(ggplot2)

theme_te <- function() {
  theme_minimal(base_size = 11) +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
      plot.title    = element_text(colour = "#16241d", face = "bold", size = 12),
      plot.subtitle = element_text(colour = "#5d6b61", size = 9.5),
      axis.title    = element_text(colour = "#46604a", size = 9.5),
      axis.text     = element_text(colour = "#2c3a31", size = 9),
      legend.title  = element_text(colour = "#46604a", size = 9.5),
      legend.text   = element_text(colour = "#2c3a31", size = 9),
      strip.text    = element_text(colour = "#16241d", face = "bold", size = 10)
    )
}
pal_h <- c(meadow = "#cda23f", wetland = "#2f8f63", woodland = "#b5534e")

ggplot(data.frame(y = y, stratum = factor(stratum, levels = names(Nh))),
       aes(y, colour = stratum, fill = stratum)) +
  geom_density(alpha = 0.18, linewidth = 0.8) +
  scale_colour_manual(values = pal_h) +
  scale_fill_manual(values = pal_h) +
  labs(title = "One landscape, three very different strata",
       subtitle = "1200 plots; the habitat map tells you which stratum each plot is in",
       x = "biomass (g per plot)", y = "density",
       colour = "stratum", fill = "stratum") +
  theme_te()

## ---- estimators ----
n  <- 120
f  <- n / N
nh <- round(n * W)                                # proportional allocation
nh

V_srs  <- (1 - f) * S2 / n
V_prop <- sum(W^2 * (1 - nh / Nh) * S2h / nh)
c(SE_srs = sqrt(V_srs), SE_stratified = sqrt(V_prop), ratio = V_srs / V_prop)

## ---- scalars-1 ----
se_srs   <- sqrt(V_srs)
se_str   <- sqrt(V_prop)
deff     <- V_srs / V_prop
n_equiv  <- ceiling(1 / (V_prop / S2 + 1 / N))   # SRS size with the same variance, FPC included

## ---- decomposition ----
within  <- sum((Nh - 1) * S2h) / (N - 1)
between <- sum(Nh * (muh - mu)^2) / (N - 1)
c(S2 = S2, within = within, between = between,
  check = within + between - S2, between_share = between / S2)

## ---- scalars-2 ----
share_between <- between / S2
gap_within    <- within - sum(W * S2h)

## ---- monte-carlo ----
idx_h <- split(seq_len(N), stratum)[names(Nh)]
B     <- 4000

draw_srs <- function() mean(y[sample.int(N, n)])
draw_str <- function() sum(W * vapply(seq_len(H), function(h)
                        mean(y[sample(idx_h[[h]], nh[h])]), 0))

set.seed(3711); mc_srs <- replicate(B, draw_srs())
set.seed(3712); mc_str <- replicate(B, draw_str())

rbind(simple     = c(mean = mean(mc_srs), variance = var(mc_srs), analytic = V_srs),
      stratified = c(mean = mean(mc_str), variance = var(mc_str), analytic = V_prop))

## ---- scalars-3 ----
mc_v_srs <- var(mc_srs); mc_v_str <- var(mc_str)

## ---- fig-sampling ----
dd <- rbind(data.frame(est = mc_srs, design = "simple random"),
            data.frame(est = mc_str, design = "stratified"))

ggplot(dd, aes(est, colour = design, fill = design)) +
  geom_density(alpha = 0.2, linewidth = 0.8) +
  geom_vline(xintercept = mu, colour = "#16241d", linetype = "dashed", linewidth = 0.4) +
  scale_colour_manual(values = c("simple random" = "#b5534e", "stratified" = "#275139")) +
  scale_fill_manual(values = c("simple random" = "#b5534e", "stratified" = "#275139")) +
  labs(title = "Same effort, a much tighter estimate",
       subtitle = "4000 samples of 120 plots each; dashed line is the population mean",
       x = "estimated mean biomass (g per plot)", y = "density",
       colour = "design", fill = "design") +
  theme_te()

## ---- variance-estimator ----
one_survey <- function() {
  s   <- lapply(seq_len(H), function(h) y[sample(idx_h[[h]], nh[h])])
  est <- sum(W * vapply(s, mean, 0))
  v   <- sum(W^2 * (1 - nh / Nh) * vapply(s, var, 0) / nh)
  c(estimate = est, variance = v)
}

set.seed(3713)
surveys  <- t(replicate(B, one_survey()))
coverage <- mean(abs(surveys[, "estimate"] - mu) <= 1.96 * sqrt(surveys[, "variance"]))
c(mean_v_hat = mean(surveys[, "variance"]), true_V = V_prop, coverage = coverage)

## ---- scalars-4 ----
v_hat_mean <- mean(surveys[, "variance"]); cov_str <- coverage

## ---- flat-frame ----
y_flat <- y
for (h in names(Nh)) y_flat[stratum == h] <- y[stratum == h] - muh[h] + mu

S2_flat  <- var(y_flat)
S2h_flat <- tapply(y_flat, stratum, var)[names(Nh)]
c(V_srs = (1 - f) * S2_flat / n,
  V_str = sum(W^2 * (1 - nh / Nh) * S2h_flat / nh),
  ratio = ((1 - f) * S2_flat / n) / sum(W^2 * (1 - nh / Nh) * S2h_flat / nh))

## ---- scalars-5 ----
ratio_flat <- ((1 - f) * S2_flat / n) / sum(W^2 * (1 - nh / Nh) * S2h_flat / nh)

## ---- sweep ----
k_grid <- seq(0, 1.5, by = 0.125)
ratio_k <- vapply(k_grid, function(k) {
  yk <- y
  for (h in names(Nh))
    yk[stratum == h] <- y[stratum == h] - muh[h] + mu + k * (muh[h] - mu)
  S2k  <- var(yk)
  S2hk <- tapply(yk, stratum, var)[names(Nh)]
  ((1 - f) * S2k / n) / sum(W^2 * (1 - nh / Nh) * S2hk / nh)
}, 0)
setNames(round(ratio_k, 2), k_grid)

## ---- fig-sweep ----
ggplot(data.frame(k = k_grid, ratio = ratio_k), aes(k, ratio)) +
  geom_hline(yintercept = 1, colour = "#93a87f", linetype = "dashed", linewidth = 0.4) +
  geom_line(colour = "#275139", linewidth = 0.9) +
  geom_point(colour = "#275139", size = 1.9) +
  annotate("point", x = 1, y = ratio_k[k_grid == 1], colour = "#b5534e", size = 3) +
  annotate("text", x = 1, y = ratio_k[k_grid == 1] - 0.45, label = "this landscape",
           colour = "#b5534e", size = 3.2) +
  labs(title = "Under proportional allocation, the gain is the separation",
       subtitle = "Within-stratum spreads held fixed; only the stratum means are moved",
       x = "stratum means, as a multiple of the real separation",
       y = "variance ratio (simple / stratified)") +
  theme_te()
