CCausal inference · causal.rdd
Regression discontinuity (sharp / fuzzy)
Did crossing a cutoff in a running variable (score, age, date) change the outcome?
Local polynomial regression discontinuity with data-driven bandwidths and robust bias-corrected confidence intervals (rdrobust). Fuzzy designs use treatment take-up. The robustness battery tests for manipulation of the running variable (density test), covariate balance at the cutoff, placebo cutoffs, half and double bandwidths and an optional donut.
A real result
Example “Senate sharp”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
τ = 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
View data
| margin (fit) | vote (local fit) | kind | side | margin | vote |
|---|---|---|---|---|---|
| — | — | bin | below | −99.680 | 33.928 |
| — | — | bin | below | −94.542 | 0 |
| — | — | bin | below | −86.618 | 40.624 |
| — | — | bin | below | −82.646 | 46.862 |
| — | — | bin | below | −79.323 | 43.499 |
| — | — | bin | below | −67.110 | 31.884 |
| — | — | bin | below | −62.180 | 33.846 |
| — | — | bin | below | −56.492 | 29.446 |
| — | — | bin | below | −52.340 | 30.552 |
| — | — | bin | below | −47.396 | 33.690 |
| — | — | bin | below | −42.347 | 31.986 |
| — | — | bin | below | −36.927 | 34.465 |
| — | — | bin | below | −32.409 | 34.036 |
| — | — | bin | below | −27.475 | 38.765 |
| — | — | bin | below | −22.697 | 39.431 |
| — | — | bin | below | −17.331 | 42.747 |
| — | — | bin | below | −12.347 | 41.692 |
| — | — | bin | below | −7.484 | 43.899 |
| — | — | bin | below | −2.553 | 44.985 |
| — | — | bin | above | 2.524 | 52.772 |
| — | — | bin | above | 7.666 | 55.819 |
| — | — | bin | above | 12.399 | 54.741 |
| — | — | bin | above | 17.360 | 58.376 |
| — | — | bin | above | 22.654 | 56.948 |
| — | — | bin | above | 27.482 | 59.194 |
| — | — | bin | above | 32.245 | 62.252 |
| — | — | bin | above | 37.153 | 64.137 |
| — | — | bin | above | 41.651 | 65.182 |
| — | — | bin | above | 47.258 | 70.312 |
| — | — | bin | above | 52.549 | 77.070 |
| — | — | bin | above | 57.879 | 80.059 |
| — | — | bin | above | 62.818 | 69.813 |
| — | — | bin | above | 67.143 | 71.240 |
| — | — | bin | above | 72.485 | 90.659 |
| — | — | bin | above | 77.140 | 87.144 |
| — | — | bin | above | 83.613 | 65.455 |
| — | — | bin | above | 87.476 | 87.788 |
| — | — | bin | above | 91.618 | 85.604 |
| — | — | bin | above | 99.877 | 89.434 |
| −17.754 | 42.263 | fit | below | — | — |
| −17.392 | 42.322 | fit | below | — | — |
| −17.030 | 42.382 | fit | below | — | — |
| −16.667 | 42.441 | fit | below | — | — |
| −16.305 | 42.501 | fit | below | — | — |
| −15.943 | 42.560 | fit | below | — | — |
| −15.580 | 42.619 | fit | below | — | — |
| −15.218 | 42.679 | fit | below | — | — |
| −14.856 | 42.738 | fit | below | — | — |
| −14.493 | 42.797 | fit | below | — | — |
| −14.131 | 42.857 | fit | below | — | — |
| −13.769 | 42.916 | fit | below | — | — |
| −13.406 | 42.976 | fit | below | — | — |
| −13.044 | 43.035 | fit | below | — | — |
| −12.682 | 43.094 | fit | below | — | — |
| −12.319 | 43.154 | fit | below | — | — |
| −11.957 | 43.213 | fit | below | — | — |
| −11.595 | 43.273 | fit | below | — | — |
| −11.232 | 43.332 | fit | below | — | — |
| −10.870 | 43.391 | fit | below | — | — |
| −10.508 | 43.451 | fit | below | — | — |
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)
| Estimate | Value | SE | p | Lower | Upper |
|---|---|---|---|---|---|
| Conventional | 7.414 | 1.459 | 3.722e-7 | 4.555 | 10.273 |
| Bias-corrected | 7.507 | 1.459 | 2.661e-7 | 4.647 | 10.366 |
| Robust | 7.507 | 1.741 | 1.625e-5 | 4.094 | 10.919 |
τ = 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)
| Estimate | Value | SE | p | Lower | Upper |
|---|---|---|---|---|---|
| Conventional | 7.414 | 1.459 | 3.722e-7 | 4.555 | 10.273 |
| Bias-corrected | 7.507 | 1.459 | 2.661e-7 | 4.647 | 10.366 |
| Robust | 7.507 | 1.741 | 1.625e-5 | 4.094 | 10.919 |
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Senate sharpc1_senate · outcome: vote · running: margin
- Fuzzy balancec1_fuzzy · covariates: age · outcome: gpa · running: test score · treatment: scholarship
- Optionsc1_senate · outcome: vote · running: margin
- Manual bandwidth clusterc1_fuzzy · cluster: school · outcome: gpa · running: test score
- Degenerate constantc1_senate · outcome: vote · running: margin
- Degenerate n3c1_senate · outcome: vote · running: margin
In the guides
Where it sits in the decision guides
- Causal inference (experiments, DiD, IV, RDD) · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Outcomenumeric · 1 column
- The outcome measured on both sides of the cutoff.
- Running variablenumeric · 1 column
- The score that decides treatment at the cutoff.
- Treatment received (fuzzy)numeric / boolean · 0–1 column
- Leave empty for a sharp design. With take-up, the estimate is the effect for compliers at the cutoff.
- Balance covariatesnumeric / boolean · 0–10 columns
- Pre-determined variables that should not jump at the cutoff (tested one by one).
- Clustercategorical / numeric · 0–1 column
- Groups whose rows are not independent (for example, schools); standard errors are clustered on it.
Choices you make
hypothesis
- Cutoffdefault 0
Value of the running variable where treatment switches on.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- Polynomial orderdefault 1
Degree of the local polynomial on each side of the cutoff. 1 (local linear) is the standard choice.
- Kerneldefault triangular
How rows are weighted by distance from the cutoff. Triangular is the usual choice.
- Triangular(default) — Weights rows less as they get further from the cutoff; the usual choice.
- Epanechnikov — Weights rows along a smooth curve; a close alternative to triangular for a robustness check.
- Uniform — Weights every row in the bandwidth equally; a plain regression on the window, and easy to explain.
- Bandwidth selectordefault mserd
How the bandwidth around the cutoff is chosen: MSE-optimal (best estimate) or coverage-optimal (best intervals).
- MSE-optimal, same on both sides(default) — One bandwidth for both sides, minimizing the estimate's mean squared error; the usual choice.
- MSE-optimal, each side — A separate MSE-optimal bandwidth on each side; pick it when the outcome or data density differs across the cutoff.
- Coverage-optimal, same on both sides — One bandwidth for both sides, tuned for interval coverage; narrower, and aimed at inference over point estimates.
- Coverage-optimal, each side — A separate coverage-optimal bandwidth on each side; pick it for inference when the two sides behave differently.
- Bandwidthdefault —
Bandwidth around the cutoff. Leave empty to choose it with the selector above.
- Donut radiusdefault 0
Leave out observations this close to the cutoff (sorting or heaping near it). 0 = no donut.
- Robustness batterydefault on
Density test, covariate balance, placebo cutoffs, half and double bandwidths.
plots
- Bins per side (plot)default 20
Number of bins per side in the binned scatterplot (display only; the estimate doesn't use them).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Continuity at the cutoffNot checked from data: state why it holds
Without treatment the outcome would change smoothly across the cutoff.
No manipulation
Units cannot precisely sort around the cutoff (density test).
Local effect
The estimate applies to units near the cutoff.
Covariate balance at the cutoff
Covariates should not jump at the cutoff; a jump suggests the groups differ in more than treatment.
Placebo cutoffs
Fake cutoffs away from the real one should show no jump.
Bandwidth sensitivity
The estimate at half and double the chosen bandwidth.
Jump in treatment take-up
In a fuzzy design, treatment take-up must jump at the cutoff; a small jump is a weak instrument.
What it reports
- Tests: Discontinuity at the cutoff
- estimate
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- estimate_bc
- Estimates an effect from the jump in outcomes at a cut-off that decides treatment.
- se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- se_robust
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- p_value
- How surprising your data would be if the null hypothesis were true, as a probability.
- ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- n
- How many independent units the analysis used; it sets precision and power.
- n_left
- How many independent units the analysis used; it sets precision and power.
- n_right
- How many independent units the analysis used; it sets precision and power.
- bandwidth
- Estimates an effect from the jump in outcomes at a cut-off that decides treatment.
- bandwidth_right
- Estimates an effect from the jump in outcomes at a cut-off that decides treatment.
- b_left
- Estimates an effect from the jump in outcomes at a cut-off that decides treatment.
- b_right
- Estimates an effect from the jump in outcomes at a cut-off that decides treatment.
- cutoff
- Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
- fuzzy
- Estimates an effect from the jump in outcomes at a cut-off that decides treatment.
- estimand
- The exact quantity an analysis targets, such as a difference in means or a ratio of medians.
- effect_label
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- claim_level_max
- How strong a causal statement the design supports, from association up to a causal effect.
Per group, level or term: density_p, check[<id>], balance_estimate[<covariate>], balance_p[…], density_t, half_bw_estimate, half_bw_p, double_bw_estimate, double_bw_p, first_stage, first_stage_f, first_stage_p, kernel, p_order, placebo_p, placebo_left_cutoff, placebo_left_estimate, placebo_left_p, placebo_right_cutoff, placebo_right_estimate, placebo_right_p
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses pandas, numpy, scipy, rdrobust, rddensity, codesplash; R uses rdrobust, rddensity, nanoparquet, codesplashr.
Default traps between the two languages
- rdrobust and rddensity are the same authors' implementations in both languages; bandwidth selection agrees to ≈ 1e-11 and estimates to ≈ 1e-12.
- Binned means and the plotted local fits are computed by a twin (evenly spaced bins per side, weighted least squares with the chosen kernel).
The exact script CodeSplash ran for example “Senate sharp” · 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 exact script CodeSplash ran for example “Senate sharp” · 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)))
))
Sources
- Calonico, S., Cattaneo, M. D., & Titiunik, R. (2014). Robust nonparametric confidence intervals for regression-discontinuity designs. Econometrica, 82, 2295–2326.
- Cattaneo, M. D., Jansson, M., & Ma, X. (2020). Simple local polynomial density estimators. JASA, 115, 1449–1455.
- Cattaneo, M. D., Idrobo, N., & Titiunik, R. (2020). A practical introduction to regression discontinuity designs: foundations. Cambridge University Press.
From the CodeSplash method registry · causal.rdd v1.0.2.