Skip to content

Regression discontinuity

When a cutoff decides treatment, compare units close to it on either side, and test what could undermine the comparison.

Advanced ~13 min9 steps

What runs in CodeSplash

You will be able to

  • Say why units near a cutoff are comparable, and what would break that
  • Weigh bias against variance when you choose a bandwidth
  • Read a fuzzy design as an effect for compliers at the cutoff

Read first

01

A rule creates an experiment

Read

A scholarship goes to students above a test score. A student one point above the line and one point below are nearly the same, apart from that bit of luck.

That's a regression discontinuityRegression discontinuityEstimates an effect from the jump in outcomes at a cut-off that decides treatment.. The score is the running variableRunning variableThe score whose cutoff decides treatment in a regression discontinuity design.. Without treatment, the outcome should change smoothly across the cutoff, so a sudden jump there is the effect.

The key assumption is that smoothness. It can fail if people can place themselves precisely on one side.

02

Does winning help next time?

Predict

Predict first

Senate candidates who barely win an election are compared with those who barely lose. How much higher, in percentage points, is their party's vote share next time?

No jumpA jump of 5 to 10 pointsA jump of more than 20 points
Reveal

The estimated jump is 7.41 points, with a robust interval from 4.09 to 10.9. It uses 360 races below the cutoff and 323 above, out of 1,297.

03

See the jump

In the app
Sharp regression discontinuityRecorded · Python and R agreeRecorded 2026-11-17 · 38 values compared
R

τ = 7.41, robust 95% CI [4.09, 10.92], p < .001, h = 17.75

Discontinuity
7.414
Robust 95% CI
[4.094, 10.919]
p (robust)
< .001
Bandwidth
17.754

Plots

vote around the cutoffDoes the outcome jump where the running variable crosses the cutoff?
View data
margin (fit)vote (local fit)kindsidemarginvote
——binbelow−99.68033.928
——binbelow−94.5420
——binbelow−86.61840.624
——binbelow−82.64646.862
——binbelow−79.32343.499
——binbelow−67.11031.884
——binbelow−62.18033.846
——binbelow−56.49229.446
——binbelow−52.34030.552
——binbelow−47.39633.690
——binbelow−42.34731.986
——binbelow−36.92734.465
——binbelow−32.40934.036
——binbelow−27.47538.765
——binbelow−22.69739.431
——binbelow−17.33142.747
——binbelow−12.34741.692
——binbelow−7.48443.899
——binbelow−2.55344.985
——binabove2.52452.772
——binabove7.66655.819
——binabove12.39954.741
——binabove17.36058.376
——binabove22.65456.948
——binabove27.48259.194
——binabove32.24562.252
——binabove37.15364.137
——binabove41.65165.182
——binabove47.25870.312
——binabove52.54977.070
——binabove57.87980.059
——binabove62.81869.813
——binabove67.14371.240
——binabove72.48590.659
——binabove77.14087.144
——binabove83.61365.455
——binabove87.47687.788
——binabove91.61885.604
——binabove99.87789.434
−17.75442.263fitbelow——
−17.39242.322fitbelow——
−17.03042.382fitbelow——
−16.66742.441fitbelow——
−16.30542.501fitbelow——
−15.94342.560fitbelow——
−15.58042.619fitbelow——
−15.21842.679fitbelow——
−14.85642.738fitbelow——
−14.49342.797fitbelow——
−14.13142.857fitbelow——
−13.76942.916fitbelow——
−13.40642.976fitbelow——
−13.04443.035fitbelow——
−12.68243.094fitbelow——
−12.31943.154fitbelow——
−11.95743.213fitbelow——
−11.59543.273fitbelow——
−11.23243.332fitbelow——
−10.87043.391fitbelow——
−10.50843.451fitbelow——

First 60 of 139 rows.

Assumptions

  • No manipulation of the running variable — No jump in the density of margin at the cutoff (rddensity p = .447).
  • Placebo cutoffs — No jump at the placebo cutoffs (medians of each side).
  • Bandwidth sensitivity — Half and double bandwidths give estimates of the same sign.
  • Local effect — The estimate applies to units with margin near 0; extrapolating it away from the cutoff needs further assumptions.

rdrobust (p = 1, triangular kernel, mserd bandwidth)

EstimateValueSEpLowerUpper
Conventional7.4141.4593.722e-74.55510.273
Bias-corrected7.5071.4592.661e-74.64710.366
Robust7.5071.7411.625e-54.09410.919
The exact R script · R R version 4.5.1 (2025-06-13)
# Regression discontinuity (sharp / fuzzy)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.rdd 1.0.2 · spec e3efed1d1fcbc910
# Dataset: c1_senate (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
library(rdrobust)
library(rddensity)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_senate.parquet", col_select = c("vote", "margin")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("vote", "margin")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("vote", "margin"))  # infinite values stop the run (registry/errors.yaml)

