# Correlations from gradients of different length
# https://tidyecology.com/posts/correlations-from-gradients-of-different-length/
#
# 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-09-08

## ---- setup ----
library(ggplot2)
library(patchwork)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- design ----
k_st  <- 20                # studies per meta-analysis
n_lo  <- 15; n_hi <- 100   # study sample sizes, log-uniform
b_true <- 1                # the one per-unit slope
r_med <- 0.30              # population correlation of the median study
L_med <- sqrt(12) * r_med / (b_true * sqrt(1 - r_med^2))

sim_studies <- function(n_meta, R, rho, cv_b = 0) {
  n_st <- n_meta * k_st
  n_i <- round(exp(runif(n_st, log(n_lo), log(n_hi))))
  log_ext <- rnorm(n_st)
  sd_logL <- log(R) / (2 * qnorm(0.9))           # P90 / P10 of L equals R
  meta <- rep(seq_len(n_meta), each = k_st)
  L <- exp(sd_logL * (rho * log_ext + sqrt(1 - rho^2) * rnorm(n_st)))
  L <- L / ave(L, meta, FUN = median) * L_med
  b_i <- b_true * exp(rnorm(n_st, -0.5 * log(1 + cv_b^2), sqrt(log(1 + cv_b^2))))
  st <- rep(seq_len(n_st), n_i)
  x <- runif(length(st)) * L[st]
  y <- b_i[st] * x + rnorm(length(st))
  mx <- rowsum(x, st)[, 1] / n_i; my <- rowsum(y, st)[, 1] / n_i
  xc <- x - mx[st]; yc <- y - my[st]
  sxx <- rowsum(xc^2, st)[, 1]; syy <- rowsum(yc^2, st)[, 1]
  sxy <- rowsum(xc * yc, st)[, 1]
  bh <- sxy / sxx
  x_range <- as.vector(tapply(x, st, max) - tapply(x, st, min))
  data.frame(meta = meta, n = n_i, log_ext = log_ext, L = L,
             r = sxy / sqrt(sxx * syy), sx = sqrt(sxx / (n_i - 1)), x_range = x_range,
             bh = bh, se = sqrt((syy - bh * sxy) / (n_i - 2) / sxx))
}

## ---- example ----
set.seed(4417)
one_ma <- sim_studies(1, R = 4, rho = 0.7)
ex_rmin <- min(one_ma$r); ex_rmax <- max(one_ma$r)
ex_bmin <- min(one_ma$bh); ex_bmax <- max(one_ma$bh)
ex_cor_rs <- cor(one_ma$r, log(one_ma$sx)); ex_cor_bs <- cor(one_ma$bh, log(one_ma$sx))
s_curve <- exp(seq(log(min(one_ma$sx)) - 0.1, log(max(one_ma$sx)) + 0.1, length.out = 200))
curve_df <- data.frame(sx = s_curve, r = b_true * s_curve / sqrt(b_true^2 * s_curve^2 + 1))

## ---- fig-one-meta ----
p_r <- ggplot(one_ma, aes(sx, r)) +
  geom_line(data = curve_df, colour = te_rust, linewidth = 0.9) +
  geom_point(aes(size = n), colour = te_ink, alpha = 0.8) +
  scale_x_log10(limits = range(s_curve)) + scale_size_area(max_size = 4, name = "study n") +
  labs(x = "SD of the sampled gradient (log scale)", y = "study correlation r",
       title = "Correlations track the design",
       subtitle = "line: b s / sqrt(b^2 s^2 + 1)") +
  theme_datasheet() + theme(legend.position = "bottom")
p_b <- ggplot(one_ma, aes(sx, bh)) +
  geom_hline(yintercept = b_true, colour = te_forest, linewidth = 0.9) +
  geom_errorbar(aes(ymin = bh - se, ymax = bh + se), width = 0, colour = te_body,
                linewidth = 0.4) +
  geom_point(aes(size = n), colour = te_ink, alpha = 0.8) +
  scale_x_log10(limits = range(s_curve)) + scale_size_area(max_size = 4, name = "study n") +
  labs(x = "SD of the sampled gradient (log scale)", y = "study slope",
       title = "Slopes do not", subtitle = "line: the true slope") +
  theme_datasheet() + theme(legend.position = "bottom")
