# Dichotomising a continuous confounder
# https://tidyecology.com/posts/dichotomising-a-continuous-predictor/
#
# 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-11-04

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

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
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))
}

n_plot   <- 200
rho_base <- 0.6
b_open   <- 1
sde_base <- 1

set.seed(1)
openness <- rnorm(n_plot)
deadwood <- rho_base * openness + sqrt(1 - rho_base^2) * rnorm(n_plot)
one <- data.frame(openness, deadwood,
                  recruit = b_open * openness + rnorm(n_plot, 0, sde_base),
                  open_class = ifelse(openness > median(openness), "open", "closed"))

fit_cont  <- lm(recruit ~ deadwood + openness, data = one)
fit_split <- lm(recruit ~ deadwood + open_class, data = one)

coef_cont  <- summary(fit_cont)$coefficients["deadwood", ]
coef_split <- summary(fit_split)$coefficients["deadwood", ]
round(rbind(as_measured = coef_cont, median_split = coef_split), 4)

## ---- rhosweep ----
leak_q <- function(q) {
  z <- qnorm(q)
  1 - dnorm(z)^2 / (q * (1 - q))
}
rej_closed <- function(n, rho, b1, sde, k) {
  v_res <- 1 - rho^2 * (1 - k)
  ncp   <- (b1 * rho * k / v_res) *
    sqrt(n * v_res / (sde^2 + b1^2 * (k - rho^2 * k^2 / v_res)))
  crit <- qt(0.975, n - 3)
  pt(-crit, n - 3, ncp) + pt(-crit, n - 3, -ncp)
}

sim_cell <- function(nsim, n, rho, b1, sde, adj, q = 0.5, dep = "linear", known = FALSE, seed) {
  set.seed(seed)
  n_rej <- 0
  est <- numeric(nsim)
  for (i in seq_len(nsim)) {
    openness <- rnorm(n)
    deadwood <- if (dep == "linear") rho * openness + sqrt(1 - rho^2) * rnorm(n) else
      scale(rho * (openness^2 - 1) / sqrt(2) + sqrt(1 - rho^2) * rnorm(n))[, 1]
    recruit  <- b1 * openness + rnorm(n, 0, sde)
    adj_mat <- if (adj == "cont") cbind(openness) else if (adj == "split") {
      cbind(as.numeric(openness > if (known) qnorm(q) else quantile(openness, q)))
    } else {
      edge <- quantile(openness, seq(0, 1, length.out = as.integer(adj) + 1))
      model.matrix(~ 0 + cut(openness, edge, include.lowest = TRUE))[, -1, drop = FALSE]
    }
    design <- cbind(1, deadwood, adj_mat)
    fit <- .lm.fit(design, recruit)
    np <- ncol(design)
    s2 <- sum(fit$residuals^2) / (n - np)
    vv <- chol2inv(chol(crossprod(design)))[2, 2]
    n_rej <- n_rej + (abs(fit$coefficients[2] / sqrt(s2 * vv)) > qt(0.975, n - np))
    est[i] <- fit$coefficients[2]
  }
  pr <- n_rej / nsim
  data.frame(adj, n, rho, sde, q, rej = pr, se_rej = sqrt(pr * (1 - pr) / nsim),
             bias = mean(est), se_bias = sd(est) / sqrt(nsim))
}

nsim_rho <- 8000
rho_grid <- c(0, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99)

sweep_split <- do.call(rbind, lapply(seq_along(rho_grid), function(i)
  sim_cell(nsim_rho, n_plot, rho_grid[i], b_open, sde_base, "split", seed = 300 + i)))
sweep_cont <- do.call(rbind, lapply(seq_along(rho_grid), function(i)
  sim_cell(nsim_rho, n_plot, rho_grid[i], b_open, sde_base, "cont", seed = 300 + i)))
sweep_known <- do.call(rbind, lapply(seq_along(rho_grid), function(i)
  sim_cell(nsim_rho, n_plot, rho_grid[i], b_open, sde_base, "split", known = TRUE, seed = 300 + i)))
rej_line   <- rej_closed(n_plot, rho_grid, b_open, sde_base, leak_q(0.5))
gap_sample <- max(rej_line - sweep_split$rej)
gap_known  <- max(rej_line - sweep_known$rej)

at_base  <- which(rho_grid == rho_base)
at_zero  <- which(rho_grid == 0)
at_high  <- which(rho_grid == 0.9)
at_max   <- which(rho_grid == 0.99)
rej_split_base <- sweep_split$rej[at_base]
rej_cont_base  <- sweep_cont$rej[at_base]
bias_base      <- sweep_split$bias[at_base]

## ---- figsweep ----
sweep_long <- data.frame(rho = rho_grid, rej = c(sweep_split$rej, sweep_cont$rej),
  adjustment = rep(c("median split of openness", "openness as measured"), each = length(rho_grid)))
closed_line <- data.frame(rho = seq(0, 0.99, length.out = 200))
closed_line$rej <- rej_closed(n_plot, closed_line$rho, b_open, sde_base, leak_q(0.5))