# %% Design
Y <- "vote"
RUN <- "margin"
TREAT <- NULL
COVARIATES <- c()
CLUSTER <- NULL
cutoff <- 0
p_order <- as.integer(1)
kernel <- "triangular"
bwselect <- "mserd"
h_manual <- NULL
donut <- 0
robustness <- TRUE
nbins <- as.integer(20)
conf <- 0.95

numeric_of <- function(col) {
  v <- df[[col]]
  if (is.factor(v)) {
    lv <- levels(v)
    return(as.numeric(as.character(v) == if ("true" %in% lv) "true" else lv[length(lv)]))
  }
  as.numeric(v)
}

keep <- if (donut > 0) abs(as.numeric(df[[RUN]]) - cutoff) >= donut else rep(TRUE, nrow(df))
if (donut > 0 && any(!keep)) warnings <- c(warnings, sprintf("%d observations within %s of the cutoff were left out (donut).", sum(!keep), format(donut)))
d <- df[keep, , drop = FALSE]
y <- as.numeric(d[[Y]])
x <- as.numeric(d[[RUN]])
tr <- if (!is.null(TREAT)) numeric_of(TREAT)[keep] else NULL
cl <- if (!is.null(CLUSTER)) match(as.character(d[[CLUSTER]]), unique(as.character(d[[CLUSTER]]))) else NULL
# The local fits need at least 10 observations on each side of the cutoff.
sides <- list(  # %g prints the cutoff as Python's :g does
  list(sprintf("%s < %g", RUN, cutoff), sum(x < cutoff)),
  list(sprintf("%s ≥ %g", RUN, cutoff), sum(x >= cutoff))
)
for (side in sides) {
  if (side[[2]] < 10) cs_error("CS_E_SMALL_GROUP", min = 10, group = side[[1]], n = side[[2]])
}
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = Y)
vce <- if (!is.null(CLUSTER)) "cr1" else "nn"  # pinned (rdrobust defaults differ by whether a cluster is given)

rd <- function(outcome, xx = x, c = cutoff, h = h_manual, fuzzy = NULL, cluster = cl) {
  args <- list(y = outcome, x = xx, c = c, p = p_order, kernel = kernel, vce = vce, level = conf * 100)
  if (!is.null(h)) args$h <- h else args$bwselect <- bwselect
  if (!is.null(fuzzy)) args$fuzzy <- fuzzy
  if (!is.null(cluster)) args$cluster <- cluster
  do.call(rdrobust, args)
}

# %% Estimate: local polynomial RD with robust bias-corrected inference (rdrobust)
r <- rd(y, fuzzy = tr)
coef_v <- as.numeric(r$coef)
se_all <- as.numeric(r$se)
pv <- as.numeric(r$pv)
ci <- unname(r$ci)
est <- coef_v[1]
est_bc <- coef_v[2]
se <- se_all[1]
se_rb <- se_all[3]
p_rb <- pv[3]
ci_low <- ci[3, 1]
ci_high <- ci[3, 2]
h_l <- r$bws[1, 1]; h_r <- r$bws[1, 2]; b_l <- r$bws[2, 1]; b_r <- r$bws[2, 2]
n_left <- r$N_h[1]; n_right <- r$N_h[2]

