What if you missed a confounder?
Ask how strong an unmeasured confounder would have to be, using robustness values, E-values and Rosenbaum bounds.
What runs in CodeSplash
- Sensitivity to unmeasured confounding (sensemakr, E-values, Rosenbaum bounds) Verified in Python and R
You will be able to
- Read a robustness value and compare it with measured covariates
- Interpret an E-value on the risk-ratio scale
- Use Rosenbaum's Γ for matched pairs
Read first
The question you can answer
ReadYou can't test for a confounder you didn't measure. You can ask how strong one would have to be to change your conclusion.
If a weak confounder could overturn it, be cautious. If it would need to be stronger than anything you measured, you have some reassurance. That's still not proof.
Robustness value
ReadThe robustness valueRobustness valueThe share of residual variance a confounder must explain in both treatment and outcome to wipe out the effect. is the share of residual variance a confounder must explain, in both treatment and outcome, to drive the estimate to zero.
How fragile is it?
PredictPredict first
On the LaLonde data, the regression estimate is $1,548 with p = .048. How much residual variance must a confounder explain, in both treatment and outcome, to reduce it to zero?
Reveal
7.7%. To make it merely non-significant, far less: 0.07%. A marginal result can be overturned by almost anything.
See it
In the appAdjusted 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.
The exact R script · R 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
))
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.
The exact Python script · Python 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,
})
Shortened for the Academy: 1 chart(s) dropped to stay under 100 KB; 1 chart(s) dropped to stay under 100 KB.
Benchmarks compare against things you did measure: "a confounder as strong as prior earnings". That's far easier to judge than a raw percentage. The contour plot shows where such a confounder would take the estimate.
E-values
In the appFor a risk ratio, the E-valueE-valueHow strongly an unmeasured confounder would have to relate to both treatment and outcome to explain an effect away. is the strength of association, with both treatment and outcome, that could explain the result away:
On a simulated binary outcome, the E-value is 8.25 for the estimate and 6.68 for the interval's limit. A confounder weaker than that couldn't explain it all.
Adjusted for 4 covariate(s), the effect of true vs false on converted = true is 0.35 (90% CI [0.31, 0.38]). An unmeasured confounder would have to explain 37.4% of the residual variance of both treatment and outcome to remove the effect (RV) and 34.4% to make it non-significant at α = 0.1 (RV_α). E-value: 8.25 for the estimate and 6.68 for the confidence limit.
- Adjusted effect
- 0.3454
- Robustness value
- 0.3737
- Robustness value (α)
- 0.3436
- E-value
- 8.249
Assumptions
- Robust to benchmark-strength confounding — A confounder as strong as x1 would not remove the effect or its significance.
Sensitivity statistics
| Statistic | Value |
|---|---|
| Estimate | 0.3454 |
| Standard error | 0.0213 |
| t | 16.204 |
| Partial R² of treatment with outcome | 0.1823 |
| Robustness value RV | 0.3737 |
| Robustness value RV (α = 0.1) | 0.3436 |
| E-value (OR (common outcome, √OR)) | 8.249 |
| E-value of the confidence limit | 6.678 |
Bounds from benchmark covariates
| Confounder as strong as | R² with treatment | R² with outcome | Adjusted estimate | CI low | CI high |
|---|---|---|---|---|---|
| x1 ×1 | 0.1231 | 0.6369 | 0.1267 | 0.1041 | 0.1493 |
| x1 ×2 | 0.2462 | 1 | −0.0727 | −0.0727 | −0.0727 |
Partial R² bounds (Cinelli & Hazlett 2020, §4.4); intervals at α = 0.1.
- 15 of 1200 rows were left out because a value was missing.
- Omitted-variable-bias bounds assume a single confounder (or group) acting linearly; E-values use VanderWeele's approximations.
The exact R script · R 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 5fada1005253d762
# Dataset: c2_obs (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_obs.parquet", col_select = c("converted", "treated", "x1", "x2", "segment", "member")))
n_input <- nrow(df)
df[["converted"]] <- factor(df[["converted"]], levels = c("false", "true")) # stored level order
df[["treated"]] <- factor(df[["treated"]], levels = c("false", "true")) # stored level order
df[["segment"]] <- factor(df[["segment"]], levels = c("a", "b", "c")) # stored level order
df[["member"]] <- factor(df[["member"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("converted", "treated", "x1", "x2", "segment", "member")]), , 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("converted", "treated", "x1", "x2", "segment", "member")) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment <- "treated"
outcome <- "converted"
covariates <- c("x1", "x2", "segment", "member")
conf <- 0.9
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("x1")
pair_col <- NULL
alpha <- 0.1
kds <- as.numeric(unlist(c(1, 2)))
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
))
Adjusted for 4 covariate(s), the effect of true vs false on converted = true is 0.35 (90% CI [0.31, 0.38]). An unmeasured confounder would have to explain 37.4% of the residual variance of both treatment and outcome to remove the effect (RV) and 34.4% to make it non-significant at α = 0.1 (RV_α). E-value: 8.25 for the estimate and 6.68 for the confidence limit.
- Adjusted effect
- 0.3454
- Robustness value
- 0.3737
- Robustness value (α)
- 0.3436
- E-value
- 8.249
Assumptions
- Robust to benchmark-strength confounding — A confounder as strong as x1 would not remove the effect or its significance.
Sensitivity statistics
| Statistic | Value |
|---|---|
| Estimate | 0.3454 |
| Standard error | 0.0213 |
| t | 16.204 |
| Partial R² of treatment with outcome | 0.1823 |
| Robustness value RV | 0.3737 |
| Robustness value RV (α = 0.1) | 0.3436 |
| E-value (OR (common outcome, √OR)) | 8.249 |
| E-value of the confidence limit | 6.678 |
Bounds from benchmark covariates
| Confounder as strong as | R² with treatment | R² with outcome | Adjusted estimate | CI low | CI high |
|---|---|---|---|---|---|
| x1 ×1 | 0.1231 | 0.6369 | 0.1267 | 0.1041 | 0.1493 |
| x1 ×2 | 0.2462 | 1 | −0.0727 | −0.0727 | −0.0727 |
Partial R² bounds (Cinelli & Hazlett 2020, §4.4); intervals at α = 0.1.
- 15 of 1200 rows were left out because a value was missing.
- Omitted-variable-bias bounds assume a single confounder (or group) acting linearly; E-values use VanderWeele's approximations.
The exact Python script · Python 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 5fada1005253d762
# Dataset: c2_obs (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_obs.parquet", columns=["converted", "treated", "x1", "x2", "segment", "member"])
n_input = len(df)
df["converted"] = pd.Categorical(df["converted"], categories=["false", "true"]) # stored level order
df["treated"] = pd.Categorical(df["treated"], categories=["false", "true"]) # stored level order
df["segment"] = pd.Categorical(df["segment"], categories=["a", "b", "c"]) # stored level order
df["member"] = pd.Categorical(df["member"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["converted", "treated", "x1", "x2", "segment", "member"]) # listwise deletion over the analysis columns
df["converted"] = df["converted"].cat.remove_unused_categories()
df["treated"] = df["treated"].cat.remove_unused_categories()
df["segment"] = df["segment"].cat.remove_unused_categories()
df["member"] = df["member"].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, ["converted", "treated", "x1", "x2", "segment", "member"]) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment = "treated"
outcome = "converted"
covariates = ["x1", "x2", "segment", "member"]
conf = 0.9
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 = ["x1"]
pair_col = None
alpha = 0.1
kds = [float(k) for k in [1, 2]] 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,
})
Shortened for the Academy: 1 chart(s) dropped to stay under 100 KB; 1 chart(s) dropped to stay under 100 KB.
Rosenbaum bounds
ReadFor matched pairs, Rosenbaum's ΓRosenbaum boundsFor matched pairs, how large a hidden bias in treatment odds (Γ) the conclusion could survive. says how much hidden bias in treatment odds the result can bear. Within a pair, one person's odds of treatment could be up to Γ times the other's.
Here the conclusion holds up to Γ = 1.78.
Check your understanding
CheckpointCheck yourself
A study reports a risk ratio of 2. What's its E-value? Give two decimals.
Show the answer
Answer: 3.41
. A confounder would need a risk ratio of about 3.4 with both treatment and outcome to explain the result away.
Check yourself
A high E-value tells you:
Show the answer
Answer: b
Sensitivity analysis moves the argument from "is there a confounder?" to "could one this strong exist?". It doesn't end the argument.
Check yourself
A confounder as strong as your strongest measured covariate would overturn the result. What should you conclude?
Show the answer
Answer: b
Benchmarks anchor the abstract numbers. If a plausible omission overturns the result, say so plainly.
Add it to your study
In the appIn the Causal studio, the Robustness step has a card for sensitivity to unmeasured confounding. Without it, a selection-on-observables design can't earn its full claim level.
Method guide · causal.sensitivitySensitivity to unmeasured confounding (sensemakr, E-values, Rosenbaum bounds)How strong would an unmeasured confounder have to be to explain away the estimated effect?Recap
Recap- You can't test for an unmeasured confounder, but you can measure how strong one would need to be.
- Benchmark against covariates you did measure, to make the number meaningful.
- A sensitivity analysis informs your judgment; it doesn't replace it.
Concepts in this lesson