CCausal inference · causal.sensitivity
Sensitivity to unmeasured confounding (sensemakr, E-values, Rosenbaum bounds)
How strong would an unmeasured confounder have to be to explain away the estimated effect?
Fits the regression-adjusted treatment effect and asks how robust it is to omitted confounders: partial R² of the treatment and robustness values RV and RV_α (Cinelli & Hazlett's omitted-variable bias framework), bounds on a confounder k times as strong as observed benchmark covariates with the adjusted estimate and interval, a contour of adjusted estimates, the E-value of the estimate and of its confidence limit (VanderWeele & Ding), and — for matched pairs — Rosenbaum bounds for the signed-rank test with the critical Γ.
A real result
Example “Lalonde benchmarks”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Adjusted for 7 covariate(s), the effect of true vs false on earnings 1978 is 1548.24 (95% CI [13.89, 3082.60]). An unmeasured confounder would have to explain 7.7% of the residual variance of both treatment and outcome to remove the effect (RV) and 0.1% to make it non-significant at α = 0.05 (RV_α). E-value: 1.71 for the estimate and 1.05 for the confidence limit.
- Adjusted effect
- 1548.24
- Robustness value
- 0.0774
- Robustness value (α)
- 0.0007
- E-value
- 1.708
Assumptions
- Robust to benchmark-strength confounding — A confounder as strong as race, re74 could make the effect non-significant.
Sensitivity statistics
| Statistic | Value |
|---|---|
| Estimate | 1548.24 |
| Standard error | 781.28 |
| t | 1.982 |
| Partial R² of treatment with outcome | 0.0065 |
| Robustness value RV | 0.0774 |
| Robustness value RV (α = 0.05) | 0.0007 |
| E-value (SMD) | 1.708 |
| E-value of the confidence limit | 1.052 |
Bounds from benchmark covariates
| Confounder as strong as | R² with treatment | R² with outcome | Adjusted estimate | CI low | CI high |
|---|---|---|---|---|---|
| re74 ×1 | 0.0068 | 0.0434 | 1216.72 | −290.34 | 2723.79 |
| re74 ×2 | 0.0136 | 0.0868 | 882.89 | −594.66 | 2360.43 |
| re74 ×3 | 0.0205 | 0.1303 | 546.69 | −900.30 | 1993.68 |
| race ×1 | 0.4250 | 0.0154 | −500.55 | −2510.09 | 1509.00 |
| race ×2 | 0.8501 | 0.0815 | −11501.11 | −15302.26 | −7699.96 |
Partial R² bounds (Cinelli & Hazlett 2020, §4.4); intervals at α = 0.05.
- Omitted-variable-bias bounds assume a single confounder (or group) acting linearly; E-values use VanderWeele's approximations.
Adjusted for 7 covariate(s), the effect of true vs false on earnings 1978 is 1548.24 (95% CI [13.89, 3082.60]). An unmeasured confounder would have to explain 7.7% of the residual variance of both treatment and outcome to remove the effect (RV) and 0.1% to make it non-significant at α = 0.05 (RV_α). E-value: 1.71 for the estimate and 1.05 for the confidence limit.
- Adjusted effect
- 1548.24
- Robustness value
- 0.0774
- Robustness value (α)
- 0.0007
- E-value
- 1.708
Assumptions
- Robust to benchmark-strength confounding — A confounder as strong as race, re74 could make the effect non-significant.
Sensitivity statistics
| Statistic | Value |
|---|---|
| Estimate | 1548.24 |
| Standard error | 781.28 |
| t | 1.982 |
| Partial R² of treatment with outcome | 0.0065 |
| Robustness value RV | 0.0774 |
| Robustness value RV (α = 0.05) | 0.0007 |
| E-value (SMD) | 1.708 |
| E-value of the confidence limit | 1.052 |
Bounds from benchmark covariates
| Confounder as strong as | R² with treatment | R² with outcome | Adjusted estimate | CI low | CI high |
|---|---|---|---|---|---|
| re74 ×1 | 0.0068 | 0.0434 | 1216.72 | −290.34 | 2723.79 |
| re74 ×2 | 0.0136 | 0.0868 | 882.89 | −594.66 | 2360.43 |
| re74 ×3 | 0.0205 | 0.1303 | 546.69 | −900.30 | 1993.68 |
| race ×1 | 0.4250 | 0.0154 | −500.55 | −2510.09 | 1509.00 |
| race ×2 | 0.8501 | 0.0815 | −11501.11 | −15302.26 | −7699.96 |
Partial R² bounds (Cinelli & Hazlett 2020, §4.4); intervals at α = 0.05.
- Omitted-variable-bias bounds assume a single confounder (or group) acting linearly; E-values use VanderWeele's approximations.
Shortened for the Academy: 1 chart(s) dropped to stay under 100 KB; 1 chart(s) dropped to stay under 100 KB.
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
- Lalonde benchmarksc2_lalonde · benchmarks: re74, race · covariates: age, educ, race, married, nodegree, re74, re75 · outcome: earnings 1978 · treatment: treat
- Binary outcome evaluec2_obs · benchmarks: x1 · covariates: x1, x2, segment, member · outcome: converted · treatment: treated
- Pairs rosenbaumc2_pairs · benchmarks: age · covariates: age · outcome: score · pair: pair · treatment: treated
- Degenerate constantc2_lalonde · benchmarks: re74, race · covariates: age, educ, race, married, nodegree, re74, re75 · outcome: earnings 1978 · treatment: treat
- Degenerate n3c2_lalonde · benchmarks: re74, race · covariates: age, educ, race, married, nodegree, re74, re75 · outcome: earnings 1978 · treatment: treat
- Degenerate single levelc2_lalonde · benchmarks: re74, race · covariates: age, educ, race, married, nodegree, re74, re75 · outcome: earnings 1978 · treatment: treat
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?
- Causal ML (uplift modeling) · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Outcomenumeric / boolean · 1 column
- Numeric (E-value via the standardized mean difference) or yes/no (E-value via the odds ratio).
- Treatmentboolean / categorical · 1 column · 2–2 levels
- Marks which rows received the treatment (yes/no, or a level that means treated).
- Observed confoundersnumeric / categorical / boolean · 0–40 columns · 2–30 levels
- Covariates in the adjusted regression.
- Benchmark covariatesnumeric / categorical / boolean · 0–5 columns · 2–30 levels
- Covariates (also listed as confounders) to compare an unmeasured confounder with: "as strong as age".
- Matched pair idcategorical · 0–1 column
- For matched data — one treated and one control row per pair — adds Rosenbaum bounds.
Choices you make
hypothesis
- Treated groupdefault —
Default: the second stored level (true for yes/no columns).
- Significance level for RV_α and boundsdefault 0.05
Significance level used for the robustness value RV_α and for the bias bounds.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- Benchmark multiples (k)default 1,2,3
Bounds for a confounder k times as strongly related to treatment and outcome as each benchmark.
- Yes/no outcome for the E-valuedefault auto
For yes/no outcomes, whether the outcome is rare (odds ratio ≈ risk ratio) when converting to an E-value.
- Automatic (rare when under 15% have it)(default) — Treats the outcome as rare when under 15% have it; the usual choice.
- Rare (odds ratio ≈ risk ratio) — Treats the odds ratio as a risk ratio; pick it when the outcome is rare.
- Common (√OR approximation) — Uses √OR as the risk ratio; pick it when the outcome is common.
- Largest Γ (Rosenbaum)default 3
Largest hidden-bias factor Γ to try in Rosenbaum bounds.
- Γ stepdefault 0.1
Step between the Γ values tried in Rosenbaum bounds.
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.
Robust to plausible confounding
Bounds from benchmark covariates should not explain the effect away.
Rosenbaum bounds
How strong hidden bias (Γ) would have to be before the matched-pairs result loses significance.
What it reports
- Tests: Regression-adjusted treatment effect
- estimate
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- 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.
- t_stat
- An estimate divided by its standard error, compared with a t distribution.
- p_value
- How surprising your data would be if the null hypothesis were true, as a probability.
- dof
- How much independent information is left to estimate variability after fitting the model.
- n
- How many independent units the analysis used; it sets precision and power.
- partial_r2_treatment
- The share of residual variance a confounder must explain in both treatment and outcome to wipe out the effect.
- rv_q1
- The share of residual variance a confounder must explain in both treatment and outcome to wipe out the effect.
- rv_qa
- The share of residual variance a confounder must explain in both treatment and outcome to wipe out the effect.
- evalue_point
- How strongly an unmeasured confounder would have to relate to both treatment and outcome to explain an effect away.
- evalue_ci
- How strongly an unmeasured confounder would have to relate to both treatment and outcome to explain an effect away.
- evalue_rr
- How strongly an unmeasured confounder would have to relate to both treatment and outcome to explain an effect away.
- evalue_measure
- How strongly an unmeasured confounder would have to relate to both treatment and outcome to explain an effect away.
- 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.
- treated_level
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- control_level
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
Per group, level or term: bound_r2dz[<benchmark> ×k], bound_r2yz[…], bound_estimate[…], bound_ci_low[…], bound_ci_high[…], gamma_critical, rosenbaum_p1, n_pairs
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, sensemakr, EValue, codesplashr.
Default traps between the two languages
- R runs sensemakr::sensemakr and EValue (evalues.MD / evalues.OR); Python runs twins of their closed forms (codesplash.causal.sensitivity). Rosenbaum bounds are a twin of rbounds::psens in both engines (unrounded p-values).
The exact script CodeSplash ran for example “Lalonde benchmarks” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Sensitivity to unmeasured confounding (sensemakr, E-values, Rosenbaum bounds)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.sensitivity 1.0.2 · spec 424e330f2c2dadfe
# Dataset: c2_lalonde (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import special, stats
import codesplash as cs
from codesplash.causal import sensitivity as css
from codesplash.causal import weighting as csw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c2_lalonde.parquet", columns=["earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75"])
n_input = len(df)
df["treat"] = pd.Categorical(df["treat"], categories=["false", "true"]) # stored level order
df["race"] = pd.Categorical(df["race"], categories=["black", "hispan", "white"]) # stored level order
df["married"] = pd.Categorical(df["married"], categories=["false", "true"]) # stored level order
df["nodegree"] = pd.Categorical(df["nodegree"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75"]) # listwise deletion over the analysis columns
df["treat"] = df["treat"].cat.remove_unused_categories()
df["race"] = df["race"].cat.remove_unused_categories()
df["married"] = df["married"].cat.remove_unused_categories()
df["nodegree"] = df["nodegree"].cat.remove_unused_categories()
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, ["earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75"]) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment = "treat"
outcome = "earnings 1978"
covariates = ["age", "educ", "race", "married", "nodegree", "re74", "re75"]
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R draws the same folds and resamples
t, treated_level, control_level = csw.treatment_indicator(df, treatment, None)
y, event_level = csw.outcome_vector(df, outcome)
X, labels, binary, sources = csw.covariate_matrix(df, covariates)
if X.shape[1]:
csw.check_rank(X, labels)
n = len(t)
n_treated, n_control = int(t.sum()), int(n - t.sum())
outcome_text = f"{outcome} = {event_level}" if event_level is not None else outcome
contrast_text = f"{treatment} = {treated_level} vs {control_level}"
benchmarks = ["re74", "race"]
pair_col = None
alpha = 0.05
kds = [float(k) for k in [1, 2, 3]] or [1.0]
rare_opt = "auto"
gamma_max, gamma_step = 3, 0.1
missing = [b for b in benchmarks if b not in covariates]
if missing:
raise ValueError(f"Benchmark covariates must also be confounders: {', '.join(missing)}")
# %% Adjusted regression: y ~ 1 + treatment + covariates (sensemakr's model; lm() in R)
Z = np.column_stack([np.ones(n), t, X])
b, V, dof = css.ols(Z, y)
est, se = float(b[1]), float(np.sqrt(V[1, 1]))
t_stat = est / se
p_value = float(2 * stats.t.sf(abs(t_stat), dof))
crit = stats.t.ppf(1 - (1 - conf) / 2, dof)
ci_low, ci_high = est - crit * se, est + crit * se
r2yd = t_stat**2 / (t_stat**2 + dof)
rv_q1 = css.rv(t_stat, dof, 1.0, 1.0)
rv_qa = css.rv(t_stat, dof, 1.0, alpha)
values = {}
# %% Bounds from benchmark covariates (sensemakr::ovb_bounds, partial R² groups)
Zd = np.column_stack([np.ones(n), X])
bd, Vd, dof_d = css.ols(Zd, t)
bounds = []
for bench in benchmarks:
cols = [j for j, s in enumerate(sources) if s == bench]
if not cols: # a category with one level left has no design columns: skipped, as sensemakr does in R
warnings.append(f"{bench} has no variation in the analyzed rows, so it gives no benchmark bound.")
continue
r2yxj = css.group_r2(b, V, [j + 2 for j in cols], dof)
r2dxj = css.group_r2(bd, Vd, [j + 1 for j in cols], dof_d)
for kd in kds:
bb = css.bound(r2dxj, r2yxj, kd, kd)
if bb is None:
continue
adj = css.adjusted(est, se, dof, bb[0], bb[1], alpha)
label = f"{bench} ×{kd:g}"
bounds.append({"label": label, "benchmark": bench, "kd": kd, "r2dz": bb[0], "r2yz": bb[1], **adj})
values[f"bound_r2dz[{label}]"] = bb[0]
values[f"bound_r2yz[{label}]"] = bb[1]
values[f"bound_estimate[{label}]"] = adj["estimate"]
values[f"bound_ci_low[{label}]"] = adj["ci_low"]
values[f"bound_ci_high[{label}]"] = adj["ci_high"]
lim = min(0.95, max([0.4] + [1.25 * max(r["r2dz"], r["r2yz"]) for r in bounds]))
grid = css.contour(est, se, dof, lim, lim)
# %% E-value (EValue::evalues.MD for numeric outcomes, evalues.OR for yes/no)
if event_level is None:
sd_y = float(np.std(y, ddof=1))
ev = css.evalues_md(est / sd_y, se / sd_y)
measure = "SMD"
else:
from codesplash.causal.weighting import logistic_fit
bl, _ = logistic_fit(Z, y)
pl = special.expit(Z @ bl)
Vl = np.linalg.inv((Z * (pl * (1 - pl))[:, None]).T @ Z)
zc = stats.norm.ppf(1 - (1 - conf) / 2)
sel = float(np.sqrt(Vl[1, 1]))
rare = (float(y.mean()) < 0.15) if rare_opt == "auto" else rare_opt == "rare"
ev = css.evalues_or(float(np.exp(bl[1])), float(np.exp(bl[1] - zc * sel)), float(np.exp(bl[1] + zc * sel)), rare)
measure = "OR (rare outcome)" if rare else "OR (common outcome, √OR)"
# %% Rosenbaum bounds for matched pairs
ros = None
if pair_col is not None:
p = df[pair_col].astype(str).to_numpy()
order = pd.unique(p)
diffs = []
for key in order:
m = p == key
if m.sum() != 2 or t[m].sum() != 1:
raise ValueError(f"Pair {key!r} must have exactly one treated and one control row.")
diffs.append(float(y[m & (t == 1)][0] - y[m & (t == 0)][0]))
ros = css.rosenbaum(np.array(diffs), gamma_max, gamma_step, alpha)
values["gamma_critical"] = ros["gamma_critical"]
values["rosenbaum_p1"] = ros["rows"][0]["p_upper"]
values["n_pairs"] = ros["n_pairs"]
# %% Checks
if bounds:
k1 = [r for r in bounds if r["kd"] == 1.0] or bounds
survives = all((r["ci_low"] > 0) if est > 0 else (r["ci_high"] < 0) for r in k1)
worst = k1[0]["benchmark"] if len(k1) == 1 else ", ".join(sorted({r["benchmark"] for r in k1}))
check = {"id": "robustness", "label": "Robust to benchmark-strength confounding", "status": "pass" if survives else "concern",
"detail": (f"A confounder as strong as {worst} would not remove the effect or its significance." if survives
else f"A confounder as strong as {worst} could make the effect non-significant.")}
else:
check = {"id": "robustness", "label": "Robust to confounding", "status": "info",
"detail": f"RV = {rv_q1:.1%}: a confounder explaining that share of the residual variance of treatment and outcome would remove the effect. Add benchmark covariates to judge plausibility."}
checks = [check]
if ros is not None:
checks.append({"id": "rosenbaum", "label": "Rosenbaum bounds", "status": "info",
"detail": f"The signed-rank test stays significant at α = {alpha:g} up to Γ = {ros['gamma_critical']:.2f}."})
# %% Result
effect_label = f"Regression-adjusted effect of {contrast_text} on {outcome_text}"
pct = f"{conf:.0%}"
summary = (
f"Adjusted for {len(covariates)} covariate(s), the effect of {treated_level} vs {control_level} on {outcome_text} is {cs.fmt_num(est)} "
f"({pct} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}]). An unmeasured confounder would have to explain {rv_q1:.1%} of the residual "
f"variance of both treatment and outcome to remove the effect (RV) and {rv_qa:.1%} to make it non-significant at α = {alpha:g} (RV_α). "
f"E-value: {ev['evalue_point']:.2f} for the estimate and {ev['evalue_ci']:.2f} for the confidence limit."
+ (f" Rosenbaum bounds: significant up to Γ = {ros['gamma_critical']:.2f}." if ros is not None else "")
)
values.update({
"estimate": est, "se": se, "ci_low": ci_low, "ci_high": ci_high, "t_stat": t_stat, "p_value": p_value, "dof": dof, "n": n,
"partial_r2_treatment": r2yd, "rv_q1": rv_q1, "rv_qa": rv_qa, "evalue_point": ev["evalue_point"], "evalue_ci": ev["evalue_ci"],
"evalue_rr": ev["rr"], "evalue_measure": measure, "estimand": "ATE (regression-adjusted)", "effect_label": effect_label,
"claim_level_max": "L2", "treated_level": treated_level, "control_level": control_level,
})
kinds = ["grid"] * len(grid["x"]) + ["point"] * len(bounds)
charts = [cs.chart(
"contour", "contour-grid", "Adjusted estimate by confounder strength",
{"x": cs.col("Partial R² of confounder with treatment", grid["x"] + [r["r2dz"] for r in bounds]),
"y": cs.col("Partial R² of confounder with outcome", grid["y"] + [r["r2yz"] for r in bounds]),
"z": cs.col("Adjusted estimate", grid["z"] + [r["estimate"] for r in bounds]),
"kind": cs.col("Kind", kinds, kind="categorical"),
"label": cs.col("Benchmark", [""] * len(grid["x"]) + [r["label"] for r in bounds], kind="categorical")},
{"levels": 10, "zero_line": True},
)]
tables = [
{"key": "sensitivity", "title": "Sensitivity statistics", "columns": [
{"key": "statistic", "label": "Statistic", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [
{"statistic": "Estimate", "value": est}, {"statistic": "Standard error", "value": se}, {"statistic": "t", "value": t_stat},
{"statistic": "Partial R² of treatment with outcome", "value": r2yd}, {"statistic": "Robustness value RV", "value": rv_q1},
{"statistic": f"Robustness value RV (α = {alpha:g})", "value": rv_qa}, {"statistic": f"E-value ({measure})", "value": ev["evalue_point"]},
{"statistic": "E-value of the confidence limit", "value": ev["evalue_ci"]}]},
]
if bounds:
tables.append({"key": "bounds", "title": "Bounds from benchmark covariates", "columns": [
{"key": "label", "label": "Confounder as strong as", "type": "string"}, {"key": "r2dz", "label": "R² with treatment", "type": "number"},
{"key": "r2yz", "label": "R² with outcome", "type": "number"}, {"key": "estimate", "label": "Adjusted estimate", "type": "number"},
{"key": "ci_low", "label": "CI low", "type": "number"}, {"key": "ci_high", "label": "CI high", "type": "number"}],
"rows": [{k: r[k] for k in ("label", "r2dz", "r2yz", "estimate", "ci_low", "ci_high")} for r in bounds],
"note": f"Partial R² bounds (Cinelli & Hazlett 2020, §4.4); intervals at α = {alpha:g}."})
if ros is not None:
tables.append({"key": "rosenbaum", "title": "Rosenbaum bounds (Wilcoxon signed-rank)", "columns": [
{"key": "gamma", "label": "Γ", "type": "number"}, {"key": "p_upper", "label": "Upper-bound p", "type": "pvalue"},
{"key": "p_lower", "label": "Lower-bound p", "type": "pvalue"}], "rows": ros["rows"],
"note": f"{ros['n_pairs']} pairs with a non-zero difference; test in the direction of the observed effect ({ros['direction']})."})
cs.publish({
"method": "causal.sensitivity",
"methodVersion": "1.0.2",
"title": "Sensitivity to unmeasured confounding",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": n,
"summary": summary,
"statistics": [
{"key": "estimate", "label": "Adjusted effect", "value": est},
{"key": "rv_q1", "label": "Robustness value", "value": rv_q1},
{"key": "rv_qa", "label": "Robustness value (α)", "value": rv_qa},
{"key": "evalue_point", "label": "E-value", "value": ev["evalue_point"]},
],
"tables": tables,
"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,
"notes": ["Omitted-variable-bias bounds assume a single confounder (or group) acting linearly; E-values use VanderWeele's approximations."],
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Lalonde benchmarks” · R version 4.5.1 (2025-06-13)
# Sensitivity to unmeasured confounding (sensemakr, E-values, Rosenbaum bounds)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.sensitivity 1.0.2 · spec 424e330f2c2dadfe
# Dataset: c2_lalonde (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c2_lalonde.parquet", col_select = c("earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75")))
n_input <- nrow(df)
df[["treat"]] <- factor(df[["treat"]], levels = c("false", "true")) # stored level order
df[["race"]] <- factor(df[["race"]], levels = c("black", "hispan", "white")) # stored level order
df[["married"]] <- factor(df[["married"]], levels = c("false", "true")) # stored level order
df[["nodegree"]] <- factor(df[["nodegree"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75")]), , 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("earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75")) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment <- "treat"
outcome <- "earnings 1978"
covariates <- c("age", "educ", "race", "married", "nodegree", "re74", "re75")
conf <- 0.95
seed <- 42 # portable Wichmann–Hill stream: Python draws the same folds and resamples
tr_info <- cs_causal_treatment(df, treatment, NULL)
t <- tr_info$t
treated_level <- tr_info$treated
control_level <- tr_info$control
y_info <- cs_causal_outcome(df, outcome)
y <- y_info$y
event_level <- y_info$event
des <- cs_causal_design(df, covariates)
X <- des$X
labels <- des$labels
binary <- des$binary
if (ncol(X) > 0) cs_causal_check_rank(X, labels)
n <- length(t)
n_treated <- as.integer(sum(t))
n_control <- as.integer(n - sum(t))
outcome_text <- if (!is.null(event_level)) sprintf("%s = %s", outcome, event_level) else outcome
contrast_text <- sprintf("%s = %s vs %s", treatment, treated_level, control_level)
benchmarks <- c("re74", "race")
pair_col <- NULL
alpha <- 0.05
kds <- as.numeric(unlist(c(1, 2, 3)))
if (!length(kds)) kds <- 1
rare_opt <- "auto"
gamma_max <- 3
gamma_step <- 0.1
missing_b <- setdiff(benchmarks, covariates)
if (length(missing_b)) stop(sprintf("Benchmark covariates must also be confounders: %s", paste(missing_b, collapse = ", ")))
# %% Adjusted regression: y ~ treatment + covariates, read by sensemakr
Xn <- X
colnames(Xn) <- if (ncol(X)) paste0("X", seq_len(ncol(X))) else character(0)
data <- cbind(data.frame(.y = y, .d = t), as.data.frame(Xn))
fit <- lm(.y ~ ., data = data)
ss <- sensemakr::sensitivity_stats(fit, treatment = ".d", q = 1, alpha = alpha)
est <- ss$estimate
se <- ss$se
t_stat <- ss$t_statistic
dof <- fit$df.residual
p_value <- 2 * stats::pt(abs(t_stat), dof, lower.tail = FALSE)
crit <- stats::qt(1 - (1 - conf) / 2, dof)
ci_low <- est - crit * se
ci_high <- est + crit * se
r2yd <- ss$r2yd.x
rv_q1 <- as.numeric(sensemakr::robustness_value(fit, covariates = ".d", q = 1, alpha = 1))
rv_qa <- as.numeric(ss$rv_qa)
values <- list()
# %% Bounds from benchmark covariates (sensemakr::ovb_bounds; impossible k values are skipped)
bounds <- list()
for (bench in benchmarks) {
cols <- colnames(Xn)[des$sources == bench]
if (!length(cols)) { # a category with one level left has no design columns (sensemakr can't use it)
warnings <- c(warnings, sprintf("%s has no variation in the analyzed rows, so it gives no benchmark bound.", bench))
next
}
for (kd in kds) {
bb <- tryCatch(suppressWarnings(sensemakr::ovb_bounds(fit, treatment = ".d", benchmark_covariates = stats::setNames(list(cols), bench),
kd = kd, ky = kd, alpha = alpha)), error = function(e) NULL)
if (is.null(bb) || !nrow(bb)) next
label <- sprintf("%s ×%s", bench, sprintf("%g", kd))
adj <- cs_causal_ovb_adjusted(est, se, dof, bb$r2dz.x[1], bb$r2yz.dx[1], alpha)
bounds[[length(bounds) + 1]] <- list(label = label, benchmark = bench, kd = kd, r2dz = bb$r2dz.x[1], r2yz = bb$r2yz.dx[1],
estimate = bb$adjusted_estimate[1], se = bb$adjusted_se[1], ci_low = bb$adjusted_lower_CI[1],
ci_high = bb$adjusted_upper_CI[1], t = adj$t)
values[[sprintf("bound_r2dz[%s]", label)]] <- bb$r2dz.x[1]
values[[sprintf("bound_r2yz[%s]", label)]] <- bb$r2yz.dx[1]
values[[sprintf("bound_estimate[%s]", label)]] <- bb$adjusted_estimate[1]
values[[sprintf("bound_ci_low[%s]", label)]] <- bb$adjusted_lower_CI[1]
values[[sprintf("bound_ci_high[%s]", label)]] <- bb$adjusted_upper_CI[1]
}
}
lim <- min(0.95, max(c(0.4, vapply(bounds, function(r) 1.25 * max(r$r2dz, r$r2yz), numeric(1)))))
grid <- cs_causal_ovb_contour(est, se, dof, lim, lim)
# %% E-value (EValue package)
if (is.null(event_level)) {
sd_y <- stats::sd(y)
ev <- suppressMessages(EValue::evalues.MD(est / sd_y, se / sd_y))
measure <- "SMD"
} else {
gl <- suppressWarnings(glm(.y ~ ., family = binomial(), data = data, control = glm.control(epsilon = 1e-14, maxit = 100)))
zc <- stats::qnorm(1 - (1 - conf) / 2)
bl <- unname(coef(gl)[".d"])
sel <- sqrt(vcov(gl)[".d", ".d"])
rare <- if (rare_opt == "auto") mean(y) < 0.15 else rare_opt == "rare"
ev <- suppressMessages(EValue::evalues.OR(exp(bl), exp(bl - zc * sel), exp(bl + zc * sel), rare = rare))
measure <- if (rare) "OR (rare outcome)" else "OR (common outcome, √OR)"
}
ev_point <- unname(ev[2, "point"])
ev_ci <- unname(if (ev[1, "point"] > 1) ev[2, "lower"] else ev[2, "upper"])
if (is.na(ev_ci)) ev_ci <- 1
ev_rr <- unname(ev[1, "point"])
# %% Rosenbaum bounds for matched pairs (twin of rbounds::psens with unrounded p-values)
ros <- NULL
if (!is.null(pair_col)) {
p <- as.character(df[[pair_col]])
diffs <- vapply(unique(p), function(key) {
m <- p == key
if (sum(m) != 2 || sum(t[m]) != 1) stop(sprintf("Pair '%s' must have exactly one treated and one control row.", key))
y[m & t == 1] - y[m & t == 0]
}, numeric(1))
ros <- cs_causal_rosenbaum(unname(diffs), gamma_max, gamma_step, alpha)
values$gamma_critical <- ros$gamma_critical
values$rosenbaum_p1 <- ros$rows[[1]]$p_upper
values$n_pairs <- ros$n_pairs
}
# %% Checks
if (length(bounds)) {
k1 <- Filter(function(r) r$kd == 1, bounds)
if (!length(k1)) k1 <- bounds
survives <- all(vapply(k1, function(r) if (est > 0) r$ci_low > 0 else r$ci_high < 0, logical(1)))
worst <- paste(sort(unique(vapply(k1, `[[`, "", "benchmark")), method = "radix"), collapse = ", ")
check <- list(id = "robustness", label = "Robust to benchmark-strength confounding", status = if (survives) "pass" else "concern",
detail = if (survives) sprintf("A confounder as strong as %s would not remove the effect or its significance.", worst)
else sprintf("A confounder as strong as %s could make the effect non-significant.", worst))
} else {
check <- list(id = "robustness", label = "Robust to confounding", status = "info",
detail = sprintf("RV = %s: a confounder explaining that share of the residual variance of treatment and outcome would remove the effect. Add benchmark covariates to judge plausibility.", cs_causal_pct1(rv_q1)))
}
checks <- list(check)
if (!is.null(ros)) {
checks[[2]] <- list(id = "rosenbaum", label = "Rosenbaum bounds", status = "info",
detail = sprintf("The signed-rank test stays significant at α = %s up to Γ = %.2f.", sprintf("%g", alpha), ros$gamma_critical))
}
# %% Result
effect_label <- sprintf("Regression-adjusted effect of %s on %s", contrast_text, outcome_text)
pct <- sprintf("%.0f%%", conf * 100)
summary <- paste0(
sprintf("Adjusted for %d covariate(s), the effect of %s vs %s on %s is %s (%s CI [%s, %s]). ", length(covariates), treated_level, control_level,
outcome_text, cs_fmt_num(est), pct, cs_fmt_num(ci_low), cs_fmt_num(ci_high)),
sprintf("An unmeasured confounder would have to explain %s of the residual variance of both treatment and outcome to remove the effect (RV) and %s to make it non-significant at α = %s (RV_α). ",
cs_causal_pct1(rv_q1), cs_causal_pct1(rv_qa), sprintf("%g", alpha)),
sprintf("E-value: %.2f for the estimate and %.2f for the confidence limit.", ev_point, ev_ci),
if (!is.null(ros)) sprintf(" Rosenbaum bounds: significant up to Γ = %.2f.", ros$gamma_critical) else "")
values <- c(values, list(
estimate = est, se = se, ci_low = ci_low, ci_high = ci_high, t_stat = t_stat, p_value = p_value, dof = dof, n = n,
partial_r2_treatment = r2yd, rv_q1 = rv_q1, rv_qa = rv_qa, evalue_point = ev_point, evalue_ci = ev_ci, evalue_rr = ev_rr,
evalue_measure = measure, estimand = "ATE (regression-adjusted)", effect_label = effect_label, claim_level_max = "L2",
treated_level = treated_level, control_level = control_level))
nb <- length(bounds)
charts <- list(cs_chart("contour", "contour-grid", "Adjusted estimate by confounder strength", list(
x = cs_col("Partial R² of confounder with treatment", c(grid$x, vapply(bounds, `[[`, 0, "r2dz"))),
y = cs_col("Partial R² of confounder with outcome", c(grid$y, vapply(bounds, `[[`, 0, "r2yz"))),
z = cs_col("Adjusted estimate", c(grid$z, vapply(bounds, `[[`, 0, "estimate"))),
kind = cs_col("Kind", c(rep("grid", length(grid$x)), rep("point", nb)), kind = "categorical"),
label = cs_col("Benchmark", c(rep("", length(grid$x)), vapply(bounds, `[[`, "", "label")), kind = "categorical")),
controls = list(levels = 10, zero_line = TRUE)))
tables <- list(list(key = "sensitivity", title = "Sensitivity statistics", columns = list(
list(key = "statistic", label = "Statistic", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(list(statistic = "Estimate", value = est), list(statistic = "Standard error", value = se), list(statistic = "t", value = t_stat),
list(statistic = "Partial R² of treatment with outcome", value = r2yd), list(statistic = "Robustness value RV", value = rv_q1),
list(statistic = sprintf("Robustness value RV (α = %s)", sprintf("%g", alpha)), value = rv_qa),
list(statistic = sprintf("E-value (%s)", measure), value = ev_point), list(statistic = "E-value of the confidence limit", value = ev_ci))))
if (nb) {
tables[[length(tables) + 1]] <- list(key = "bounds", title = "Bounds from benchmark covariates", columns = list(
list(key = "label", label = "Confounder as strong as", type = "string"), list(key = "r2dz", label = "R² with treatment", type = "number"),
list(key = "r2yz", label = "R² with outcome", type = "number"), list(key = "estimate", label = "Adjusted estimate", type = "number"),
list(key = "ci_low", label = "CI low", type = "number"), list(key = "ci_high", label = "CI high", type = "number")),
rows = lapply(bounds, function(r) r[c("label", "r2dz", "r2yz", "estimate", "ci_low", "ci_high")]),
note = sprintf("Partial R² bounds (Cinelli & Hazlett 2020, §4.4); intervals at α = %s.", sprintf("%g", alpha)))
}
if (!is.null(ros)) {
tables[[length(tables) + 1]] <- list(key = "rosenbaum", title = "Rosenbaum bounds (Wilcoxon signed-rank)", columns = list(
list(key = "gamma", label = "Γ", type = "number"), list(key = "p_upper", label = "Upper-bound p", type = "pvalue"),
list(key = "p_lower", label = "Lower-bound p", type = "pvalue")), rows = ros$rows,
note = sprintf("%d pairs with a non-zero difference; test in the direction of the observed effect (%s).", ros$n_pairs, ros$direction))
}
cs_publish(list(
method = "causal.sensitivity",
methodVersion = "1.0.2",
title = "Sensitivity to unmeasured confounding",
engine = cs_engine_info("stats", "nanoparquet", "sensemakr", "EValue"),
n = n,
summary = summary,
statistics = list(
list(key = "estimate", label = "Adjusted effect", value = est),
list(key = "rv_q1", label = "Robustness value", value = rv_q1),
list(key = "rv_qa", label = "Robustness value (α)", value = rv_qa),
list(key = "evalue_point", label = "E-value", value = ev_point)),
tables = tables,
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,
notes = list("Omitted-variable-bias bounds assume a single confounder (or group) acting linearly; E-values use VanderWeele's approximations."),
charts = charts,
values = values
))
Sources
- Cinelli, C., & Hazlett, C. (2020). Making sense of sensitivity: Extending omitted variable bias. JRSS-B, 82, 39–67.
- VanderWeele, T. J., & Ding, P. (2017). Sensitivity analysis in observational research: Introducing the E-value. Annals of Internal Medicine, 167, 268–274.
- Rosenbaum, P. R. (2002). Observational studies (2nd ed.). Springer.
From the CodeSplash method registry · causal.sensitivity v1.0.2.