# %% Robustness battery
values_extra <- list()
checks <- list()
add_check <- function(...) checks[[length(checks) + 1]] <<- list(...)
if (!is.null(TREAT)) {
  fs <- rd(tr, h = c(h_l, h_r))
  fs_est <- as.numeric(fs$coef)[1]
  fs_f <- (fs_est / as.numeric(fs$se)[1])^2
  values_extra$first_stage <- fs_est
  values_extra$first_stage_p <- as.numeric(fs$pv)[3]
  values_extra$first_stage_f <- fs_f
  if (fs_f < 10) {
    add_check(id = "first_stage", label = "Jump in treatment take-up", status = "fail", downgrade_to = "L1",
              detail = sprintf("Take-up jumps by %.3f at the cutoff (F = %.1f < 10): a weak first stage makes the fuzzy estimate unreliable.", fs_est, fs_f))
  } else {
    add_check(id = "first_stage", label = "Jump in treatment take-up", status = "pass",
              detail = sprintf("Take-up jumps by %.3f at the cutoff (F = %.1f).", fs_est, fs_f))
  }
}
if (robustness) {
  dens <- rddensity(X = x, c = cutoff)
  values_extra$density_t <- dens$test$t_jk
  values_extra$density_p <- dens$test$p_jk
  if (dens$test$p_jk < 0.05) {
    add_check(id = "density", label = "No manipulation of the running variable", status = "concern", downgrade_to = "L1",
              detail = sprintf("The density of %s jumps at the cutoff (rddensity %s): units may sort around it.", RUN, cs_fmt_p(dens$test$p_jk)))
  } else {
    add_check(id = "density", label = "No manipulation of the running variable", status = "pass",
              detail = sprintf("No jump in the density of %s at the cutoff (rddensity %s).", RUN, cs_fmt_p(dens$test$p_jk)))
  }
  bal_bad <- character(0)
  for (cv in COVARIATES) {
    rb <- rd(numeric_of(cv)[keep])
    values_extra[[sprintf("balance_estimate[%s]", cv)]] <- as.numeric(rb$coef)[1]
    bp <- as.numeric(rb$pv)[3]
    values_extra[[sprintf("balance_p[%s]", cv)]] <- bp
    if (bp < 0.05) bal_bad <- c(bal_bad, cv)
  }
  if (length(COVARIATES)) {
    add_check(id = "balance", label = "Covariate balance at the cutoff", status = if (length(bal_bad)) "concern" else "pass",
              detail = if (length(bal_bad)) sprintf("%s jump%s at the cutoff (p < .05): units on either side differ in more than treatment.", paste(bal_bad, collapse = ", "), if (length(bal_bad) == 1) "s" else "")
                       else sprintf("None of %s jumps at the cutoff (all p ≥ .05).", paste(COVARIATES, collapse = ", ")))
  }
  placebo_ps <- numeric(0)
  for (side in c("left", "right")) {
    sel <- if (side == "left") x < cutoff else x >= cutoff
    xs <- x[sel]; ys <- y[sel]
    c_pl <- unname(quantile(xs, 0.5, type = 7))
    if (sum(xs < c_pl) >= 10 && sum(xs >= c_pl) >= 10) {
      rp <- tryCatch(rd(ys, xx = xs, c = c_pl, h = NULL, cluster = if (!is.null(cl)) cl[sel] else NULL), error = function(e) e)
      if (inherits(rp, "error")) {
        warnings <- c(warnings, sprintf("Placebo cutoff on the %s: %s", side, conditionMessage(rp)))
      } else {
        values_extra[[sprintf("placebo_%s_cutoff", side)]] <- c_pl
        values_extra[[sprintf("placebo_%s_estimate", side)]] <- as.numeric(rp$coef)[1]
        pp <- as.numeric(rp$pv)[3]
        values_extra[[sprintf("placebo_%s_p", side)]] <- pp
        placebo_ps <- c(placebo_ps, pp)
      }
    }
  }
  if (length(placebo_ps)) {
    values_extra$placebo_p <- min(placebo_ps)
    add_check(id = "placebo", label = "Placebo cutoffs", status = if (min(placebo_ps) < 0.05) "concern" else "pass",
              detail = if (min(placebo_ps) < 0.05) "A jump appears at a placebo cutoff (median of one side, p < .05): the outcome may be discontinuous for other reasons."
                       else "No jump at the placebo cutoffs (medians of each side).")
  }
  flips <- character(0)
  for (nm in c("half", "double")) {
    f <- if (nm == "half") 0.5 else 2
    rs <- tryCatch(rd(y, h = c(h_l * f, h_r * f), fuzzy = tr), error = function(e) e)
    if (inherits(rs, "error")) {
      warnings <- c(warnings, sprintf("Bandwidth × %s: %s", format(f), conditionMessage(rs)))
    } else {
      values_extra[[sprintf("%s_bw_estimate", nm)]] <- as.numeric(rs$coef)[1]
      values_extra[[sprintf("%s_bw_p", nm)]] <- as.numeric(rs$pv)[3]
      if (sign(as.numeric(rs$coef)[1]) != sign(est)) flips <- c(flips, nm)
    }
  }
  add_check(id = "bandwidth", label = "Bandwidth sensitivity", status = if (length(flips)) "concern" else "pass",
            detail = if (length(flips)) sprintf("The estimate changes sign with the %s bandwidth: the result depends on the bandwidth.", paste(flips, collapse = " and "))
                     else "Half and double bandwidths give estimates of the same sign.")
}
add_check(id = "local", label = "Local effect", status = "info",
          detail = sprintf("The estimate applies to units with %s near %s; extrapolating it away from the cutoff needs further assumptions.", RUN, format(cutoff)))

# %% Result
bin_rows <- cs_causal_rdd_bins(x, y, cutoff, nbins)
fit_rows <- cs_causal_rdd_local_fit(x, y, cutoff, h_l, h_r, p_order, kernel)
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.rdd/senate-sharp/out-r")
nanoparquet::write_parquet(bin_rows, file.path(out, "rdd_bins.parquet"))
artifacts <- list(list(key = "bins", path = file.path(out, "rdd_bins.parquet"), format = "parquet", title = "Binned means on each side of the cutoff"))
chart_rows <- rbind(data.frame(x = bin_rows$x, y = bin_rows$y, side = bin_rows$side, kind = "bin"),
                    if (!is.null(fit_rows)) data.frame(x = fit_rows$x, y = fit_rows$y, side = fit_rows$side, kind = "fit"))