ggplot(sweep_long, aes(rho, rej, colour = adjustment)) +
  geom_line(data = closed_line, aes(rho, rej), inherit.aes = FALSE,
            colour = te_ink, linewidth = 0.4) +
  geom_hline(yintercept = 0.05, linetype = "dashed", colour = te_body, linewidth = 0.5) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.2) +
  scale_colour_manual(values = c(te_rust, te_forest), name = NULL) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "correlation between canopy openness and deadwood volume",
       y = "share of surveys with p < 0.05 for deadwood",
       title = "A true null, tested two ways",
       subtitle = "dashed: the nominal 5 per cent; thin dark line: the closed form") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- leak ----
k_median <- 1 - 2 / pi

set.seed(5)
n_check <- 4e6
leak_measured <- function(x) 1 - cor(x, as.numeric(x > median(x)))^2

k_normal <- leak_measured(rnorm(n_check))
k_unif   <- leak_measured(runif(n_check))
k_lnorm  <- leak_measured(rlnorm(n_check))
k_expo   <- leak_measured(rexp(n_check))
k_t3     <- leak_measured(rt(n_check, 3))

k_unif_exact  <- 1 - 3 / 4
k_expo_exact  <- 1 - log(2)^2
k_lnorm_exact <- 1 - ((exp(0.5) * pnorm(1) - exp(0.5) / 2) /
                        (sqrt(exp(2) - exp(1)) * 0.5))^2
exact_gap <- max(abs(c(k_unif - k_unif_exact, k_expo - k_expo_exact,
                       k_lnorm - k_lnorm_exact)))
bias_closed <- b_open * rho_base * k_median / (1 - rho_base^2 * (1 - k_median))
round(c(normal = k_normal, uniform = k_unif, exponential = k_expo,
        t_3df = k_t3, lognormal = k_lnorm), 4)

## ---- invariance ----
n_grid <- c(50, 100, 500, 2000)
inv_n <- do.call(rbind, lapply(seq_along(n_grid), function(i)
  sim_cell(4000, n_grid[i], rho_base, b_open, sde_base, "split", seed = 520 + i)))

sde_grid <- c(0.25, 0.5, 2, 4)
inv_sde <- do.call(rbind, lapply(seq_along(sde_grid), function(i)
  sim_cell(4000, n_plot, rho_base, b_open, sde_grid[i], "split", seed = 610 + i)))

bias_span <- range(c(inv_n$bias, inv_sde$bias))
round(rbind(inv_n, inv_sde)[, c("n", "sde", "rej", "bias")], 4)

## ---- forms ----
form_cell <- function(nsim, n, rho, sde, shape, adj, seed) {
  set.seed(seed)
  n_rej <- 0
  est <- numeric(nsim)
  for (i in seq_len(nsim)) {
    openness <- rnorm(n)
    deadwood <- rho * openness + sqrt(1 - rho^2) * rnorm(n)
    truth <- switch(shape, linear = openness, quad = openness^2,
                    step80 = as.numeric(openness > qnorm(0.8)))
    recruit <- scale(truth)[, 1] + rnorm(n, 0, sde)
    adj_mat <- switch(adj, cont = cbind(openness), spline = splines::ns(openness, 4),
                      split  = cbind(as.numeric(openness > median(openness))),
                      step80 = cbind(as.numeric(openness > quantile(openness, 0.8))),
                      quadratic = cbind(openness, openness^2))
    design <- cbind(1, deadwood, adj_mat)
    fit <- .lm.fit(design, recruit)
    np <- ncol(design)
    s2 <- sum(fit$residuals^2) / (n - np)
    vv <- chol2inv(chol(crossprod(design)))[2, 2]
    n_rej <- n_rej + (abs(fit$coefficients[2] / sqrt(s2 * vv)) > qt(0.975, n - np))
    est[i] <- fit$coefficients[2]
  }
  pr <- n_rej / nsim
  data.frame(shape, adj, rej = pr, se_rej = sqrt(pr * (1 - pr) / nsim),
             bias = mean(est), se_bias = sd(est) / sqrt(nsim))
}

form_grid <- rbind(
  c("linear", "cont"), c("linear", "split"), c("linear", "quadratic"), c("linear", "spline"),
  c("step80", "cont"), c("step80", "split"), c("step80", "step80"), c("step80", "spline"),
  c("quad", "cont"), c("quad", "split"), c("quad", "quadratic"), c("quad", "spline"))

forms <- do.call(rbind, lapply(seq_len(nrow(form_grid)), function(i)
  form_cell(5000, n_plot, rho_base, sde_base, form_grid[i, 1], form_grid[i, 2],
            seed = 900 + i)))

pick <- function(sh, ad) forms[forms$shape == sh & forms$adj == ad, ]
step_wrong <- pick("step80", "cont")
step_right <- pick("step80", "step80")
step_split <- pick("step80", "split")
step_spline <- pick("step80", "spline")
quad_split <- pick("quad", "split")
cbind(forms[, 1:2], round(forms[, 3:6], 4))

## ---- figforms ----
adj_label <- c(cont = "openness as measured", split = "median split", step80 = "step at the 80th percentile",
               quadratic = "quadratic in openness", spline = "natural spline, 4 df")