p_r + p_b + plot_layout(guides = "collect") +
  plot_annotation(theme = theme_datasheet()) & theme(legend.position = "bottom")

## ---- engine ----
dl_pool <- function(y, v) {
  w <- 1 / v; k <- length(y); mu_fe <- sum(w * y) / sum(w)
  Q <- sum(w * (y - mu_fe)^2)
  t2 <- max(0, (Q - (k - 1)) / (sum(w) - sum(w^2) / sum(w)))
  ws <- 1 / (v + t2)
  c(mu = sum(ws * y) / sum(ws), pQ = pchisq(Q, k - 1, lower.tail = FALSE),
    I2 = max(0, (Q - (k - 1)) / Q), t2 = t2)
}
mm_reg <- function(y, v, X) {       # p value of the first moderator
  X <- cbind(1, X); k <- length(y); p <- ncol(X); w <- 1 / v
  XtW <- t(X * w); A <- solve(XtW %*% X)
  e <- y - X %*% (A %*% (XtW %*% y))
  QE <- sum(w * e^2)
  trP <- sum(w) - sum(diag(A %*% (t(X * w^2) %*% X)))
  t2 <- max(0, (QE - (k - p)) / trP)
  ws <- 1 / (v + t2); XtWs <- t(X * ws); V <- solve(XtWs %*% X)
  beta_hat <- V %*% (XtWs %*% y)
  2 * pnorm(-abs(beta_hat[2] / sqrt(V[2, 2])))
}

## ---- analyse ----
case2 <- function(r, U) U * r / sqrt(1 + r^2 * (U^2 - 1))
analyse_meta <- function(d) {
  r <- d$r; n <- d$n; zr <- atanh(r); vz <- 1 / (n - 3)
  U <- median(d$sx) / d$sx
  den <- 1 + r^2 * (U^2 - 1)
  rc <- case2(r, U); zc <- atanh(rc)
  v_delta <- (U / den^1.5)^2 * (1 - r^2)^2 / (n - 1) / (1 - rc^2)^2
  v_scale <- vz * (rc / r)^2
  se_known <- 1 / (d$sx * sqrt(n - 1))
  arms <- list(zr = list(zr, vz), sl = list(d$bh, d$se^2), cu = list(zc, vz),
               cd = list(zc, v_delta), cs = list(zc, v_scale))
  out <- numeric(0)
  for (nm in names(arms)) {
    pp <- dl_pool(arms[[nm]][[1]], arms[[nm]][[2]])
    out[paste0(nm, "_I2")] <- pp[["I2"]]
    out[paste0(nm, "_Q")]  <- pp[["pQ"]] < 0.05
    out[paste0(nm, "_mu")] <- pp[["mu"]]
    out[paste0(nm, "_E")]  <- mm_reg(arms[[nm]][[1]], arms[[nm]][[2]], d$log_ext) < 0.05
  }
  out["zsd_E"] <- mm_reg(zr, vz, cbind(d$log_ext, log(d$sx))) < 0.05
  out["zrg_E"] <- mm_reg(zr, vz, cbind(d$log_ext, log(d$x_range))) < 0.05
  out["slk_Q"] <- dl_pool(d$bh, se_known^2)[["pQ"]] < 0.05
  out["t2_design"] <- var(asinh(b_true * d$L / sqrt(12)))
  out["t2_zr"] <- dl_pool(zr, vz)[["t2"]]
  out["rmin"] <- min(r); out["rmax"] <- max(r)
  out
}

## ---- mainsim ----
n_meta <- 2000
cells <- rbind(expand.grid(R = c(1, 2, 4, 8), rho = 0.7, cv = c(0, 0.2)),
               data.frame(R = 4, rho = c(0, 0.4), cv = 0))