fuzzy <- !is.null(TREAT)
pct <- sprintf("%.0f%%", conf * 100)
g3 <- function(v) formatC(v, digits = 3, format = "g")
summary <- sprintf("At the cutoff %s of %s, %s jumps by %s (robust bias-corrected %s CI [%s, %s], %s), using %d observations below and %d above within a bandwidth of %s.",
                   format(cutoff), RUN, Y, g3(est), pct, g3(ci_low), g3(ci_high), cs_fmt_p(p_rb), n_left, n_right, g3(h_l))
if (!is.null(values_extra$density_p)) {
  summary <- paste(summary, if (values_extra$density_p < 0.05) sprintf("The density of %s jumps at the cutoff (%s), a sign of manipulation.", RUN, cs_fmt_p(values_extra$density_p))
                   else sprintf("There is no sign of manipulation of %s (%s).", RUN, cs_fmt_p(values_extra$density_p)))
}
values <- list(
  estimate = est, estimate_bc = est_bc, se = se, se_robust = se_rb, p_value = p_rb, ci_low = ci_low, ci_high = ci_high,
  n = r$N[1] + r$N[2], n_left = n_left, n_right = n_right, bandwidth = h_l, bandwidth_right = h_r,
  b_left = b_l, b_right = b_r, cutoff = cutoff, fuzzy = fuzzy, p_order = p_order, kernel = kernel,
  estimand = if (fuzzy) "Local ATE for compliers at the cutoff" else "Local ATE at the cutoff",
  effect_label = if (fuzzy) sprintf("Effect of %s on %s for units at the cutoff whose take-up the cutoff changes", TREAT, Y)
                 else sprintf("Jump in %s at %s = %s", Y, RUN, format(cutoff)),
  claim_level_max = "L3"
)
values <- c(values, values_extra)
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
est_rows <- data.frame(estimate = c("Conventional", "Bias-corrected", "Robust"), value = coef_v, se = se_all, p = pv, low = ci[, 1], high = ci[, 2])
cs_publish(list(
  method = "causal.rdd",
  methodVersion = "1.0.2",
  title = paste(if (fuzzy) "Fuzzy" else "Sharp", "regression discontinuity"),
  engine = cs_engine_info("rdrobust", "rddensity", "nanoparquet"),
  n = values$n,
  summary = summary,
  apa = sprintf("τ = %s, robust %s CI [%s, %s], %s, h = %s", cs_fmt_num(est), pct, cs_fmt_num(ci_low), cs_fmt_num(ci_high), cs_fmt_p(p_rb), cs_fmt_num(h_l)),
  statistics = list(
    list(key = "estimate", label = "Discontinuity", value = est),
    list(key = "ci", label = sprintf("Robust %s CI", pct), value = c(ci_low, ci_high)),
    list(key = "p_value", label = "p (robust)", value = p_rb, format = "p"),
    list(key = "bandwidth", label = "Bandwidth", value = h_l)
  ),
  tables = list(list(key = "estimates", title = sprintf("rdrobust (p = %d, %s kernel, %s bandwidth)", p_order, kernel, if (is.null(h_manual)) bwselect else "manual"),
                     columns = list(list(key = "estimate", label = "Estimate", type = "string"), list(key = "value", label = "Value", type = "number"),
                                    list(key = "se", label = "SE", type = "number"), list(key = "p", label = "p", type = "p"),
                                    list(key = "low", label = "Lower", type = "number"), list(key = "high", label = "Upper", type = "number")),
                     rows = est_rows)),
  assumptions = lapply(checks, function(c) list(key = c$id, label = c$label, status = if (c$status == "concern") "warn" else c$status, detail = c$detail)),
  checks = checks,
  warnings = warnings,
  values = values,
  artifacts = artifacts,
  charts = list(cs_chart("rdd", "rdd-plot", sprintf("%s around the cutoff", Y), list(
    x = cs_col(RUN, ifelse(chart_rows$kind == "bin", chart_rows$x, NA_real_), kind = "numeric"),
    y = cs_col(Y, ifelse(chart_rows$kind == "bin", chart_rows$y, NA_real_), kind = "numeric"),
    fit_x = cs_col(sprintf("%s (fit)", RUN), ifelse(chart_rows$kind == "fit", chart_rows$x, NA_real_), kind = "numeric"),
    fit_y = cs_col(sprintf("%s (local fit)", Y), ifelse(chart_rows$kind == "fit", chart_rows$y, NA_real_), kind = "numeric"),
    side = cs_col("side", chart_rows$side, kind = "categorical", levels = c("below", "above")),
    kind = cs_col("kind", chart_rows$kind, kind = "categorical", levels = c("bin", "fit"))
  ), controls = list(cutoff = cutoff)))
))
Python

