DRegression models · regression.mediation
Mediation analysis
How much of an exposure's effect on an outcome runs through a mediator, and how much is direct?
Causal mediation with linear mediator and outcome models (Imai–Keele–Tingley; VanderWeele): the average causal mediation effect (indirect, ACME), the average direct effect (ADE), the total effect and the proportion mediated, each for the exposure held at control and at treatment when the exposure–mediator interaction is included. Intervals by the nonparametric bootstrap, quasi-Bayesian simulation or the delta method (Sobel), with the a and b paths. The effects are causal only under sequential ignorability: no unmeasured confounding of exposure–mediator, exposure–outcome and mediator–outcome, and no mediator–outcome confounder affected by the exposure.
A real result
Example “Bootstrap binary exposure”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
ACME = 1.40, 95% CI [1.01, 1.82], p < .001
- ACME (indirect)
- 1.404
- p
- < .001
- ADE (direct)
- 1.609
- Total
- 3.014
- Proportion mediated
- 0.4659
Plots
View data
| Estimate | high | Effect | low |
|---|---|---|---|
| 1.404 | 1.824 | ACME (average) | 1.007 |
| 1.609 | 1.959 | ADE (average) | 1.204 |
| 3.014 | 3.481 | Total effect | 2.479 |
Assumptions
- Sequential ignorability — Not testable: the effects are causal only if no unmeasured variable confounds exposure–mediator, exposure–outcome or mediator–outcome beyond the 2 covariates adjusted for.
- Exposure × mediator interaction — In a model with the interaction its coefficient is 0.350 (p = .051); leaving it out is reasonable.
- Exposure → mediator → outcome in time — motivation should be measured after treat and before score; otherwise the indirect effect has no causal meaning.
Effects of treat (true vs false)
| Effect | Estimate | 95% CI low | 95% CI high | p |
|---|---|---|---|---|
| ACME (average) | 1.404 | 1.007 | 1.824 | < .001 |
| ADE (average) | 1.609 | 1.204 | 1.959 | < .001 |
| Total effect | 3.014 | 2.479 | 3.481 | < .001 |
| Proportion mediated | 0.4659 | 0.3707 | 0.5730 | < .001 |
ACME: the change in the outcome when only the mediator moves as the exposure would move it; ADE: the change with the mediator held fixed.
Model paths
| Path | B | SE | t | p |
|---|---|---|---|---|
| a: treat → motivation | 0.9004 | 0.1221 | 7.375 | < .001 |
| b: motivation → score (given treat) | 1.559 | 0.0919 | 16.964 | < .001 |
| c′: treat → score (direct) | 1.609 | 0.2098 | 7.672 | < .001 |
- Linear mediator and outcome models (OLS); covariates at their sample means. Intervals: nonparametric bootstrap (500 of 500 resamples, percentile intervals). Seed 42: the same draws in Python and R.
ACME = 1.40, 95% CI [1.01, 1.82], p < .001
- ACME (indirect)
- 1.404
- p
- < .001
- ADE (direct)
- 1.609
- Total
- 3.014
- Proportion mediated
- 0.4659
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Sequential ignorability — Not testable: the effects are causal only if no unmeasured variable confounds exposure–mediator, exposure–outcome or mediator–outcome beyond the 2 covariates adjusted for.
- Exposure × mediator interaction — In a model with the interaction its coefficient is 0.350 (p = .051); leaving it out is reasonable.
- Exposure → mediator → outcome in time — motivation should be measured after treat and before score; otherwise the indirect effect has no causal meaning.
Effects of treat (true vs false)
| Effect | Estimate | 95% CI low | 95% CI high | p |
|---|---|---|---|---|
| ACME (average) | 1.404 | 1.007 | 1.824 | < .001 |
| ADE (average) | 1.609 | 1.204 | 1.959 | < .001 |
| Total effect | 3.014 | 2.479 | 3.481 | < .001 |
| Proportion mediated | 0.4659 | 0.3707 | 0.5730 | < .001 |
ACME: the change in the outcome when only the mediator moves as the exposure would move it; ADE: the change with the mediator held fixed.
Model paths
| Path | B | SE | t | p |
|---|---|---|---|---|
| a: treat → motivation | 0.9004 | 0.1221 | 7.375 | < .001 |
| b: motivation → score (given treat) | 1.559 | 0.0919 | 16.964 | < .001 |
| c′: treat → score (direct) | 1.609 | 0.2098 | 7.672 | < .001 |
- Linear mediator and outcome models (OLS); covariates at their sample means. Intervals: nonparametric bootstrap (500 of 500 resamples, percentile intervals). Seed 42: the same draws in Python and R.
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
- Bootstrap binary exposurec3_mediation · covariates: age, region · exposure: treat · mediator: motivation · outcome: score
- Quasi bayes interactionc3_mediation · covariates: age · exposure: treat · mediator: motivation · outcome: score
- Delta numeric dosec3_mediation · covariates: treat, age · exposure: dose · mediator: motivation · outcome: score
- Degenerate constantc3_mediation · covariates: age, region · exposure: treat · mediator: motivation · outcome: score
- Degenerate n3c3_mediation · covariates: age, region · exposure: treat · mediator: motivation · outcome: score
- Degenerate single levelc3_mediation · covariates: age, region · exposure: treat · mediator: motivation · outcome: score
In the guides
Where it sits in the decision guides
- Continuous outcome: linear regression · Statistics Guide · D — Predict an outcome
- Model selection and structure (penalized, stepwise, SEM) · Statistics Guide · D — Predict an outcome
- Interactions · Statistics Guide · Additional considerations
- Causal inference (experiments, DiD, IV, RDD) · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Outcomenumeric · 1 column
- The numeric result the exposure may change, directly or through the mediator.
- Exposure (treatment)numeric / boolean / categorical · 1 column · 2–2 levels
- A two-level treatment (the second stored level is 'treated') or a numeric dose.
- Mediatornumeric · 1 column
- Measured after the exposure and before the outcome.
- Covariatesnumeric / categorical / boolean · 0–10 columns · 2–30 levels
- Pre-exposure confounders of any of the three relationships; both models adjust for them.
Choices you make
hypothesis
- Confidence leveldefault 0.95
Coverage of the effect intervals; 0.95 gives 95% intervals and tests at α = 0.05.
statistics
- Exposure × mediator interactiondefault off
Lets the mediator's effect on the outcome differ by exposure; effects are then reported with the exposure held at control and at treatment.
- Intervalsdefault bootstrap
How the uncertainty of the indirect effect is estimated; the bootstrap makes the fewest assumptions.
- Nonparametric bootstrap (percentile)(default) — Resamples rows and refits both models; no normality assumption for the indirect effect.
- Quasi-Bayesian simulation — Draws both models' coefficients from their estimated sampling distributions (mediation::mediate's default).
- Delta method (Sobel) — First-order normal approximation of a·b; only without the interaction, and too narrow in small samples.
- Resamples / simulationsdefault 1000
1,000 is enough for 95% intervals; more steadies the interval ends.
- Exposure control valuedefault —
The exposure level effects are measured from (numeric exposures).
- Exposure treatment valuedefault —
The exposure level effects are measured to (numeric exposures).
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.
Sequential ignorability
No unmeasured confounding of exposure, mediator and outcome, and no exposure-caused mediator–outcome confounder. Not testable.
Exposure × mediator interaction
Whether the mediator affects the outcome differently when exposed; if so, include the interaction term.
- If violated → Include the exposure × mediator interaction — The mediator's effect on the outcome differs by exposure, so a single indirect effect hides two; with the interaction, effects are reported at control and at treatment. Changes the question: ACME and ADE become averages of the control and treated versions.
Exposure → mediator → outcome in time
The mediator must be measured after the exposure and before the outcome for the indirect effect to be causal.
What it reports
- Tests: Indirect effect (ACME) is zero
- Tests: Direct effect (ADE) is zero
- n
- How many independent units the analysis used; it sets precision and power.
- x0
- Exposure value the effects are measured from. 0 for yes/no or two-level exposures, which are coded 0 and 1.
- x1
- Exposure value the effects are measured to. 1 for yes/no or two-level exposures, which are coded 0 and 1.
- interaction
- True when the outcome model includes an exposure × mediator term, letting effects differ between control and treatment.
- ci_method
- A range of effect values compatible with your data at the chosen confidence level.
- sims
- Estimating a quantity by drawing many random samples and summarizing the results.
- n_used
- How many independent units the analysis used; it sets precision and power.
- n_failed
- How many independent units the analysis used; it sets precision and power.
- acme
- The part of a treatment's effect that passes through the mediator.
- acme_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- acme_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- acme_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- ade
- The part of a treatment's effect that doesn't pass through the mediator.
- ade_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ade_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- ade_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- total
- Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
- total_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- total_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- total_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- prop_mediated
- The share of the total effect that goes through the mediator. Unstable when the total effect is small.
- prop_mediated_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- prop_mediated_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- prop_mediated_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- acme_control
- The part of a treatment's effect that passes through the mediator.
- acme_treated
- The part of a treatment's effect that passes through the mediator.
- ade_control
- The part of a treatment's effect that doesn't pass through the mediator.
- ade_treated
- The part of a treatment's effect that doesn't pass through the mediator.
- acme_control_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- acme_control_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- acme_treated_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- acme_treated_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- ade_control_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ade_control_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- ade_treated_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ade_treated_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- a
- Asks whether rows within groups are closer than random sets of the same sizes; A = 1 − δ/E(δ).
- a_se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- a_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- b
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- b_se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- b_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- c_prime
- The part of a treatment's effect that doesn't pass through the mediator.
- c_prime_se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- c_prime_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- xm
- Coefficient of the exposure × mediator term in an outcome model that includes it; fitted as a check even when the term is off.
- xm_se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- xm_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- sobel_z
- An estimate in standard-error units, compared with the standard normal distribution.
- sobel_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines resample (bootstrap) or draw coefficients (quasi-Bayes) from the same Wichmann–Hill stream, so the replicates, intervals and p-values agree to rounding.
- mediation::mediate reports the mean of the simulations as its point estimate; CodeSplash reports the estimate from the fitted models (the simulations give the interval and p only).
The exact script CodeSplash ran for example “Bootstrap binary exposure” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Mediation analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.mediation 1.0.1 · spec c31703dd14cd7fc1
# Dataset: c3_mediation (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 stats
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import mediation as csmed
from codesplash.stats import regression as csreg
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c3_mediation.parquet", columns=["score", "treat", "motivation", "age", "region"])
n_input = len(df)
df["treat"] = pd.Categorical(df["treat"], categories=["false", "true"]) # stored level order
df["region"] = pd.Categorical(df["region"], categories=["North", "South", "West"]) # stored level order
df = df.dropna(subset=["score", "treat", "motivation", "age", "region"]) # listwise deletion over the analysis columns
df["treat"] = df["treat"].cat.remove_unused_categories()
df["region"] = df["region"].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, ["score", "treat", "motivation", "age", "region"]) # infinite values stop the run (registry/errors.yaml)
# %% Variables
outcome = "score"
exposure = "treat"
mediator = "motivation"
covariates = ["age", "region"]
interaction = False # exposure × mediator term in the outcome model
ci_method = "bootstrap" # bootstrap | quasi_bayes | delta
sims = int(500)
seed = 42 # portable Wichmann–Hill stream: R draws the same resamples for this seed
conf = 0.95
control_value = None
treat_value = None
if ci_method == "delta" and interaction:
raise ValueError("The delta method covers the product a·b only; use the bootstrap or quasi-Bayesian intervals with the interaction.")
ex = df[exposure]
if isinstance(ex.dtype, pd.CategoricalDtype):
levels = [str(v) for v in ex.cat.categories]
if len(levels) != 2:
cs.cs_error("CS_E_GROUP_COUNT", column=exposure, expected=2, k=len(levels))
x = (ex.astype(str) == levels[1]).to_numpy(dtype=float)
x0, x1, contrast = 0.0, 1.0, f"{levels[1]} vs {levels[0]}"
elif ex.dtype == bool:
x = ex.to_numpy(dtype=float)
x0, x1, contrast = 0.0, 1.0, "true vs false"
else:
x = ex.to_numpy(dtype=float)
x0 = 0.0 if control_value is None else float(control_value)
x1 = 1.0 if treat_value is None else float(treat_value)
if x0 == x1:
raise ValueError("The control and treatment values of the exposure must differ.")
contrast = f"{x1:g} vs {x0:g}"
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than coefficients of the largest model: the outcome model with the exposure × mediator
# term (always fitted, to check the interaction) has 4 coefficients plus the covariate columns.
k_cov = csreg.design_matrix(df, covariates, "none").shape[1] - 1
cs.check_rows(len(df), 4 + k_cov + 1, "Mediation analysis")
for col in [outcome, exposure, mediator] + covariates:
check_not_constant(df[col], col) # one value (or one level with data) is no variation
m = df[mediator].to_numpy(dtype=float)
y = df[outcome].to_numpy(dtype=float)
if covariates:
C = csreg.design_matrix(df, covariates, "none").drop(columns="(Intercept)").to_numpy(dtype=float)
else:
C = np.zeros((len(df), 0))
n = len(df)
cbar = C.mean(axis=0) if C.shape[1] else np.zeros(0)
# %% Fit the mediator and outcome models
fm, fy = csmed.fit(x, m, y, C, interaction)
_, fy_int = csmed.fit(x, m, y, C, True) # with the interaction, to check it
def path(fit, j):
est, se = float(fit["coef"][j]), float(np.sqrt(fit["cov"][j, j]))
return est, se, est / se, float(2 * stats.t.sf(abs(est / se), fit["df"]))
a, a_se, a_t, a_p = path(fm, 1)
b, b_se, b_t, b_p = path(fy, 2)
c_prime, c_se, c_t, c_p = path(fy, 1)
xm, xm_se, xm_t, xm_p = path(fy_int, 3)
point = csmed.effects(fm["coef"], fy["coef"], x0, x1, cbar, interaction)
# %% Intervals
n_failed = 0
if ci_method == "delta":
delta = x1 - x0
va = fm["cov"][1, 1]
cy = fy["cov"][np.ix_([1, 2], [1, 2])] # (c', b)
sig = np.array([[va, 0, 0], [0, cy[0, 0], cy[0, 1]], [0, cy[1, 0], cy[1, 1]]]) # θ = (a, c', b)
tot = c_prime + a * b
grads = {"acme": delta * np.array([b, 0, a]), "ade": delta * np.array([0, 1, 0]), "total": delta * np.array([b, 1, a]),
"prop_mediated": np.array([b * c_prime, -a * b, a * c_prime]) / tot**2}
zc = stats.norm.ppf(1 - (1 - conf) / 2)
summ = {}
for key, g in grads.items():
se_k = float(np.sqrt(g @ sig @ g))
est = point[key]
summ[key] = {"ci_low": est - zc * se_k, "ci_high": est + zc * se_k, "p": float(2 * stats.norm.sf(abs(est / se_k)))}
for key, src in (("acme_control", "acme"), ("acme_treated", "acme"), ("ade_control", "ade"), ("ade_treated", "ade")):
summ[key] = summ[src]
n_used = None
else:
if ci_method == "bootstrap":
draws, n_failed = csmed.bootstrap(x, m, y, C, interaction, x0, x1, sims, seed)
else:
draws = csmed.quasi_bayes(fm, fy, interaction, x0, x1, cbar, sims, seed)
summ = csmed.summarize(draws, conf)
n_used = int(draws.shape[0])
sobel_z = None if interaction else float(a * b / np.sqrt(b**2 * a_se**2 + a**2 * b_se**2))
sobel_p = None if interaction else float(2 * stats.norm.sf(abs(sobel_z)))
# %% Assumptions
assumptions = [
{"key": "ignorability", "label": "Sequential ignorability", "status": "info",
"detail": "Not testable: the effects are causal only if no unmeasured variable confounds exposure–mediator, exposure–outcome or mediator–outcome"
+ (f" beyond the {len(covariates)} covariates adjusted for." if covariates else "; no covariates are adjusted for.")},
({"key": "interaction", "label": "Exposure × mediator interaction", "status": "warn" if xm_p < 1 - conf else "pass", "p": xm_p,
"detail": f"In a model with the interaction its coefficient is {xm:.3f} ({cs.fmt_p(xm_p)})"
+ ("; the mediator's effect differs by exposure — include the interaction." if xm_p < 1 - conf else "; leaving it out is reasonable.")}
if not interaction else
{"key": "interaction", "label": "Exposure × mediator interaction", "status": "info", "p": xm_p,
"detail": f"Included: coefficient {xm:.3f} ({cs.fmt_p(xm_p)}); effects are reported with the exposure held at control and at treatment."}),
{"key": "ordering", "label": "Exposure → mediator → outcome in time", "status": "info",
"detail": f"{mediator} should be measured after {exposure} and before {outcome}; otherwise the indirect effect has no causal meaning."},
]
# %% Result
labels = {"acme_control": "ACME (control)", "acme_treated": "ACME (treated)", "ade_control": "ADE (control)", "ade_treated": "ADE (treated)",
"acme": "ACME (average)", "ade": "ADE (average)", "total": "Total effect", "prop_mediated": "Proportion mediated"}
order = ["acme_control", "acme_treated", "ade_control", "ade_treated", "acme", "ade", "total", "prop_mediated"] if interaction else ["acme", "ade", "total", "prop_mediated"]
def fin(v):
return None if v is None or not np.isfinite(v) else float(v)
effect_rows = [{"effect": labels[k], "estimate": fin(point[k]), "ci_low": fin(summ[k]["ci_low"]), "ci_high": fin(summ[k]["ci_high"]), "p": fin(summ[k]["p"])} for k in order]
values = {"n": n, "x0": x0, "x1": x1, "interaction": interaction, "ci_method": ci_method, "sims": sims if ci_method != "delta" else None,
"n_used": n_used, "n_failed": n_failed, "a": a, "a_se": a_se, "a_p": a_p, "b": b, "b_se": b_se, "b_p": b_p,
"c_prime": c_prime, "c_prime_se": c_se, "c_prime_p": c_p, "xm": xm, "xm_se": xm_se, "xm_p": xm_p, "sobel_z": sobel_z, "sobel_p": sobel_p,
"missing_share": n_dropped / n_input if n_input else 0.0}
for k in labels:
values[k] = fin(point[k])
if k in ("acme", "ade", "total", "prop_mediated"):
values.update({f"{k}_ci_low": fin(summ[k]["ci_low"]), f"{k}_ci_high": fin(summ[k]["ci_high"]), f"{k}_p": fin(summ[k]["p"])})
else:
values.update({f"{k}_ci_low": fin(summ[k]["ci_low"]), f"{k}_ci_high": fin(summ[k]["ci_high"])})
paths = [
{"path": f"a: {exposure} → {mediator}", "estimate": a, "se": a_se, "t": a_t, "p": a_p},
{"path": f"b: {mediator} → {outcome} (given {exposure})", "estimate": b, "se": b_se, "t": b_t, "p": b_p},
{"path": f"c′: {exposure} → {outcome} (direct)", "estimate": c_prime, "se": c_se, "t": c_t, "p": c_p},
] + ([{"path": f"{exposure} × {mediator}", "estimate": xm, "se": xm_se, "t": xm_t, "p": xm_p}] if interaction else [])
method_name = {"bootstrap": f"nonparametric bootstrap ({n_used} of {sims} resamples, percentile intervals)",
"quasi_bayes": f"quasi-Bayesian simulation ({sims} draws, percentile intervals)",
"delta": "delta method (normal approximation)"}[ci_method]
pct = f"{conf:.0%}"
pm = point["prop_mediated"]
summary = (f"Effect of {exposure} ({contrast}) on {outcome} through {mediator} (n = {n}): ACME = {point['acme']:.3f} "
f"[{summ['acme']['ci_low']:.3f}, {summ['acme']['ci_high']:.3f}], {cs.fmt_p(summ['acme']['p'])}; ADE = {point['ade']:.3f}; "
f"total = {point['total']:.3f}" + (f"; proportion mediated {pm:.2f}." if np.isfinite(pm) else "."))
cs.publish({
"method": "regression.mediation",
"methodVersion": "1.0.1",
"title": "Mediation analysis",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"ACME = {point['acme']:.2f}, {pct} CI [{summ['acme']['ci_low']:.2f}, {summ['acme']['ci_high']:.2f}], {cs.fmt_p(summ['acme']['p'])}",
"statistics": [{"key": "acme", "label": "ACME (indirect)", "value": fin(point["acme"])}, {"key": "acme_p", "label": "p", "value": fin(summ["acme"]["p"]), "format": "p"},
{"key": "ade", "label": "ADE (direct)", "value": fin(point["ade"])}, {"key": "total", "label": "Total", "value": fin(point["total"])},
{"key": "prop_mediated", "label": "Proportion mediated", "value": fin(pm)}],
"tables": [
{"key": "effects", "title": f"Effects of {exposure} ({contrast})", "columns": [
{"key": "effect", "label": "Effect", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}],
"rows": effect_rows, "note": "ACME: the change in the outcome when only the mediator moves as the exposure would move it; ADE: the change with the mediator held fixed."},
{"key": "paths", "title": "Model paths", "columns": [
{"key": "path", "label": "Path", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": paths},
],
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings + ([f"{n_failed} resamples lost a variable's variation and were skipped."] if n_failed else []),
"notes": [f"Linear mediator and outcome models (OLS){', outcome model with the exposure × mediator interaction' if interaction else ''}; covariates at their sample means. Intervals: {method_name}."
+ (f" Seed {seed}: the same draws in Python and R." if ci_method != "delta" else "")],
"charts": [cs.chart("effects", "forest", "Indirect, direct and total effects", {
"label": cs.col("Effect", [r["effect"] for r in effect_rows if r["effect"] != "Proportion mediated"], kind="categorical"),
"estimate": cs.col("Estimate", [r["estimate"] for r in effect_rows if r["effect"] != "Proportion mediated"]),
"low": cs.col("low", [r["ci_low"] for r in effect_rows if r["effect"] != "Proportion mediated"]),
"high": cs.col("high", [r["ci_high"] for r in effect_rows if r["effect"] != "Proportion mediated"])}, controls={"reference": 0})],
"values": values,
})
The exact script CodeSplash ran for example “Bootstrap binary exposure” · R version 4.5.1 (2025-06-13)
# Mediation analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.mediation 1.0.1 · spec c31703dd14cd7fc1
# Dataset: c3_mediation (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/c3_mediation.parquet", col_select = c("score", "treat", "motivation", "age", "region")))
n_input <- nrow(df)
df[["treat"]] <- factor(df[["treat"]], levels = c("false", "true")) # stored level order
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "West")) # stored level order
df <- df[stats::complete.cases(df[c("score", "treat", "motivation", "age", "region")]), , 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("score", "treat", "motivation", "age", "region")) # infinite values stop the run (registry/errors.yaml)
# %% Variables
outcome <- "score"
exposure <- "treat"
mediator <- "motivation"
covariates <- c("age", "region")
interaction <- FALSE # exposure x mediator term in the outcome model
ci_method <- "bootstrap" # bootstrap | quasi_bayes | delta
sims <- as.integer(500)
seed <- 42 # portable Wichmann-Hill stream: Python draws the same resamples for this seed
conf <- 0.95
control_value <- NULL
treat_value <- NULL
if (ci_method == "delta" && interaction) stop("The delta method covers the product a·b only; use the bootstrap or quasi-Bayesian intervals with the interaction.")
ex <- df[[exposure]]
if (is.factor(ex)) {
levels_ex <- levels(ex)
if (length(levels_ex) != 2) cs_error("CS_E_GROUP_COUNT", column = exposure, expected = 2, k = length(levels_ex))
x <- as.numeric(as.character(ex) == levels_ex[2])
x0 <- 0
x1 <- 1
contrast <- sprintf("%s vs %s", levels_ex[2], levels_ex[1])
} else if (is.logical(ex)) {
x <- as.numeric(ex)
x0 <- 0
x1 <- 1
contrast <- "true vs false"
} else {
x <- as.numeric(ex)
x0 <- if (is.null(control_value)) 0 else control_value
x1 <- if (is.null(treat_value)) 1 else treat_value
if (x0 == x1) stop("The control and treatment values of the exposure must differ.")
contrast <- sprintf("%s vs %s", sprintf("%g", x1), sprintf("%g", x0))
}
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than coefficients of the largest model: the outcome model with the exposure x mediator
# term (always fitted, to check the interaction) has 4 coefficients plus the covariate columns.
k_cov <- length(cs_design_labels(df, covariates)) - 1
cs_check_rows(nrow(df), 4 + k_cov + 1, "Mediation analysis")
for (col in c(outcome, exposure, mediator, covariates)) cs_check_not_constant(df[[col]], col) # one value (or one level with data) is no variation
m <- as.numeric(df[[mediator]])
y <- as.numeric(df[[outcome]])
C <- if (length(covariates)) unname(model.matrix(cs_model_formula(outcome, covariates, "none"), data = df)[, -1, drop = FALSE]) else matrix(0, nrow(df), 0)
n <- nrow(df)
cbar <- if (ncol(C)) colMeans(C) else numeric(0)
# %% Fit the mediator and outcome models
fits <- cs_med_fit(x, m, y, C, interaction)
fm <- fits$m
fy <- fits$y
fy_int <- cs_med_fit(x, m, y, C, TRUE)$y # with the interaction, to check it
path <- function(fit, j) {
est <- fit$coef[j]
se <- sqrt(fit$cov[j, j])
c(est = est, se = se, t = est / se, p = 2 * pt(abs(est / se), fit$df, lower.tail = FALSE))
}
pa <- path(fm, 2)
pb <- path(fy, 3)
pc <- path(fy, 2)
pxm <- path(fy_int, 4)
a <- unname(pa["est"]); a_se <- unname(pa["se"]); a_p <- unname(pa["p"])
b <- unname(pb["est"]); b_se <- unname(pb["se"]); b_p <- unname(pb["p"])
c_prime <- unname(pc["est"]); c_se <- unname(pc["se"]); c_p <- unname(pc["p"])
xm <- unname(pxm["est"]); xm_se <- unname(pxm["se"]); xm_p <- unname(pxm["p"])
keys <- c("acme_control", "acme_treated", "ade_control", "ade_treated", "acme", "ade", "total", "prop_mediated")
point <- setNames(as.list(cs_med_effects(fm$coef, fy$coef, x0, x1, cbar, interaction)), keys)
# %% Intervals
n_failed <- 0L
n_used <- NULL
if (ci_method == "delta") {
delta <- x1 - x0
sig <- matrix(0, 3, 3) # theta = (a, c', b)
sig[1, 1] <- fm$cov[2, 2]
sig[2:3, 2:3] <- fy$cov[2:3, 2:3]
tot <- c_prime + a * b
grads <- list(acme = delta * c(b, 0, a), ade = delta * c(0, 1, 0), total = delta * c(b, 1, a),
prop_mediated = c(b * c_prime, -a * b, a * c_prime) / tot^2)
zc <- qnorm(1 - (1 - conf) / 2)
summ <- list()
for (key in names(grads)) {
g <- grads[[key]]
se_k <- sqrt(drop(t(g) %*% sig %*% g))
est <- point[[key]]
summ[[key]] <- list(ci_low = est - zc * se_k, ci_high = est + zc * se_k, p = 2 * pnorm(abs(est / se_k), lower.tail = FALSE))
}
summ$acme_control <- summ$acme
summ$acme_treated <- summ$acme
summ$ade_control <- summ$ade
summ$ade_treated <- summ$ade
} else {
if (ci_method == "bootstrap") {
bs <- cs_med_bootstrap(x, m, y, C, interaction, x0, x1, sims, seed)
draws <- bs$draws
n_failed <- bs$failed
} else {
draws <- cs_med_quasi_bayes(fm, fy, interaction, x0, x1, cbar, sims, seed)
}
summ <- cs_med_summarize(draws, conf)
n_used <- nrow(draws)
}
sobel_z <- if (interaction) NULL else a * b / sqrt(b^2 * a_se^2 + a^2 * b_se^2)
sobel_p <- if (interaction) NULL else 2 * pnorm(abs(sobel_z), lower.tail = FALSE)
# %% Assumptions
assumptions <- list(
list(key = "ignorability", label = "Sequential ignorability", status = "info",
detail = paste0("Not testable: the effects are causal only if no unmeasured variable confounds exposure–mediator, exposure–outcome or mediator–outcome",
if (length(covariates)) sprintf(" beyond the %d covariates adjusted for.", length(covariates)) else "; no covariates are adjusted for.")),
if (!interaction) {
list(key = "interaction", label = "Exposure × mediator interaction", status = if (xm_p < 1 - conf) "warn" else "pass", p = xm_p,
detail = paste0(sprintf("In a model with the interaction its coefficient is %.3f (%s)", xm, cs_fmt_p(xm_p)),
if (xm_p < 1 - conf) "; the mediator's effect differs by exposure — include the interaction." else "; leaving it out is reasonable."))
} else {
list(key = "interaction", label = "Exposure × mediator interaction", status = "info", p = xm_p,
detail = sprintf("Included: coefficient %.3f (%s); effects are reported with the exposure held at control and at treatment.", xm, cs_fmt_p(xm_p)))
},
list(key = "ordering", label = "Exposure → mediator → outcome in time", status = "info",
detail = sprintf("%s should be measured after %s and before %s; otherwise the indirect effect has no causal meaning.", mediator, exposure, outcome))
)
# %% Result
labels <- c(acme_control = "ACME (control)", acme_treated = "ACME (treated)", ade_control = "ADE (control)", ade_treated = "ADE (treated)",
acme = "ACME (average)", ade = "ADE (average)", total = "Total effect", prop_mediated = "Proportion mediated")
order <- if (interaction) keys else c("acme", "ade", "total", "prop_mediated")
fin <- function(v) if (is.null(v) || !is.finite(v)) NULL else v
effect_rows <- lapply(order, function(k) list(effect = labels[[k]], estimate = fin(point[[k]]), ci_low = fin(summ[[k]]$ci_low), ci_high = fin(summ[[k]]$ci_high), p = fin(summ[[k]]$p)))
values <- list(n = n, x0 = x0, x1 = x1, interaction = interaction, ci_method = ci_method, sims = if (ci_method != "delta") sims else NULL,
n_used = n_used, n_failed = n_failed, a = a, a_se = a_se, a_p = a_p, b = b, b_se = b_se, b_p = b_p,
c_prime = c_prime, c_prime_se = c_se, c_prime_p = c_p, xm = xm, xm_se = xm_se, xm_p = xm_p, sobel_z = sobel_z, sobel_p = sobel_p,
missing_share = if (n_input > 0) n_dropped / n_input else 0)
for (k in keys) {
values[k] <- list(fin(point[[k]])) # `[<-` with list(NULL) keeps a null value (Python's None)
values[paste0(k, "_ci_low")] <- list(fin(summ[[k]]$ci_low))
values[paste0(k, "_ci_high")] <- list(fin(summ[[k]]$ci_high))
if (k %in% c("acme", "ade", "total", "prop_mediated")) values[paste0(k, "_p")] <- list(fin(summ[[k]]$p))
}
paths <- list(
list(path = sprintf("a: %s → %s", exposure, mediator), estimate = a, se = a_se, t = unname(pa["t"]), p = a_p),
list(path = sprintf("b: %s → %s (given %s)", mediator, outcome, exposure), estimate = b, se = b_se, t = unname(pb["t"]), p = b_p),
list(path = sprintf("c′: %s → %s (direct)", exposure, outcome), estimate = c_prime, se = c_se, t = unname(pc["t"]), p = c_p)
)
if (interaction) paths[[4]] <- list(path = sprintf("%s × %s", exposure, mediator), estimate = xm, se = xm_se, t = unname(pxm["t"]), p = xm_p)
method_name <- c(bootstrap = sprintf("nonparametric bootstrap (%s of %d resamples, percentile intervals)", format(n_used), sims),
quasi_bayes = sprintf("quasi-Bayesian simulation (%d draws, percentile intervals)", sims),
delta = "delta method (normal approximation)")[[ci_method]]
pct <- sprintf("%.0f%%", conf * 100)
pm <- point$prop_mediated
summary <- paste0(sprintf("Effect of %s (%s) on %s through %s (n = %d): ACME = %.3f [%.3f, %.3f], %s; ADE = %.3f; total = %.3f",
exposure, contrast, outcome, mediator, n, point$acme, summ$acme$ci_low, summ$acme$ci_high, cs_fmt_p(summ$acme$p), point$ade, point$total),
if (is.finite(pm)) sprintf("; proportion mediated %.2f.", pm) else ".")
chart_rows <- Filter(function(r) r$effect != "Proportion mediated", effect_rows)
cs_publish(list(
method = "regression.mediation",
methodVersion = "1.0.1",
title = "Mediation analysis",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("ACME = %.2f, %s CI [%.2f, %.2f], %s", point$acme, pct, summ$acme$ci_low, summ$acme$ci_high, cs_fmt_p(summ$acme$p)),
statistics = list(list(key = "acme", label = "ACME (indirect)", value = fin(point$acme)), list(key = "acme_p", label = "p", value = fin(summ$acme$p), format = "p"),
list(key = "ade", label = "ADE (direct)", value = fin(point$ade)), list(key = "total", label = "Total", value = fin(point$total)),
list(key = "prop_mediated", label = "Proportion mediated", value = fin(pm))),
tables = list(
list(key = "effects", title = sprintf("Effects of %s (%s)", exposure, contrast), columns = list(
list(key = "effect", label = "Effect", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
list(key = "p", label = "p", type = "pvalue")),
rows = effect_rows, note = "ACME: the change in the outcome when only the mediator moves as the exposure would move it; ADE: the change with the mediator held fixed."),
list(key = "paths", title = "Model paths", columns = list(
list(key = "path", label = "Path", type = "string"), list(key = "estimate", label = "B", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue")),
rows = paths)
),
effectSizes = list(),
assumptions = assumptions,
warnings = c(warnings, if (n_failed > 0) sprintf("%d resamples lost a variable's variation and were skipped.", n_failed)),
notes = list(paste0(sprintf("Linear mediator and outcome models (OLS)%s; covariates at their sample means. Intervals: %s.",
if (interaction) ", outcome model with the exposure × mediator interaction" else "", method_name),
if (ci_method != "delta") sprintf(" Seed %s: the same draws in Python and R.", format(seed)) else "")),
charts = list(cs_chart("effects", "forest", "Indirect, direct and total effects", list(
label = cs_col("Effect", vapply(chart_rows, `[[`, "", "effect"), kind = "categorical"),
estimate = cs_col("Estimate", vapply(chart_rows, function(r) if (is.null(r$estimate)) NA_real_ else r$estimate, 0)),
low = cs_col("low", vapply(chart_rows, function(r) if (is.null(r$ci_low)) NA_real_ else r$ci_low, 0)),
high = cs_col("high", vapply(chart_rows, function(r) if (is.null(r$ci_high)) NA_real_ else r$ci_high, 0))), controls = list(reference = 0))),
values = values
))
Sources
- Imai, K., Keele, L., & Tingley, D. (2010). A general approach to causal mediation analysis. Psychological Methods, 15, 309–334.
- VanderWeele, T. J. (2015). Explanation in Causal Inference: Methods for Mediation and Interaction. Oxford University Press.
- Tingley, D., Yamamoto, T., Hirose, K., Keele, L., & Imai, K. (2014). mediation: R package for causal mediation analysis. Journal of Statistical Software, 59(5).
- Sobel, M. E. (1982). Asymptotic confidence intervals for indirect effects in structural equation models. Sociological Methodology, 13, 290–312.
- Baron, R. M., & Kenny, D. A. (1986). The moderator–mediator variable distinction. Journal of Personality and Social Psychology, 51, 1173–1182.
From the CodeSplash method registry · regression.mediation v1.0.1.