cell_res <- lapply(seq_len(nrow(cells)), function(i) {
  set.seed(5270 + i)
  st <- sim_studies(n_meta, cells$R[i], cells$rho[i], cells$cv[i])
  vapply(split(st, st$meta), analyse_meta, numeric(27))
})
res <- cbind(cells, t(vapply(cell_res, rowMeans, numeric(27))))
res_sd <- t(vapply(cell_res, function(m) apply(m, 1, sd), numeric(27)))
mcse_max <- sqrt(0.25 / n_meta); mcse_05 <- sqrt(0.05 * 0.95 / n_meta)
cell <- function(R, rho = 0.7, cv = 0) which(res$R == R & res$rho == rho & res$cv == cv)
g <- function(metric_col, R, rho = 0.7, cv = 0) res[[metric_col]][cell(R, rho, cv)]

## ---- sweep-data ----
main_rows <- res[res$rho == 0.7 & res$cv == 0, ]
main_sd <- res_sd[res$rho == 0.7 & res$cv == 0, , drop = FALSE]
colnames(main_sd) <- colnames(res)[-(1:3)]
metric_lev <- c("mean I-squared", "Q test rejects", "extent moderator significant")
arm_lev <- c("Fisher z of r", "slopes")
sweep_df <- do.call(rbind, lapply(seq_along(metric_lev), function(j) {
  suf <- c("_I2", "_Q", "_E")[j]
  do.call(rbind, lapply(1:2, function(a) {
    col_nm <- paste0(c("zr", "sl")[a], suf)
    val <- main_rows[[col_nm]]
    se <- if (j == 1) main_sd[, col_nm] / sqrt(n_meta) else sqrt(val * (1 - val) / n_meta)
    data.frame(R = main_rows$R, metric = metric_lev[j], arm = arm_lev[a],
               value = val, se = se)
  }))
}))
sweep_df$metric <- factor(sweep_df$metric, levels = metric_lev)
sweep_df$arm <- factor(sweep_df$arm, levels = arm_lev)

## ---- fig-sweep ----
ggplot(sweep_df, aes(R, value, colour = arm)) +
  geom_hline(data = data.frame(metric = factor(metric_lev[2:3], levels = metric_lev), h = 0.05),
             aes(yintercept = h), colour = te_body, linetype = "dashed", linewidth = 0.5) +
  geom_line(linewidth = 0.9) +
  geom_errorbar(aes(ymin = value - 2 * se, ymax = value + 2 * se), width = 0.08,
                linewidth = 0.4) +
  geom_point(size = 2.2) +
  facet_wrap(~ metric, nrow = 1) +
  scale_x_log10(breaks = c(1, 2, 4, 8)) +
  scale_y_continuous(limits = c(0, 1)) +
  scale_colour_manual(values = c(te_rust, te_forest), name = NULL) +
  labs(x = "spread of gradient lengths, P90 / P10 (log scale)", y = NULL,
       title = "One slope, heterogeneity on demand",
       subtitle = "dashed line: the nominal five per cent") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- rho-cells ----
rho_rows <- res[res$R == 4 & res$cv == 0, ]
rho_rows <- rho_rows[order(rho_rows$rho), ]
rho_df <- data.frame(rho = rep(rho_rows$rho, 3),
                     arm = factor(rep(c("Fisher z of r", "slopes", "Fisher z, log SD(x) added"),
                                      each = nrow(rho_rows)),
                                  levels = c("Fisher z of r", "Fisher z, log SD(x) added", "slopes")),
                     rate = c(rho_rows$zr_E, rho_rows$sl_E, rho_rows$zsd_E))
rho_df$se <- sqrt(rho_df$rate * (1 - rho_df$rate) / n_meta)

## ---- fig-rho ----
ggplot(rho_df, aes(rho, rate, colour = arm)) +
  geom_hline(yintercept = 0.05, colour = te_body, linetype = "dashed", linewidth = 0.5) +
  geom_line(linewidth = 0.9) +
  geom_errorbar(aes(ymin = rate - 2 * se, ymax = rate + 2 * se), width = 0.02,
                linewidth = 0.4) +
  geom_point(size = 2.4) +
  scale_colour_manual(values = c(te_rust, te_gold, te_forest), name = NULL) +
  scale_x_continuous(breaks = c(0, 0.4, 0.7)) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "correlation of log extent with log gradient length",
       y = "extent moderator significant",
       title = "The moderator is only as real as the coupling",
       subtitle = "fourfold spread; dashed line: five per cent") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- deriv-check ----
