# Collider bias and selection
# https://tidyecology.com/posts/collider-bias-and-selection/
#
# 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

## ---- setup ----
library(ggplot2)
paper <- "#f5f4ee"; ink <- "#16241d"; body <- "#2c3a31"
forest <- "#275139"; faint <- "#5d6b61"; line_col <- "#dad9ca"
red <- "#b5534e"; green <- "#2f8f63"
theme_te <- function(base_size = 12){
  theme_minimal(base_size = base_size) +
    theme(plot.background = element_rect(fill = paper, colour = NA),
          panel.background = element_rect(fill = paper, colour = NA),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = line_col, linewidth = 0.3),
          text = element_text(colour = body),
          plot.title = element_text(colour = ink, face = "bold"),
          plot.subtitle = element_text(colour = faint),
          axis.text = element_text(colour = faint),
          strip.text = element_text(colour = ink, face = "bold"),
          legend.position = "top")
}

## ---- collider-continuous ----
set.seed(160)
n <- 2000
X <- rnorm(n)                       # trait 1, no link to Y
Y <- rnorm(n)                       # trait 2
C <- X + Y + rnorm(n, 0, 0.5)       # a common effect of both

m_correct  <- lm(Y ~ X)             # correct: leaves the collider alone
m_collider <- lm(Y ~ X + C)         # wrong: conditions on the collider
b_corr <- coef(m_correct)["X"];  ci_corr <- confint(m_correct)["X", ]
b_coll <- coef(m_collider)["X"]; ci_coll <- confint(m_collider)["X", ]

## ---- fig-collider-scatter ----
set.seed(1600)
npop <- 4000
Xs <- rnorm(npop)                    # body size
Ys <- rnorm(npop)                    # boldness (independent of size)
det <- rbinom(npop, 1, plogis(-0.4 + 1.2 * Xs + 1.2 * Ys)) == 1
cor_full <- cor(Xs, Ys); cor_det <- cor(Xs[det], Ys[det])

d1 <- rbind(data.frame(x = Xs, y = Ys, set = "whole population"),
            data.frame(x = Xs[det], y = Ys[det], set = "detected sample only"))
d1$set <- factor(d1$set, levels = c("whole population", "detected sample only"))
ggplot(d1, aes(x, y)) +
  geom_point(alpha = 0.18, colour = forest, size = 0.7) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE, colour = red, linewidth = 1) +
  facet_wrap(~set) +
  labs(x = "body size", y = "boldness",
       title = "Selection on a common effect fabricates a correlation",
       subtitle = "two independent traits; the trap keeps animals high on either one") +
  theme_te()

## ---- m-bias ----
set.seed(16000)
nm <- 3000
U1 <- rnorm(nm); U2 <- rnorm(nm)
Xm <- 0.9 * U1 + rnorm(nm, 0, 0.6)                 # X <- U1
Cm <- 0.9 * U1 + 0.9 * U2 + rnorm(nm, 0, 0.6)      # C <- U1, C <- U2 (pre-treatment)
Ym <- 0.9 * U2 + rnorm(nm, 0, 0.6)                 # Y <- U2
m_corr2 <- lm(Ym ~ Xm);      b_m_corr <- coef(m_corr2)["Xm"]
m_mbias <- lm(Ym ~ Xm + Cm); b_m_coll <- coef(m_mbias)["Xm"]; ci_m_coll <- confint(m_mbias)["Xm", ]

## ---- fig-collider-estimates ----
fig2 <- data.frame(
  model = factor(c("Y ~ X\n(unadjusted)", "Y ~ X + C\n(collider)", "Y ~ X + C\n(M-bias)"),
                 levels = c("Y ~ X\n(unadjusted)", "Y ~ X + C\n(collider)", "Y ~ X + C\n(M-bias)")),
  est = c(b_corr, b_coll, b_m_coll),
  lo  = c(ci_corr[1], ci_coll[1], ci_m_coll[1]),
  hi  = c(ci_corr[2], ci_coll[2], ci_m_coll[2]),
  kind = c("right", "wrong", "wrong"))
ggplot(fig2, aes(model, est, colour = kind)) +
  geom_hline(yintercept = 0, linetype = "dashed", colour = ink) +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.16, linewidth = 0.8) +
  geom_point(size = 3) +
  scale_colour_manual(values = c(right = green, wrong = red), guide = "none") +
  labs(x = NULL, y = "estimated effect of X on Y",
       title = "Adjusting for a collider invents an effect that is not there",
       subtitle = "true effect = 0 (dashed line)") +
  theme_te()

## ---- type-one ----
set.seed(21600)
nsim <- 2000; nn <- 300
sig_un <- sig_co <- sig_mb <- logical(nsim)
for (i in seq_len(nsim)) {
  x <- rnorm(nn); y <- rnorm(nn); cc <- x + y + rnorm(nn, 0, 0.5)
  sig_un[i] <- summary(lm(y ~ x))$coefficients["x", "Pr(>|t|)"] < 0.05
  sig_co[i] <- summary(lm(y ~ x + cc))$coefficients["x", "Pr(>|t|)"] < 0.05
  u1 <- rnorm(nn); u2 <- rnorm(nn)
  xm <- 0.9 * u1 + rnorm(nn, 0, 0.6)
  cm <- 0.9 * u1 + 0.9 * u2 + rnorm(nn, 0, 0.6)
  ym <- 0.9 * u2 + rnorm(nn, 0, 0.6)
  sig_mb[i] <- summary(lm(ym ~ xm + cm))$coefficients["xm", "Pr(>|t|)"] < 0.05
}
