Techniquecore
Regression discontinuity design
Also called regression discontinuity.
When treatment is assigned by a score crossing a cutoff, estimate the effect by the jump in the outcome regression at the cutoff, using local linear fits.
A regression discontinuity design estimates the effect of a treatment that is given to units whose score , the running variable, is at or above a known cutoff . Units just above and just below the cutoff are alike in everything except the treatment, so a jump in the mean outcome at is the effect of the treatment for units at the cutoff. The estimate fits a straight line to the outcome on each side of the cutoff, using only units within a bandwidth and giving more weight to units closer to , and takes the difference of the two lines at . It needs no assumption about how the treatment was chosen apart from the rule itself, and no ignorability. It needs the outcome means to be continuous in the score at the cutoff, which fails if units can move their score across it. When crossing the cutoff only raises the chance of treatment, the fuzzy design divides the jump in the outcome by the jump in the treatment rate, an instrumental variables estimate at the cutoff.
In plain words
A scholarship goes to every student who scores 80 or more on a test. Students with 79 and students with 81 are, for practical purposes, the same: one or two questions apart, which is luck. If students just above 80 later earn more than students just below, the difference is the effect of the scholarship, not of being a better student, because the better students are on both sides in almost equal measure.
We cannot compare students at exactly 80 on both sides, because there are none. So we draw a line through the data just left of 80 and one just right, and read off where each line hits 80.
When it applies
Each unit has a running variable with a density positive around , potential outcomes and , and treatment .
- Sharp design. . The target is .
- Fuzzy design. jumps at but not from 0 to 1. The target is the average effect at the cutoff for the units whose treatment changes when their score crosses it.
Identification in the sharp design. Assume and are continuous at . Then
Proof. For every unit is treated, so , and the right limit is by continuity. For no unit is treated, so , and the left limit is . The difference is .
The proof uses nothing about how relates to the potential outcomes away from : may be strongly related to them, as test scores are to later earnings. Continuity is what can fail. If units know the rule and can adjust their score, those who sort just above the cutoff differ from those just below, and jumps at . Lee (2008) showed that if units control their score only imprecisely, with a random part whose density is continuous, then continuity holds, and treatment near the cutoff is as good as randomly assigned.
Identification in the fuzzy design. Hahn, Todd and van der Klaauw (2001) show that the ratio of the jump in to the jump in is the average effect for compliers at the cutoff, under continuity and a monotonicity condition. This is the local average treatment effect theorem with as the instrument, applied in the limit at . The page cites this result and does not prove the limit argument.
The design does not apply when the cutoff is not known, when the running variable is discrete with few values near , when other treatments change at the same cutoff, or when there is evidence of sorting.
The template
Estimation. Local linear regression on each side with the triangular kernel:
RDD(x, y, c, h) ▷ sharp design, bandwidth h > 0- 1
wᵢ ← max(0, 1 - |xᵢ - c| / h) - 2
(a₋, b₋) ← WLS of y on (1, x - c) with weights w over the units with x < c - 3
(a₊, b₊) ← WLS of y on (1, x - c) with weights w over the units with x ≥ c - 4
τ̂ ← a₊ - a₋ - 5
se ← √(Σᵢ ℓᵢ² eᵢ²) over both sides ▷ ℓᵢ the weight of yᵢ in its side's intercept, eᵢ the residual - 6
return (τ̂, se)
The cost is . The fuzzy design runs RDD on and on and divides the two jumps; its standard error linearizes the ratio. Choosing is the hard part and is an input of the code. Imbens and Kalyanaraman (2012) give a plug-in bandwidth that minimizes the mean squared error of , and Calonico, Cattaneo and Titiunik (2014) correct the bias of that choice and widen the interval to account for the correction.
Why local linear and not local constant. At a boundary, a weighted mean of near has bias of order when the regression function has a slope, because all the data lie on one side. A local line removes that term and leaves bias of order (Hahn, Todd and van der Klaauw 2001). This is the boundary property of local polynomial regression. The fit on one side is a weighted least squares problem in closed form. With weighted means , and for , the intercept is
These weights satisfy and , so a line gives exactly. Hence, if the noise-free outcome is a line on each side, is the true jump for every bandwidth, which the tests check in fractions.
The pooled regression is exact. Fit by WLS, with the same kernel weights, on with . The left units have regressors and the right units . Reparametrize as and ; the map is one to one and the weighted sum of squares splits into a left part depending only on and a right part depending only on . So the pooled minimum is the pair of side minima, and . The tests check this, and the side fits against a direct solve of the weighted normal equations, exactly in 60 random cases.
Worked example. Cutoff , bandwidth :
| -2.5 | -1.5 | -1 | -0.5 | 0 | 0.5 | 1 | 1.5 | 2.5 | |
|---|---|---|---|---|---|---|---|---|---|
| 2 | 1 | 3 | 2 | 6 | 5 | 7 | 6 | 9 | |
| 0 | 1/4 | 1/2 | 3/4 | 1 | 3/4 | 1/2 | 1/4 | 0 |
The end points get weight 0 and drop out. On the left, , , , and , so the slope is and the intercept is . On the right, , , , and , so the slope is and the intercept is . The jump is . The pooled regression gives , the same jump.
Simulation. uniform on , , with , , 300 samples each. In the second design the right side has an extra , so the curvature jumps by . All numbers are measured; the predicted bias is the standard leading term for the triangular kernel at a flat design density, .
| design | mean of | predicted mean | SD | coverage of | |
|---|---|---|---|---|---|
| same curvature | 0.2 | 0.992 | 1 | 0.086 | 0.94 |
| same curvature | 0.4 | 0.993 | 1 | 0.062 | 0.95 |
| curvature jump 4 | 0.2 | 0.989 | 0.992 | 0.092 | 0.95 |
| curvature jump 4 | 0.4 | 0.971 | 0.968 | 0.062 | 0.93 |
| curvature jump 4 | 0.8 | 0.875 | 0.872 | 0.043 | 0.25 |
A wider bandwidth lowers the standard deviation and raises the bias. At the bias is three standard deviations and the interval misses three times out of four. This is why the bias-corrected interval of Calonico, Cattaneo and Titiunik is preferred when is chosen to minimize mean squared error, since that choice makes bias and standard deviation of the same order.
Classic examples
- Merit awards. Thistlethwaite and Campbell (1960) compared students just above and below the score that earned a National Merit certificate of merit, the first use of the design.
- Close elections. Lee (2008) compared U.S. House districts where a party barely won with those where it barely lost, to measure the incumbency advantage. Vote share is hard to control precisely, which supports continuity.
- Class size. Angrist and Lavy used Maimonides' rule, which splits a class when enrollment passes 40, as a fuzzy design: enrollment crossing a multiple of 40 lowers the class size.
- Age thresholds. The legal drinking age, pension eligibility and school entry dates assign treatment by age crossing a cutoff, with age as the running variable.
- Credit scores and test scores. Many decisions by firms and schools use a score cutoff, which makes the design common in practice.
Variations
- Fuzzy design. Ratio of two jumps; equivalent to 2SLS with as the instrument and the same kernel weights and side-specific slopes.
- Bandwidth choice. The Imbens-Kalyanaraman plug-in bandwidth, the Calonico-Cattaneo-Titiunik bandwidth with robust bias-corrected intervals, or cross-validation of the fit near the cutoff.
- Other kernels and degrees. The triangular kernel is optimal for boundary estimation in a minimax sense; the uniform kernel gives a plain local regression. Local quadratic fits are used for bias correction. Global polynomials of high degree are a bad choice: Gelman and Imbens (2019) show their implicit weights are noisy and their intervals under-cover.
- Covariates. Adding predetermined covariates can reduce variance but must not change the estimand; a covariate that jumps at the cutoff is a warning sign.
- Regression kink design. If the treatment intensity changes slope, not level, at the cutoff, the effect is the ratio of the kinks.
- Multiple cutoffs and geographic boundaries. Several cutoffs can be pooled after normalizing the running variable; a border between regions gives a two-dimensional running variable.
- Local randomization. In a small window around , treat assignment as random and use a permutation test, which avoids the extrapolation of the line.
Pitfalls
- Sorting. If units can push their score over the cutoff, the units just above differ from those just below. Check the density of for a jump at (McCrary 2008), and check that predetermined covariates do not jump.
- High-order global polynomials. They fit well far from the cutoff and badly at it. Use local linear fits.
- Reporting the interval at the MSE-optimal bandwidth without bias correction. The bias is of the same order as the standard deviation, so the plain interval under-covers.
- Reading the estimate as an average effect for everyone. It is the effect at the cutoff. Units far from the cutoff may respond differently.
- Discrete running variables. With few distinct values near , the local fits extrapolate from coarse points, and the usual standard errors are too small.
- Other policies at the same cutoff. An age of 65 changes pension and health insurance at once, and the jump is their combined effect.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/regression-discontinuity-design/. The authors are listed in prov/QMX934.jsonl.
"""Regression discontinuity by local linear regression with a triangular kernel.
Units with running variable x >= c are treated (sharp design), or have a higher chance of
treatment (fuzzy design). On each side of c, fit y on (1, x - c) by weighted least squares
with weights max(0, 1 - |x - c| / h). The sharp estimate is the right intercept minus the
left intercept. The fuzzy estimate divides that jump by the jump of the treatment.
Each intercept is a linear combination sum(l_i y_i) of the outcomes; local_weights returns
the l_i. The standard error uses the heteroskedasticity-robust (HC0) variance sum(l_i^2 e_i^2).
The bandwidth h is an input. Choosing it (Imbens and Kalyanaraman, Calonico, Cattaneo and
Titiunik) is not done here. Everything except the standard error is exact for Fractions.
"""
import math
from collections.abc import Sequence
from typing import NamedTuple
class RDResult(NamedTuple):
tau: object # the jump at the cutoff
se: float # HC0 standard error of the jump
left: tuple # (intercept, slope) on the left
right: tuple # (intercept, slope) on the right
n_left: int # units with positive weight on the left
n_right: int
def triangular(u):
return max(u * 0, 1 - abs(u))
def local_weights(v: Sequence, w: Sequence) -> list:
"""For WLS of y on (1, v) with weights w, the intercept is sum(l_i y_i). Returns l."""
sw = sum(w)
if sw == 0:
raise ValueError("no unit has positive weight")
vb = sum(a * b for a, b in zip(w, v)) / sw
sv = sum(a * (b - vb) * (b - vb) for a, b in zip(w, v))
if sv == 0:
raise ValueError("need at least two distinct running-variable values with positive weight on each side")
# intercept = ybar - slope * vbar, slope = sum w (v - vb) y / sv
return [a / sw - vb * a * (b - vb) / sv for a, b in zip(w, v)]
def _fit(v, y, w):
sw = sum(w)
vb = sum(a * b for a, b in zip(w, v)) / sw
yb = sum(a * b for a, b in zip(w, y)) / sw
sv = sum(a * (b - vb) * (b - vb) for a, b in zip(w, v))
slope = sum(a * (b - vb) * (c - yb) for a, b, c in zip(w, v, y)) / sv
return yb - slope * vb, slope
def _side(x, y, c, h, right):
keep = [i for i in range(len(x)) if (x[i] >= c) == right]
v = [x[i] - c for i in keep]
w = [triangular(a / h) for a in v] # @line L1
pos = [j for j in range(len(keep)) if w[j] > 0]
return [keep[j] for j in pos], [v[j] for j in pos], [w[j] for j in pos]
def _local_linear(x, y, c, h, right):
"""(intercept, slope), HC0 variance of the intercept, and the number of units used."""
idx, v, w = _side(x, y, c, h, right)
yy = [y[i] for i in idx]
lw = local_weights(v, w)
a, b = _fit(v, yy, w)
resid = [q - a - b * p for p, q in zip(v, yy)]
var = sum(float(l) ** 2 * float(e) ** 2 for l, e in zip(lw, resid))
return (a, b), var, len(idx)
def rdd(x: Sequence, y: Sequence, c, h) -> RDResult:
"""Sharp design. Cost: Theta(n)."""
if len(x) != len(y):
raise ValueError("x and y need the same length")
if not h > 0:
raise ValueError("the bandwidth must be positive")
left, vl, nl = _local_linear(x, y, c, h, False) # @line L2
right_fit, vr, nr = _local_linear(x, y, c, h, True) # @line L3
tau = right_fit[0] - left[0] # @line L4
se = math.sqrt(vl + vr) # @line L5
return RDResult(tau, se, left, right_fit, nl, nr) # @line L6
def rdd_fuzzy(x: Sequence, y: Sequence, d: Sequence, c, h) -> tuple:
"""Fuzzy design: (jump in y / jump in d, se, jump in y, jump in d). The se linearizes
the ratio: var = sum over both sides of l_i^2 (e_y,i - tau e_d,i)^2 / jump_d^2."""
ry = rdd(x, y, c, h)
rd = rdd(x, d, c, h)
if rd.tau == 0:
raise ZeroDivisionError("the treatment does not jump at the cutoff")
tau = ry.tau / rd.tau
var = 0.0
for right, fy, fd in ((False, ry.left, rd.left), (True, ry.right, rd.right)):
idx, v, w = _side(x, y, c, h, right)
lw = local_weights(v, w)
for l, i, p in zip(lw, idx, v):
ey = y[i] - fy[0] - fy[1] * p
ed = d[i] - fd[0] - fd[1] * p
var += float(l) ** 2 * float(ey - tau * ed) ** 2
return tau, math.sqrt(var) / abs(float(rd.tau)), ry.tau, rd.tau
def wls(xm: list[list], y: Sequence, w: Sequence) -> list:
"""Direct weighted least squares by the normal equations (Gauss-Jordan), for checking."""
k = len(xm[0])
a = [[sum(wi * r[i] * r[j] for r, wi in zip(xm, w)) for j in range(k)] for i in range(k)]
b = [sum(wi * r[i] * yi for r, wi, yi in zip(xm, w, y)) for i in range(k)]
m = [row + [v] for row, v in zip(a, b)]
for col in range(k):
p = max(range(col, k), key=lambda r: abs(m[r][col]))
if m[p][col] == 0:
raise ValueError("singular matrix")
m[col], m[p] = m[p], m[col]
for r in range(k):
if r != col and m[r][col] != 0:
f = m[r][col] / m[col][col]
for j in range(col, k + 1):
m[r][j] -= f * m[col][j]
return [m[r][k] / m[r][r] for r in range(k)]
def pooled_fit(x: Sequence, y: Sequence, c, h) -> list:
"""WLS of y on (1, T, x - c, T (x - c)) with the kernel weights, T = [x >= c].
The coefficient of T equals rdd(...).tau exactly."""
one = y[0] * 0 + 1
rows, yy, ww = [], [], []
for a, b in zip(x, y):
w = triangular((a - c) / h)
if w > 0:
t = one if a >= c else one - one
rows.append([one, t, (a - c) * one, t * (a - c)])
yy.append(b)
ww.append(w)
return wls(rows, yy, ww)
test_regression_discontinuity_design.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/regression-discontinuity-design/. The authors are listed in prov/QMX934.jsonl.
import math
import random
from fractions import Fraction as Fr
import pytest
from regression_discontinuity_design import (
local_weights,
pooled_fit,
rdd,
rdd_fuzzy,
triangular,
wls,
)
def test_worked_example():
x = [Fr(v, 2) for v in (-5, -3, -2, -1, 0, 1, 2, 3, 5)]
y = [Fr(v) for v in (2, 1, 3, 2, 6, 5, 7, 6, 9)]
r = rdd(x, y, 0, 2)
assert r.left == (Fr(5, 2), Fr(2, 5)) and r.right == (Fr(57, 10), Fr(2, 5))
assert r.tau == Fr(16, 5) and (r.n_left, r.n_right) == (3, 4)
assert pooled_fit(x, y, 0, 2) == [Fr(5, 2), Fr(16, 5), Fr(2, 5), 0]
def random_case(rng):
n = rng.randint(8, 20)
x = [Fr(rng.randint(-20, 20), 4) for _ in range(n)]
x += [Fr(-1), Fr(-2), Fr(0), Fr(1)] # two distinct values on each side inside h >= 3
y = [Fr(rng.randint(-9, 9)) for _ in x]
return x, y, Fr(rng.randint(3, 6))
def test_local_linear_equals_direct_wls_exactly():
"""Closed-form side fits agree with solving the weighted normal equations, and the jump equals
the coefficient of T in the pooled WLS with separate slopes."""
rng = random.Random(1)
for _ in range(60):
x, y, h = random_case(rng)
r = rdd(x, y, 0, h)
for right, fit in ((False, r.left), (True, r.right)):
rows, yy, ww = [], [], []
for a, b in zip(x, y):
w = triangular(a / h)
if (a >= 0) == right and w > 0:
rows.append([Fr(1), a])
yy.append(b)
ww.append(w)
assert tuple(wls(rows, yy, ww)) == fit
assert pooled_fit(x, y, 0, h)[1] == r.tau
def test_local_weights_reproduce_lines():
"""sum l_i = 1 and sum l_i v_i = 0, so the intercept of an exact line is returned exactly."""
rng = random.Random(2)
for _ in range(60):
v = [Fr(rng.randint(0, 30), 7) for _ in range(rng.randint(3, 10))] + [Fr(0), Fr(1, 3)]
w = [triangular(a / 5) for a in v]
lw = local_weights(v, w)
assert sum(lw) == 1
assert sum(a * b for a, b in zip(lw, v)) == 0
def test_sharp_design_recovers_the_jump_of_piecewise_lines():
"""Noise-free y = a + b v + T (tau + g v): any bandwidth returns tau exactly."""
rng = random.Random(3)
for _ in range(40):
x, _, h = random_case(rng)
a, b, g, tau = (Fr(rng.randint(-9, 9), rng.randint(1, 3)) for _ in range(4))
y = [a + b * v + (tau + g * v if v >= 0 else 0) for v in x]
r = rdd(x, y, 0, h)
assert r.tau == tau and r.se == 0
def test_fuzzy_design_exact_ratio():
"""y = a + b v + tau d with d jumping at the cutoff: the ratio of jumps is tau exactly."""
rng = random.Random(4)
done = 0
while done < 40:
x, _, h = random_case(rng)
d = [Fr(int(rng.random() < (0.8 if v >= 0 else 0.2))) for v in x]
a, b, tau = (Fr(rng.randint(-9, 9), rng.randint(1, 3)) for _ in range(3))
y = [a + b * v + tau * di for v, di in zip(x, d)]
try:
est, se, jy, jd = rdd_fuzzy(x, y, d, 0, h)
except ZeroDivisionError:
continue
assert est == tau and jy == tau * jd
done += 1
def simulate(rng, n, h, extra_curvature):
x = [rng.uniform(-1, 1) for _ in range(n)]
y = [
0.5 + 0.8 * a + 0.6 * a * a + (1.0 + extra_curvature * a * a if a >= 0 else 0.0) + rng.gauss(0, 0.3)
for a in x
]
return rdd(x, y, 0.0, h)
def test_monte_carlo_bias_and_coverage():
"""x uniform on (-1, 1), true jump 1, noise sd 0.3, n = 1000, h = 0.4, r = 300 per design.
Same curvature on both sides: mean within 4 SE of 1, coverage within 0.95 +- (4 SE + 0.02).
Curvature larger by 4 on the right: the triangular-kernel boundary bias is -(h^2/20) 4 = -0.032,
and the mean is within 4 SE + 0.01 of 0.968."""
for extra, target, seed in ((0.0, 1.0, 2026), (2.0, 1.0 - 0.032, 7)):
rng = random.Random(seed)
est, cover = [], 0
for _ in range(300):
res = simulate(rng, 1000, 0.4, extra)
est.append(res.tau)
cover += abs(res.tau - 1) <= 1.96 * res.se
m = sum(est) / 300
sd = math.sqrt(sum((v - m) ** 2 for v in est) / 299)
assert abs(m - target) < 4 * sd / math.sqrt(300) + (0.01 if extra else 0.0)
if not extra:
assert abs(cover / 300 - 0.95) < 4 * math.sqrt(0.95 * 0.05 / 300) + 0.02
def test_input_checks():
with pytest.raises(ValueError):
rdd([1, 2], [1], 0, 1)
with pytest.raises(ValueError):
rdd([-1, 1, 2], [1, 2, 3], 0, 0)
with pytest.raises(ValueError):
rdd([-0.5, 0.5, 0.7], [1, 2, 3], 0, 1) # one point on the left
Exercises
- Show that the local constant estimate (weighted means on each side) has bias of order when and have the same nonzero slope at , for a uniform design density.
- In the worked example, add 10 to at . What changes?
- Prove that .
- A fuzzy design has a jump of 0.4 in the treatment rate and of 1.2 in the outcome. What is the estimate, and for whom?
- Explain why a placebo cutoff, a value of away from where no treatment changes, should give a jump near zero, and what a large placebo jump suggests.
References
- Donald L. Thistlethwaite and Donald T. Campbell, Regression-discontinuity analysis, an alternative to the ex post facto experiment, Journal of Educational Psychology 51(6), 1960, pp. 309 to 317 (the design, with National Merit certificates of merit as the treatment)
- Jinyong Hahn, Petra Todd and Wilbert van der Klaauw, Identification and estimation of treatment effects with a regression-discontinuity design, Econometrica 69(1), 2001, pp. 201 to 209 (identification under continuity, the fuzzy design as a local instrumental variables problem, local linear estimation)
- Guido W. Imbens and Thomas Lemieux, Regression discontinuity designs, a guide to practice, Journal of Econometrics 142(2), 2008, pp. 615 to 635 (local linear fits, the pooled regression form, graphs and checks)
- Guido Imbens and Karthik Kalyanaraman, Optimal bandwidth choice for the regression discontinuity estimator, The Review of Economic Studies 79(3), 2012, pp. 933 to 959 (the mean squared error optimal bandwidth and its plug-in estimate)
- Sebastian Calonico, Matias D. Cattaneo and Rocío Titiunik, Robust nonparametric confidence intervals for regression-discontinuity designs, Econometrica 82(6), 2014, pp. 2295 to 2326 (bias correction with a variance that accounts for it)
- Justin McCrary, Manipulation of the running variable in the regression discontinuity design, a density test, Journal of Econometrics 142(2), 2008, pp. 698 to 714 (testing for a jump in the density of the running variable)
- David S. Lee, Randomized experiments from non-random selection in U.S. House elections, Journal of Econometrics 142(2), 2008, pp. 675 to 697 (close elections, and why imprecise control of the score makes the design as good as local randomization)
- Andrew Gelman and Guido Imbens, Why high-order polynomials should not be used in regression discontinuity designs, Journal of Business and Economic Statistics 37(3), 2019, pp. 447 to 456 (noisy weights and poor coverage of global polynomial fits)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag QMX934 Edit this page History Report an error Markdown