τ = 7.41, robust 95% CI [4.09, 10.92], p < .001, h = 17.75

Discontinuity
7.414
Robust 95% CI
[4.094, 10.919]
p (robust)
< .001
Bandwidth
17.754

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • No manipulation of the running variable — No jump in the density of margin at the cutoff (rddensity p = .447).
  • Placebo cutoffs — No jump at the placebo cutoffs (medians of each side).
  • Bandwidth sensitivity — Half and double bandwidths give estimates of the same sign.
  • Local effect — The estimate applies to units with margin near 0; extrapolating it away from the cutoff needs further assumptions.

rdrobust (p = 1, triangular kernel, mserd bandwidth)

EstimateValueSEpLowerUpper
Conventional7.4141.4593.722e-74.55510.273
Bias-corrected7.5071.4592.661e-74.64710.366
Robust7.5071.7411.625e-54.09410.919
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Regression discontinuity (sharp / fuzzy)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.rdd 1.0.2 · spec e3efed1d1fcbc910
# Dataset: c1_senate (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import os

import numpy as np
import pandas as pd
from rddensity import rddensity
from rdrobust import rdrobust
from scipy import stats

import codesplash as cs
from codesplash import ml as csml
from codesplash.causal import rdd as csrdd

# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_senate.parquet", columns=["vote", "margin"])
n_input = len(df)
df = df.dropna(subset=["vote", "margin"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["vote", "margin"])  # infinite values stop the run (registry/errors.yaml)

# %% Design
Y, RUN = "vote", "margin"
TREAT = None
COVARIATES = []
CLUSTER = None
cutoff = 0
p_order = int(1)
kernel = "triangular"
bwselect = "mserd"
h_manual = None
donut = 0
robustness = True
nbins = int(20)
conf = 0.95


def numeric(col: str) -> np.ndarray:
    s = df[col]
    if isinstance(s.dtype, pd.CategoricalDtype):
        lv = [str(x) for x in s.cat.categories]
        return (s.astype(str) == ("true" if "true" in lv else lv[-1])).to_numpy(dtype=float)
    return s.to_numpy(dtype=float)


keep = np.abs(df[RUN].to_numpy(dtype=float) - cutoff) >= donut if donut > 0 else np.ones(len(df), dtype=bool)
if donut > 0 and (~keep).any():
    warnings.append(f"{int((~keep).sum())} observations within {donut:g} of the cutoff were left out (donut).")
d = df.loc[keep].reset_index(drop=True)
y = d[Y].to_numpy(dtype=float)
x = d[RUN].to_numpy(dtype=float)
t = numeric(TREAT)[keep] if TREAT else None
cl = pd.factorize(d[CLUSTER].astype(str))[0] + 1 if CLUSTER else None
# The local fits need at least 10 observations on each side of the cutoff.
for side, count in ((f"{RUN} < {cutoff:g}", int((x < cutoff).sum())), (f"{RUN} ≥ {cutoff:g}", int((x >= cutoff).sum()))):
    if count < 10:
        cs.cs_error("CS_E_SMALL_GROUP", min=10, group=side, n=count)
if np.unique(y).size < 2:
    cs.cs_error("CS_E_CONSTANT", column=Y)
vce = "cr1" if CLUSTER else "nn"  # pinned (rdrobust defaults differ by whether a cluster is given)


def rd(outcome, xx=x, c=cutoff, h=h_manual, fuzzy=None, cluster=cl):
    kw = {"c": c, "p": p_order, "kernel": kernel, "vce": vce, "level": conf * 100}
    if h is not None:
        kw["h"] = h
    else:
        kw["bwselect"] = bwselect
    if fuzzy is not None:
        kw["fuzzy"] = fuzzy
    if cluster is not None:
        kw["cluster"] = cluster
    return rdrobust(outcome, xx, **kw)


# %% Estimate: local polynomial RD with robust bias-corrected inference (rdrobust)
r = rd(y, fuzzy=t)
coef = r.coef.to_numpy().ravel()
se_all = r.se.to_numpy().ravel()
pv = r.pv.to_numpy().ravel()
ci = r.ci.to_numpy()
bws = r.bws.to_numpy()  # rows h, b; columns left, right
est, est_bc = float(coef[0]), float(coef[1])
se, se_rb = float(se_all[0]), float(se_all[2])
p_rb = float(pv[2])
ci_low, ci_high = float(ci[2, 0]), float(ci[2, 1])
h_l, h_r, b_l, b_r = float(bws[0, 0]), float(bws[0, 1]), float(bws[1, 0]), float(bws[1, 1])
n_left, n_right = int(r.N_h[0]), int(r.N_h[1])

# %% Robustness battery
values_extra, checks = {}, []
if TREAT:
    fs = rd(t, h=[h_l, h_r], fuzzy=None)
    fs_est, fs_se = float(fs.coef.to_numpy().ravel()[0]), float(fs.se.to_numpy().ravel()[0])
    fs_f = (fs_est / fs_se) ** 2
    values_extra.update({"first_stage": fs_est, "first_stage_p": float(fs.pv.to_numpy().ravel()[2]), "first_stage_f": fs_f})
    if fs_f < 10:
        checks.append({"id": "first_stage", "label": "Jump in treatment take-up", "status": "fail", "downgrade_to": "L1",
                       "detail": f"Take-up jumps by {fs_est:.3f} at the cutoff (F = {fs_f:.1f} < 10): a weak first stage makes the fuzzy estimate unreliable."})
    else:
        checks.append({"id": "first_stage", "label": "Jump in treatment take-up", "status": "pass",
                       "detail": f"Take-up jumps by {fs_est:.3f} at the cutoff (F = {fs_f:.1f})."})
if robustness:
    dens = rddensity(X=x, c=cutoff)
    density_t, density_p = float(dens.test["t_jk"]), float(dens.test["p_jk"])
    values_extra.update({"density_t": density_t, "density_p": density_p})
    if density_p < 0.05:
        checks.append({"id": "density", "label": "No manipulation of the running variable", "status": "concern", "downgrade_to": "L1",
                       "detail": f"The density of {RUN} jumps at the cutoff (rddensity {cs.fmt_p(density_p)}): units may sort around it."})
    else:
        checks.append({"id": "density", "label": "No manipulation of the running variable", "status": "pass",
                       "detail": f"No jump in the density of {RUN} at the cutoff (rddensity {cs.fmt_p(density_p)})."})
    bal_bad = []
    for c in COVARIATES:
        rb = rd(numeric(c)[keep], fuzzy=None)
        values_extra[f"balance_estimate[{c}]"] = float(rb.coef.to_numpy().ravel()[0])
        bp = float(rb.pv.to_numpy().ravel()[2])
        values_extra[f"balance_p[{c}]"] = bp
        if bp < 0.05:
            bal_bad.append(c)
    if COVARIATES:
        checks.append({"id": "balance", "label": "Covariate balance at the cutoff", "status": "concern" if bal_bad else "pass",
                       "detail": (f"{', '.join(bal_bad)} jump{'s' if len(bal_bad) == 1 else ''} at the cutoff (p < .05): units on either side differ in more than treatment." if bal_bad
                                  else f"None of {', '.join(COVARIATES)} jumps at the cutoff (all p ≥ .05).")})
    placebo_ps = []
    for side in ("left", "right"):
        sel = x < cutoff if side == "left" else x >= cutoff
        xs, ys = x[sel], y[sel]
        c_pl = float(np.quantile(xs, 0.5))
        if (xs < c_pl).sum() >= 10 and (xs >= c_pl).sum() >= 10:
            try:
                rp = rd(ys, xx=xs, c=c_pl, h=None, fuzzy=None, cluster=cl[sel] if cl is not None else None)
                values_extra[f"placebo_{side}_cutoff"] = c_pl
                values_extra[f"placebo_{side}_estimate"] = float(rp.coef.to_numpy().ravel()[0])
                pp = float(rp.pv.to_numpy().ravel()[2])
                values_extra[f"placebo_{side}_p"] = pp
                placebo_ps.append(pp)
            except Exception as e:  # too few points near a placebo cutoff
                warnings.append(f"Placebo cutoff on the {side}: {e}")
    if placebo_ps:
        values_extra["placebo_p"] = min(placebo_ps)
        checks.append({"id": "placebo", "label": "Placebo cutoffs", "status": "concern" if min(placebo_ps) < 0.05 else "pass",
                       "detail": ("A jump appears at a placebo cutoff (median of one side, p < .05): the outcome may be discontinuous for other reasons." if min(placebo_ps) < 0.05
                                  else "No jump at the placebo cutoffs (medians of each side).")})
    sens = {}
    for name, f in (("half", 0.5), ("double", 2.0)):
        try:
            rs = rd(y, h=[h_l * f, h_r * f], fuzzy=t)
            sens[name] = (float(rs.coef.to_numpy().ravel()[0]), float(rs.pv.to_numpy().ravel()[2]))
            values_extra[f"{name}_bw_estimate"] = sens[name][0]
            values_extra[f"{name}_bw_p"] = sens[name][1]
        except Exception as e:
            warnings.append(f"Bandwidth × {f:g}: {e}")
    flips = [nm for nm, (e, _) in sens.items() if np.sign(e) != np.sign(est)]
    checks.append({"id": "bandwidth", "label": "Bandwidth sensitivity", "status": "concern" if flips else "pass",
                   "detail": (f"The estimate changes sign with the {' and '.join(flips)} bandwidth: the result depends on the bandwidth." if flips
                              else "Half and double bandwidths give estimates of the same sign.")})
checks.append({"id": "local", "label": "Local effect", "status": "info",
               "detail": f"The estimate applies to units with {RUN} near {cutoff:g}; extrapolating it away from the cutoff needs further assumptions."})

# %% Result
bin_rows = csrdd.bins(x, y, cutoff, nbins)
fit_rows = csrdd.local_fit(x, y, cutoff, h_l, h_r, p_order, kernel)
out = csml.out_dir("target/academy-parity/run-953/causal.rdd/senate-sharp/out-python")
pd.DataFrame(bin_rows).to_parquet(os.path.join(out, "rdd_bins.parquet"), index=False)
artifacts = [{"key": "bins", "path": os.path.join(out, "rdd_bins.parquet"), "format": "parquet", "title": "Binned means on each side of the cutoff"}]
chart_rows = [dict(r, kind="bin") for r in bin_rows] + [dict(r, kind="fit") for r in fit_rows]
fuzzy = TREAT is not None
summary = (
    f"At the cutoff {cutoff:g} of {RUN}, {Y} jumps by {est:.3g} (robust bias-corrected {conf:.0%} CI [{ci_low:.3g}, {ci_high:.3g}], {cs.fmt_p(p_rb)}), "
    f"using {n_left} observations below and {n_right} above within a bandwidth of {h_l:.3g}."
)
if "density_p" in values_extra:
    summary += (f" The density of {RUN} jumps at the cutoff ({cs.fmt_p(values_extra['density_p'])}), a sign of manipulation." if values_extra["density_p"] < 0.05
                else f" There is no sign of manipulation of {RUN} ({cs.fmt_p(values_extra['density_p'])}).")
values = {
    "estimate": est, "estimate_bc": est_bc, "se": se, "se_robust": se_rb, "p_value": p_rb, "ci_low": ci_low, "ci_high": ci_high,
    "n": int(r.N[0]) + int(r.N[1]), "n_left": n_left, "n_right": n_right, "bandwidth": h_l, "bandwidth_right": h_r,
    "b_left": b_l, "b_right": b_r, "cutoff": cutoff, "fuzzy": fuzzy, "p_order": p_order, "kernel": kernel,
    "estimand": "Local ATE for compliers at the cutoff" if fuzzy else "Local ATE at the cutoff",
    "effect_label": (f"Effect of {TREAT} on {Y} for units at the cutoff whose take-up the cutoff changes" if fuzzy
                     else f"Jump in {Y} at {RUN} = {cutoff:g}"),
    "claim_level_max": "L3",
}
values.update(values_extra)
for c in checks:
    values[f"check[{c['id']}]"] = c["status"]
rows = [{"estimate": "Conventional", "value": float(coef[0]), "se": float(se_all[0]), "p": float(pv[0]), "low": float(ci[0, 0]), "high": float(ci[0, 1])},
        {"estimate": "Bias-corrected", "value": float(coef[1]), "se": float(se_all[1]), "p": float(pv[1]), "low": float(ci[1, 0]), "high": float(ci[1, 1])},
        {"estimate": "Robust", "value": float(coef[2]), "se": float(se_all[2]), "p": float(pv[2]), "low": float(ci[2, 0]), "high": float(ci[2, 1])}]
cs.publish({
    "method": "causal.rdd",
    "methodVersion": "1.0.2",
    "title": ("Fuzzy" if fuzzy else "Sharp") + " regression discontinuity",
    "engine": cs.engine_info("pandas", "numpy", "rdrobust", "rddensity"),
    "n": values["n"],
    "summary": summary,
    "apa": f"τ = {cs.fmt_num(est)}, robust {conf:.0%} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}], {cs.fmt_p(p_rb)}, h = {cs.fmt_num(h_l)}",
    "statistics": [
        {"key": "estimate", "label": "Discontinuity", "value": est},
        {"key": "ci", "label": f"Robust {conf:.0%} CI", "value": [ci_low, ci_high]},
        {"key": "p_value", "label": "p (robust)", "value": p_rb, "format": "p"},
        {"key": "bandwidth", "label": "Bandwidth", "value": h_l},
    ],
    "tables": [{"key": "estimates", "title": f"rdrobust (p = {p_order}, {kernel} kernel, {bwselect if h_manual is None else 'manual'} bandwidth)",
                "columns": [{"key": "estimate", "label": "Estimate", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
                            {"key": "se", "label": "SE", "type": "number"}, {"key": "p", "label": "p", "type": "p"},
                            {"key": "low", "label": "Lower", "type": "number"}, {"key": "high", "label": "Upper", "type": "number"}],
                "rows": rows}],
    "assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
    "checks": checks,
    "warnings": warnings,
    "values": values,
    "artifacts": artifacts,
    "charts": [cs.chart("rdd", "rdd-plot", f"{Y} around the cutoff", {
        "x": cs.col(RUN, [r["x"] if r["kind"] == "bin" else None for r in chart_rows], kind="numeric"),
        "y": cs.col(Y, [r["y"] if r["kind"] == "bin" else None for r in chart_rows], kind="numeric"),
        "fit_x": cs.col(f"{RUN} (fit)", [r["x"] if r["kind"] == "fit" else None for r in chart_rows], kind="numeric"),
        "fit_y": cs.col(f"{Y} (local fit)", [r["y"] if r["kind"] == "fit" else None for r in chart_rows], kind="numeric"),
        "side": cs.col("side", [r["side"] for r in chart_rows], kind="categorical", levels=["below", "above"]),
        "kind": cs.col("kind", [r["kind"] for r in chart_rows], kind="categorical", levels=["bin", "fit"]),
    }, controls={"cutoff": cutoff})],
})

The chart shows binned averages and a line fitted on each side. Bins are for display only, and the estimate comes from local fits near the cutoff.

The interval is robust bias-corrected, so it isn't centered on the point estimate. It accounts for the bias of a straight line far from the cutoff.

04

Choose how close to look

Explore

DExplorable · The bandwidth in a regression discontinuity

How close to the cutoff should you look when estimating a jump?

This outcome bends away from a straight line on both sides of the cutoff. If you use the whole range (h = 1), will the local-linear jump be…

How sure?
0.60
1.0

A straight line can't follow this far from the cutoff.

0.50

Fit a line on each side using only |x| ≤ h.

800
cutofftrue jump

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Narrow the bandwidth, then widen it, and raise the curvature. Wide windows bring in more data and more bias. Narrow windows are less biased and noisier.

The app picks a bandwidth from the data, here 17.8 points on each side. It also reruns at half and double: 8.36 and 7.16. They tell a similar story, which is what you hope to see.

05

Try to break it

Reflect

Three checks try to break the design:

  • Density test. A pile-up right above the cutoff suggests sorting. Here: p = .447.
  • Placebo cutoffs. No jump should appear at cutoffs where nothing happens. The more extreme of two: p = .539.
  • Covariate balance. Things settled before the cutoff shouldn't jump at it. That needs balance covariates, and the next example has them.

None of these can establish continuity. Could the people in your own setting know the score, and move it, before the cutoff applied?

06

When the cutoff only nudges

Predict

Predict first

Above a score of 60, students are more likely to get a scholarship, but not certain. The share taking it up jumps by 0.58. What should you make of the raw jump in grades?

It is the effect on everyone at the cutoffIt is too small: divide by the jump in take-upIt is too large: multiply by the jump in take-up
Reveal

In a fuzzy design, the effect is the jump in the outcome divided by the jump in take-up, as in IV. The estimate is 0.456 (p = .002), for compliers at the cutoff. Balance holds: age doesn't jump there, and the first-stage F is 58.0.

07

Check your understanding

Checkpoint

Check yourself

Applicants can retake a test until they pass, and many cluster right above the passing score. What does that threaten?

Show the answer

Answer: b

Sorting breaks the "as good as random" comparison. A density test can flag it. A donut design, which leaves out rows closest to the cutoff, may help, but the assumption stays in doubt.

Check yourself

You estimate that a program raises income for people right at the eligibility age of 65. May you say what it would do for 40-year-olds?

Show the answer

Answer: b

The design gives a credible effect in a small place. Extrapolating beyond it needs reasons the design doesn't supply.

Check yourself

Halving the bandwidth makes the estimate move a little and the interval wider. What is the most reasonable reading?

Show the answer

Answer: a

Less data near the cutoff means more variance. Worry when the estimate changes sharply, not when it wobbles.

08

Try it

In the app

In the Causal studio, start from Eligibility cutoff (regression discontinuity).

Python
import pandas as pd
from rdrobust import rdrobust

df = pd.read_csv("senate.csv")
print(rdrobust(df["vote"], df["margin"], c=0))
R
library(rdrobust)
library(rddensity)

df <- read.csv("senate.csv")
summary(rdrobust(df$vote, df$margin, c = 0))
summary(rddensity(df$margin, c = 0))  # manipulation test
09

Recap

Recap
  • A cutoff makes units close to it comparable, if they can't sort precisely.
  • Bandwidth trades bias against variance, so check half and double.
  • Try to break the design with density, placebo and balance checks.
  • The effect is local to the cutoff, and in a fuzzy design it's for compliers.

Concepts in this lesson