# Checking causal assumptions
# https://tidyecology.com/posts/checking-causal-assumptions/
#
# 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-07

## ---- setup ----
library(ggplot2)
paper <- "#f5f4ee"; ink <- "#16241d"; body <- "#2c3a31"
forest <- "#275139"; faint <- "#5d6b61"; line_col <- "#dad9ca"
red <- "#b5534e"; green <- "#2f8f63"; gold <- "#cda23f"
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")
}

## ---- negative-control ----
true_eff <- 0.5; n <- 400
set.seed(162)                                  # Scenario A: unconfounded
XA <- rnorm(n)
YA <- true_eff * XA + rnorm(n, 0, 1)           # only X drives Y
NA_ <- rnorm(n, 0, 1)                            # placebo: nothing links it to X
mA  <- lm(YA ~ XA);  ncA <- lm(NA_ ~ XA)
sA  <- coef(mA)["XA"];  ciA  <- confint(mA)["XA", ]
ncA_c <- coef(ncA)["XA"]; ci_ncA <- confint(ncA)["XA", ]

set.seed(1620)                                  # Scenario B: an unmeasured confounder U
U  <- rnorm(n)
XB <- 0.9 * U + rnorm(n, 0, 0.6)
YB <- true_eff * XB + 0.9 * U + rnorm(n, 0, 1)  # true effect still 0.5, plus confounding
NB <- 0.9 * U + rnorm(n, 0, 1)                   # placebo: driven by U, NOT by X
mB  <- lm(YB ~ XB);  ncB <- lm(NB ~ XB)
sB  <- coef(mB)["XB"];  ciB  <- confint(mB)["XB", ]
ncB_c <- coef(ncB)["XB"]; ci_ncB <- confint(ncB)["XB", ]
corrected_B <- sB - ncB_c                        # subtract the bias the control reveals

## ---- fig-negative-control ----
f1 <- data.frame(
  scen = factor(rep(c("unconfounded", "confounded"), each = 2), levels = c("unconfounded", "confounded")),
  what = factor(rep(c("primary\nX -> Y", "negative control\nX -> N"), 2),
                levels = c("primary\nX -> Y", "negative control\nX -> N")),
  est = c(sA, ncA_c, sB, ncB_c),
  lo  = c(ciA[1], ci_ncA[1], ciB[1], ci_ncB[1]),
  hi  = c(ciA[2], ci_ncA[2], ciB[2], ci_ncB[2]))
ggplot(f1, aes(what, est, colour = what)) +
  geom_hline(yintercept = 0, colour = line_col, linewidth = 0.5) +
  geom_hline(yintercept = true_eff, linetype = "dashed", colour = ink) +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.14, linewidth = 0.8) +
  geom_point(size = 3) +
  facet_wrap(~scen) +
  scale_colour_manual(values = c("primary\nX -> Y" = forest, "negative control\nX -> N" = red), guide = "none") +
  labs(x = NULL, y = "estimated coefficient",
       title = "A negative control flags confounding the primary estimate hides",
       subtitle = "dashed line: true effect (0.5); the control should be zero if unconfounded") +
  theme_te()

## ---- robustness-value ----
rv_from_t <- function(tval, df, q = 1){          # Cinelli & Hazlett (2020)
  f <- q * abs(tval) / sqrt(df); 0.5 * (sqrt(f^4 + 4 * f^2) - f^2)
}
tA <- summary(mA)$coefficients["XA", "t value"]; rvA <- rv_from_t(tA, df.residual(mA))
tB <- summary(mB)$coefficients["XB", "t value"]; rvB <- rv_from_t(tB, df.residual(mB))
adj_curve <- function(est, se, df, r) sign(est) * (abs(est) - se * sqrt(df) * (r / sqrt(1 - r)))
seA <- summary(mA)$coefficients["XA", "Std. Error"]
seB <- summary(mB)$coefficients["XB", "Std. Error"]

## ---- fig-robustness ----
rgrid <- seq(0, 0.85, by = 0.005)
dfc <- rbind(
  data.frame(r = rgrid, adj = adj_curve(sA, seA, df.residual(mA), rgrid), scen = "unconfounded"),
  data.frame(r = rgrid, adj = adj_curve(sB, seB, df.residual(mB), rgrid), scen = "confounded"))
cross <- data.frame(scen = c("unconfounded", "confounded"), rv = c(rvA, rvB), y = 0,
                    lab = sprintf("RV = %.2f", c(rvA, rvB)))
ggplot(dfc, aes(r, adj, colour = scen)) +
  geom_hline(yintercept = 0, colour = ink, linewidth = 0.4) +
  geom_line(linewidth = 1) +
  geom_point(data = cross, aes(rv, y, colour = scen), size = 3, inherit.aes = FALSE) +
  geom_text(data = cross, aes(rv + 0.015, y + 0.12, label = lab, colour = scen), hjust = 0,
            size = 3.1, inherit.aes = FALSE, show.legend = FALSE) +
  scale_colour_manual(values = c("unconfounded" = green, "confounded" = red), name = NULL) +
  labs(x = "assumed strength of unmeasured confounding (share of residual variance)",
       y = "bias-adjusted estimate",
       title = "The robustness value is where the adjusted estimate hits zero",
       subtitle = "further right means more confounding is needed to overturn the estimate") +
  theme_te()