shape_label <- c(linear = "true effect: linear", step80 = "true effect: step at the 80th percentile",
                 quad = "true effect: quadratic")
forms$adj_f <- factor(adj_label[forms$adj], levels = rev(unname(adj_label)))
forms$shape_f <- factor(shape_label[forms$shape], levels = unname(shape_label))

ggplot(forms, aes(rej, adj_f)) +
  geom_vline(xintercept = 0.05, linetype = "dashed", colour = te_body, linewidth = 0.5) +
  geom_errorbar(aes(xmin = rej - se_rej, xmax = rej + se_rej), orientation = "y",
                width = 0.25, colour = te_body, linewidth = 0.5) +
  geom_point(size = 2.8, colour = te_forest) +
  facet_wrap(~ shape_f, ncol = 1, scales = "free_y") +
  scale_x_continuous(limits = c(0, 1)) +
  labs(x = "share of surveys with p < 0.05 for deadwood", y = NULL,
       title = "The exposure side decides",
       subtitle = "dashed: the nominal 5 per cent") +
  theme_datasheet() +
  theme(strip.text = element_text(colour = te_ink, hjust = 0))

## ---- stepscale ----
scale_grid <- c(800, 3200)
step_scale <- do.call(rbind, lapply(seq_along(scale_grid), function(i)
  form_cell(3000, scale_grid[i], rho_base, sde_base, "step80", "step80", seed = 940 + i)))
step_scale$n <- scale_grid
round(step_scale[, c("n", "rej", "se_rej", "bias", "se_bias")], 4)

## ---- nonlinear ----
nonlin <- rbind(
  sim_cell(4000, n_plot, rho_base, b_open, sde_base, "cont", dep = "curved", seed = 951),
  sim_cell(4000, n_plot, rho_base, b_open, sde_base, "split", dep = "curved", seed = 952))
cbind(nonlin[, "adj", drop = FALSE], round(nonlin[, c("rej", "se_rej", "bias", "se_bias")], 4))

## ---- cutsweep ----
q_grid <- c(0.1, 0.25, 0.4, 0.5, 0.6, 0.75, 0.9)
cut_sweep <- do.call(rbind, lapply(seq_along(q_grid), function(i)
  sim_cell(5000, n_plot, rho_base, b_open, sde_base, "split", q = q_grid[i],
           seed = 700 + i)))
cut_sweep$k <- leak_q(q_grid)
closed_gap <- max(abs(c(cut_sweep$rej - rej_closed(n_plot, rho_base, b_open, sde_base, cut_sweep$k),
                        sweep_split$rej - rej_closed(n_plot, rho_grid, b_open, sde_base, k_median))))

q_best <- q_grid[which.min(cut_sweep$rej)]
k_ratio <- leak_q(0.1) / leak_q(0.5)
rej_gap <- max(cut_sweep$rej) - min(cut_sweep$rej)
round(cut_sweep[, c("q", "k", "rej", "se_rej", "bias")], 4)

## ---- grain ----
grain_adj <- c("split", "3", "4", "5", "10", "cont")
grain <- do.call(rbind, lapply(seq_along(grain_adj), function(i)
  sim_cell(5000, n_plot, rho_base, b_open, sde_base, grain_adj[i], seed = 810 + i)))

leak_cuts <- function(cuts) {
  dz <- c(0, dnorm(qnorm(cuts)), 0)
  1 - sum(diff(dz)^2 / diff(c(0, cuts, 1)))
}
grain$k <- c(leak_q(0.5), leak_cuts(1:2 / 3), leak_cuts(1:3 / 4),
             leak_cuts(1:4 / 5), leak_cuts(1:9 / 10), 0)
grain$groups <- factor(c("2", "3", "4", "5", "10", "none"),
                       levels = c("2", "3", "4", "5", "10", "none"))
dec_z <- (grain$rej[5] - 0.05) / grain$se_rej[5]
round(setNames(grain$rej, grain$groups), 4)

## ---- figcut ----
cut_curve <- data.frame(q = seq(0.06, 0.94, length.out = 200))
cut_curve$rej <- rej_closed(n_plot, rho_base, b_open, sde_base, leak_q(cut_curve$q))

p_cut <- ggplot(cut_sweep, aes(q, rej)) +
  geom_line(data = cut_curve, aes(q, rej), colour = te_ink, linewidth = 0.4) +
  geom_point(size = 2.6, colour = te_rust) +
  scale_y_continuous(limits = c(0.8, 1)) +
  labs(x = "cut quantile of openness", y = "share with p < 0.05",
       title = "Where you cut", subtitle = "the median is the shallowest point") +
  theme_datasheet()

p_grain <- ggplot(grain, aes(groups, rej)) +
  geom_hline(yintercept = 0.05, linetype = "dashed", colour = te_body, linewidth = 0.5) +
  geom_point(size = 2.8, colour = te_forest) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "groups openness is cut into", y = "share with p < 0.05",
       title = "How many pieces", subtitle = "none: openness as measured") +
  theme_datasheet()

p_cut + p_grain + plot_annotation(theme = theme_datasheet())