r_try <- c(-0.2, 0.1, 0.3, 0.6); U_try <- c(0.5, 1.4, 2.5, 3.5)
h_step <- 1e-6
num_deriv <- (case2(r_try + h_step, U_try) - case2(r_try - h_step, U_try)) / (2 * h_step)
ana_deriv <- U_try / (1 + r_try^2 * (U_try^2 - 1))^1.5
deriv_gap <- max(abs(num_deriv - ana_deriv))

## ---- repair-data ----
arm_names <- c(zr = "Fisher z of r", sl = "slopes", cu = "case II, unadjusted variance",
               cd = "case II, delta-method variance", cs = "case II, variance scaled by (rc/r)^2")
rep_df <- do.call(rbind, lapply(names(arm_names), function(a)
  data.frame(R = main_rows$R, arm = arm_names[[a]],
             I2 = main_rows[[paste0(a, "_I2")]], E = main_rows[[paste0(a, "_E")]])))
rep_df <- rbind(rep_df, data.frame(R = main_rows$R, arm = "Fisher z, log SD(x) added",
                                   I2 = main_rows$zr_I2, E = main_rows$zsd_E))
rep_df$arm <- factor(rep_df$arm, levels = c(arm_names[c("zr", "cu")], "Fisher z, log SD(x) added",
                                            arm_names[c("cd", "cs", "sl")]))
rep_df$E_se <- sqrt(rep_df$E * (1 - rep_df$E) / n_meta)

## ---- fig-repairs ----
rep_long <- rbind(
  data.frame(R = rep_df$R, arm = rep_df$arm, panel = "mean I-squared",
             value = rep_df$I2, se = 0),
  data.frame(R = rep_df$R, arm = rep_df$arm, panel = "extent moderator significant",
             value = rep_df$E, se = rep_df$E_se))
rep_long <- rep_long[!(rep_long$panel == "mean I-squared" &
                       rep_long$arm == "Fisher z, log SD(x) added"), ]
rep_long$panel <- factor(rep_long$panel,
                         levels = c("mean I-squared", "extent moderator significant"))
te_amber <- "#b5651d"   # one extra hue, for the unadjusted correction only
ggplot(rep_long, aes(R, value, colour = arm, linetype = arm, shape = arm)) +
  geom_hline(data = data.frame(panel = factor("extent moderator significant",
                                              levels = levels(rep_long$panel)), h = 0.05),
             aes(yintercept = h), colour = te_body, linetype = "dashed", linewidth = 0.4) +
  geom_line(linewidth = 0.8) +
  geom_errorbar(aes(ymin = value - 2 * se, ymax = value + 2 * se), width = 0.06,
                linewidth = 0.4, linetype = "solid") +
  geom_point(size = 2.3) +
  facet_wrap(~ panel, nrow = 1) +
  scale_x_log10(breaks = c(1, 2, 4, 8)) +
  scale_y_continuous(limits = c(0, 0.85)) +
  scale_colour_manual(values = c(te_rust, te_amber, te_gold, te_ink, te_ink, te_forest),
                      name = NULL) +
  scale_linetype_manual(values = c("solid", "solid", "dashed", "solid", "dotted", "solid"),
                        name = NULL) +
  scale_shape_manual(values = c(16, 17, 1, 15, 0, 18), name = NULL) +
  guides(colour = guide_legend(ncol = 2), linetype = guide_legend(ncol = 2),
         shape = guide_legend(ncol = 2)) +
  labs(x = "spread of gradient lengths, P90 / P10 (log scale)", y = NULL,
       title = "What each repair leaves behind",
       subtitle = "dashed line: five per cent") +
  theme_datasheet() +
  theme(legend.position = "bottom", legend.key.width = unit(1.6, "lines"))
