# Regression discontinuity design
# https://tidyecology.com/posts/regression-discontinuity-design/
#
# 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-01

## ---- setup ----
library(ggplot2); library(dplyr)
paper<-"#f5f4ee"; ink<-"#16241d"; body<-"#2c3a31"; forest<-"#275139"
sage<-"#93a87f"; line<-"#dad9ca"; faint<-"#5d6b61"; gold<-"#cda23f"; brick<-"#b5534e"
theme_te <- function(base=12) theme_minimal(base_size=base) +
  theme(plot.background=element_rect(fill=paper,colour=NA),
        panel.background=element_rect(fill=paper,colour=NA),
        panel.grid.major=element_line(colour=line,linewidth=0.3),
        panel.grid.minor=element_blank(),
        axis.text=element_text(colour=body), axis.title=element_text(colour=ink),
        plot.title=element_text(colour=ink,face="bold"),
        plot.subtitle=element_text(colour=faint), legend.position="top")

## ---- data ----
set.seed(4164)
n <- 1200; tau <- 0.8; c0 <- 0
xr <- runif(n, -1, 1)                 # running variable, centred at the cutoff
D  <- as.integer(xr >= c0)            # treatment switches on at the line
Y  <- 2 + 0.9*xr + 1.1*xr*abs(xr) + tau*D + rnorm(n, 0, 0.35)

## ---- naive ----
naive_diff <- mean(Y[D==1]) - mean(Y[D==0])
gl <- lm(Y ~ D + xr); naive_lin <- coef(gl)["D"]; ci_lin <- confint(gl)["D", ]

## ---- local ----
ll <- function(h){
  keep <- abs(xr - c0) <= h
  w    <- 1 - abs(xr[keep] - c0)/h        # triangular kernel weights
  d    <- data.frame(Y=Y[keep], D=D[keep], x=xr[keep]-c0)
  m    <- lm(Y ~ D*x, data=d, weights=w)  # separate intercept and slope each side
  list(tau=unname(coef(m)["D"]),
       se =unname(summary(m)$coef["D","Std. Error"]), nobs=sum(keep))
}
h0 <- 0.5; e0 <- ll(h0)
ci0 <- e0$tau + c(-1,1)*1.96*e0$se

## ---- fig-rdd ----
cf <- coef(lm(Y ~ D*I(xr-c0), weights=ifelse(abs(xr-c0)<=h0, 1-abs(xr-c0)/h0, 0),
              subset=abs(xr-c0)<=h0))
gridL <- data.frame(x=seq(-h0,0,length=50)); gridL$y <- cf[1] + cf[3]*gridL$x
gridR <- data.frame(x=seq(0,h0,length=50));  gridR$y <- (cf[1]+cf[2]) + (cf[3]+cf[4])*gridR$x
bins <- data.frame(xr=xr, Y=Y, D=D) %>%
  mutate(b=cut(xr, breaks=seq(-1,1,by=0.1))) %>%
  group_by(b) %>% summarise(mx=mean(xr), my=mean(Y), D=first(D), .groups="drop")
jumpL <- cf[1]; jumpR <- cf[1]+cf[2]
ggplot() +
  geom_point(data=data.frame(xr=xr,Y=Y,D=factor(D)), aes(xr,Y,colour=D), alpha=0.10, size=0.7) +
  geom_point(data=bins, aes(mx,my,colour=factor(D)), size=2.4) +
  geom_line(data=gridL, aes(x,y), colour=ink, linewidth=0.9) +
  geom_line(data=gridR, aes(x,y), colour=ink, linewidth=0.9) +
  geom_vline(xintercept=0, linetype="dashed", colour=faint, linewidth=0.4) +
  geom_segment(aes(x=0,xend=0,y=jumpL,yend=jumpR), colour=gold, linewidth=1.2) +
  annotate("text", x=0.06, y=(jumpL+jumpR)/2, label="jump", hjust=0, colour=gold, size=3.4) +
  scale_colour_manual(values=c("0"=brick,"1"=forest),
                      labels=c("below cutoff","at/above cutoff"), name=NULL) +
  labs(x="running variable (centred at cutoff)", y="outcome",
       title="The treatment effect is the jump at the threshold",
       subtitle="Binned means and local-linear fits either side; the gap at the cutoff is the estimate") +
  theme_te()

## ---- sweep ----
hs <- seq(0.15, 1.0, by=0.05)
sw <- lapply(hs, function(h){ e <- ll(h); data.frame(h=h, tau=e$tau, se=e$se) }) %>%
  bind_rows()

## ---- fig-bandwidth ----
ggplot(sw, aes(h, tau)) +
  geom_ribbon(aes(ymin=tau-1.96*se, ymax=tau+1.96*se), fill=sage, alpha=0.30) +
  geom_hline(yintercept=tau, linetype="dashed", colour=forest, linewidth=0.5) +
  geom_line(colour=ink, linewidth=0.7) + geom_point(colour=forest, size=1.9) +
  annotate("text", x=0.9, y=tau+0.03, label="true effect", hjust=1, colour=forest, size=3.3) +
  labs(x="bandwidth (half-width of the window around the cutoff)",
       y="estimated jump (with 95% interval)",
       title="The estimate depends on the bandwidth",
       subtitle="Too narrow: noisy. Too wide: the curved trend leaks in and biases the jump") +
  theme_te()

## ---- coverage ----
set.seed(8164); nsim <- 500
res <- t(sapply(1:nsim, function(i){
  xr <- runif(n,-1,1); D <- as.integer(xr>=0)
  Y  <- 2 + 0.9*xr + 1.1*xr*abs(xr) + tau*D + rnorm(n,0,0.35)
  gl <- lm(Y~D+xr); bl <- coef(gl)["D"]; cl <- confint(gl)["D",]
  keep <- abs(xr)<=h0; w <- 1-abs(xr[keep])/h0
  m  <- lm(Y~D*x, data=data.frame(Y=Y[keep],D=D[keep],x=xr[keep]), weights=w)
  bh <- coef(m)["D"]; se <- summary(m)$coef["D","Std. Error"]; ch <- bh+c(-1,1)*1.96*se
  c(lin_cov=unname(tau>=cl[1]&tau<=cl[2]), loc_cov=unname(tau>=ch[1]&tau<=ch[2]))
}))
cov_lin <- mean(res[,"lin_cov"]); cov_loc <- mean(res[,"loc_cov"])

## ---- mccrary ----
set.seed(2164)
mcc <- function(x){
  win <- 0.1; lo <- sum(x>=-win & x<0); hi <- sum(x>=0 & x<win)
  bt  <- binom.test(hi, lo+hi, 0.5)
  c(lo=lo, hi=hi, ratio=hi/lo, p=bt$p.value)
}
xr_clean <- runif(n,-1,1); xr_manip <- xr_clean
idx <- which(xr_clean >= -0.1 & xr_clean < 0)
mv  <- sample(idx, round(0.6*length(idx)))
xr_manip[mv] <- abs(xr_manip[mv])
mc_clean <- mcc(xr_clean); mc_manip <- mcc(xr_manip)
