Skip to content

CCausal inference · causal.matching

Matching (nearest neighbor, exact, coarsened exact)

What is the effect of a treatment on the treated, comparing each treated unit with similar untreated ones?

Estimates the average treatment effect on the treated (ATT) by matching: greedy nearest-neighbor matching on the logit of a logistic propensity score (1:k, with or without replacement, optional caliper), exact matching, or coarsened exact matching. Reports the matched difference in means with a pair-clustered (or robust) standard error, covariate balance before and after matching (cobalt conventions), how many treated units could not be matched, and a love plot; the matched rows are saved as an artifact.

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Nearest lalonde”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Matching (nearest neighbor)Recorded · Python and R agreeRecorded 2026-11-25 · 45 values compared
R

After nearest-neighbor matching (1:1), 185 treated units are compared with 185 controls. The ATT of true vs false on earnings 1978 is 894.37 (95% CI [−508.50, 2297.24], p = .211). The largest standardized covariate difference fell from 0.721 to 0.216.

ATT (matched difference)
894.37
95% CI
[−508.50, 2297.24]
p
.211
Matched treated / controls
[185, 185]
Max |SMD| after
0.2162

Plots

Covariate balance before and after matchingAfter matching or weighting, are treated and control groups alike on every covariate?
View data
CovariateStandardized mean differenceStage
age−0.3094before
educ0.0550before
race: hispan−0.0827before
race: white−0.5577before
married: true−0.3236before
nodegree: true0.1114before
re74−0.7211before
re75−0.2903before
age0.0718matched
educ−0.1290matched
race: hispan−0.1568matched
race: white−0.2162matched
married: true−0.0216matched
nodegree: true0.0703matched
re74−0.0505matched
re75−0.0257matched
Propensity scores by group (matched weights)Do treated and control units share a range of propensity scores (overlap / positivity)?
View data
treatPropensity scoreMatching weight
true0.63881
true0.22461
true0.67821
true0.77631
true0.70161
true0.69911
true0.65371
true0.78971
true0.77981
true0.04291
true0.68901
true0.68241
true0.64991
true0.56241
true0.60861
true0.72251
true0.70261
true0.73501
true0.71171
true0.66431
true0.76521
true0.13901
true0.12241
true0.76801
true0.71931
true0.60921
true0.77081
true0.26921
true0.71611
true0.76801
true0.71611
true0.60981
true0.59401
true0.64291
true0.66081
true0.77861
true0.56091
true0.45091
true0.55681
true0.73801
true0.64651
true0.09371
true0.64631
true0.09151
true0.75661
true0.59401
true0.64631
true0.68221
true0.56091
true0.65371
true0.68491
true0.61671
true0.75071
true0.66081
true0.61291
true0.71611
true0.74641
true0.37851
true0.60481
true0.13011

First 60 of 614 rows.

Assumptions

  • Overlap (positivity) — 25.7% of rows have propensity scores below .05 or above .95; 10.6% lie outside the common support [0.025, 0.789].
  • Covariate balance — Largest |SMD| after adjustment is 0.216 (race: white) > 0.1: residual imbalance can bias the estimate. Also, the variance ratio for age is 0.46, outside 0.5–2.
  • Common support — 0 of 185 treated units unmatched.
  • No unmeasured confounding — The estimate is causal only if the covariates include every common cause of treatment and outcome; check how strong an omitted confounder would have to be with the sensitivity analysis.

Matched estimate

QuantityEstimateSE95% CI low95% CI high
ATT (true − false)894.37715.76−508.502297.24
Mean, matched true6349.14———
Weighted mean, matched false5454.78———

Standard error clustered on matched sets (HC1).

Covariate balance

CovariateTypeMean trueMean falseSMD beforeSMD matchedVariance ratio matched
agecontinuous25.81628.030−0.30940.07180.4568
educcontinuous10.34610.2350.0550−0.12900.5721
race: hispanbinary0.05950.1422−0.0827−0.1568—
race: whitebinary0.09730.6550−0.5577−0.2162—
married: truebinary0.18920.5128−0.3236−0.0216—
nodegree: truebinary0.70810.59670.11140.0703—
re74continuous2095.575619.24−0.7211−0.05051.329
re75continuous1532.062466.48−0.2903−0.02571.496

Standardized by the treated group's SD (ATT); binary covariates as differences in proportions.

  • Estimand: ATT. Treated = true; covariates: age, educ, race, married, nodegree, re74, re75.
Python

After nearest-neighbor matching (1:1), 185 treated units are compared with 185 controls. The ATT of true vs false on earnings 1978 is 894.37 (95% CI [−508.50, 2297.24], p = .211). The largest standardized covariate difference fell from 0.721 to 0.216.

ATT (matched difference)
894.37
95% CI
[−508.50, 2297.24]
p
.211
Matched treated / controls
[185, 185]
Max |SMD| after
0.2162

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Overlap (positivity) — 25.7% of rows have propensity scores below .05 or above .95; 10.6% lie outside the common support [0.025, 0.789].
  • Covariate balance — Largest |SMD| after adjustment is 0.216 (race: white) > 0.1: residual imbalance can bias the estimate. Also, the variance ratio for age is 0.46, outside 0.5–2.
  • Common support — 0 of 185 treated units unmatched.
  • No unmeasured confounding — The estimate is causal only if the covariates include every common cause of treatment and outcome; check how strong an omitted confounder would have to be with the sensitivity analysis.

Matched estimate

QuantityEstimateSE95% CI low95% CI high
ATT (true − false)894.37715.76−508.502297.24
Mean, matched true6349.14———
Weighted mean, matched false5454.78———

Standard error clustered on matched sets (HC1).

Covariate balance

CovariateTypeMean trueMean falseSMD beforeSMD matchedVariance ratio matched
agecontinuous25.81628.030−0.30940.07180.4568
educcontinuous10.34610.2350.0550−0.12900.5721
race: hispanbinary0.05950.1422−0.0827−0.1568—
race: whitebinary0.09730.6550−0.5577−0.2162—
married: truebinary0.18920.5128−0.3236−0.0216—
nodegree: truebinary0.70810.59670.11140.0703—
re74continuous2095.575619.24−0.7211−0.05051.329
re75continuous1532.062466.48−0.2903−0.02571.496

Standardized by the treated group's SD (ATT); binary covariates as differences in proportions.

  • Estimand: ATT. Treated = true; covariates: age, educ, race, married, nodegree, re74, re75.

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

  • Nearest lalondec2_lalonde · covariates: age, educ, race, married, nodegree, re74, re75 · outcome: earnings 1978 · treatment: treat
  • Ratio2 caliper replacec2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated
  • Cem binary outcomec2_lalonde · covariates: age, educ, race, married · outcome: employed78 · treatment: treat
  • Exact stratac2_obs · covariates: segment, member · outcome: outcome · treatment: treated
  • Degenerate constantc2_lalonde · covariates: age, educ, race, married, nodegree, re74, re75 · outcome: earnings 1978 · treatment: treat
  • Degenerate n3c2_lalonde · covariates: age, educ, race, married, nodegree, re74, re75 · outcome: earnings 1978 · treatment: treat

In the guides

Where it sits in the decision guides

  • Causal inference (experiments, DiD, IV, RDD) · DS & ML Decision Guide · Explain — why is it happening?

What you need

Outcomenumeric / boolean · 1 column
Numeric, or yes/no (the effect is then a difference in proportions).
Treatmentboolean / categorical · 1 column · 2–2 levels
Two groups; choose the treated level below (default the second stored level, "true" for yes/no).
Confounders (covariates)numeric / categorical / boolean · 1–40 columns · 2–30 levels
Pre-treatment variables that affect both treatment and outcome.

Choices you make

hypothesis

Treated groupdefault —

The level that received the treatment; default: the second stored level (true for yes/no columns).

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

statistics

Matchingdefault nearest

How treated rows are paired with controls: nearest propensity score, identical covariates, or coarsened (binned) covariates.

  • Nearest neighbor on the propensity score(default) — Pairs each treated row with the control closest on propensity score; the usual choice.
  • Exact (identical covariates) — Pairs only rows with identical covariates; very clean, but drops many rows with numeric or many covariates.
  • Coarsened exact (binned numeric covariates) — Bins numeric covariates, then matches exactly on the bins; pick it to control how far matches can drift.
Controls per treated unitdefault 1

How many controls are matched to each treated unit. More controls lower variance but may worsen balance.

Match with replacementdefault off

A control can serve several treated units: closer matches, larger variance.

Caliper (SDs of the logit propensity score)default —

Treated units without a control this close are left unmatched (Austin recommends 0.2).

Matching orderdefault largest

Order in which treated units pick matches (matters without replacement). Largest propensity first is MatchIt's default.

  • Largest propensity first (MatchIt default)(default) — Treated rows with the largest propensity pick first; they're hardest to match, so it's the usual choice.
  • Smallest propensity first — Treated rows with the smallest propensity pick first; use it as a sensitivity check.
  • Data order — Treated rows pick in row order; use it to reproduce a fixed order.
Bins per numeric covariatedefault 5

Coarsened exact matching cuts each numeric covariate into this many bins before matching exactly.

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.

  • Covariate balance

    After matching, standardized mean differences should be below 0.1.

  • Common support

    Treated units that cannot be matched change the estimand to the matched treated.

  • Overlap (positivity)

  • No unmeasured confounding

What it reports

  • Tests: Matched treatment effect (ATT)
estimate
How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
ci_low
A range of effect values compatible with your data at the chosen confidence level.
ci_high
A range of effect values compatible with your data at the chosen confidence level.
z
An estimate in standard-error units, compared with the standard normal distribution.
p_value
How surprising your data would be if the null hypothesis were true, as a probability.
n
How many independent units the analysis used; it sets precision and power.
n_treated
How many independent units the analysis used; it sets precision and power.
n_control
How many independent units the analysis used; it sets precision and power.
n_treated_matched
How many independent units the analysis used; it sets precision and power.
n_control_matched
How many independent units the analysis used; it sets precision and power.
n_treated_unmatched
How many independent units the analysis used; it sets precision and power.
mu_treated
What a unit's outcome would be under one treatment; you only ever see one of them per unit.
mu_control
What a unit's outcome would be under one treatment; you only ever see one of them per unit.
estimand
The exact quantity an analysis targets, such as a difference in means or a ratio of medians.
effect_label
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
claim_level_max
How strong a causal statement the design supports, from association up to a causal effect.
ess_control
How many equally weighted units a weighted sample is worth. Unequal weights make it smaller than the real count.
max_abs_smd_before
Whether compared groups look alike on measured covariates after matching or weighting.
max_abs_smd_after
Whether compared groups look alike on measured covariates after matching or weighting.
mean_abs_smd_after
Whether compared groups look alike on measured covariates after matching or weighting.
n_vr_outside
Whether compared groups look alike on measured covariates after matching or weighting.
method
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
treated_level
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
control_level
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.

Per group, level or term: smd_before[<covariate>], smd_after[…], vr_after[…]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines run the twins codesplash.causal.matching ↔ cs_causal_match_* (MatchIt's greedy nearest-neighbor rules: m.order, rounds per ratio, earliest-row ties, caliper in SDs of the logit propensity); on the Lalonde fixture the matched set equals MatchIt::matchit(method = 'nearest', distance = 'glm', link = 'linear.logit') exactly.
  • Coarsened exact matching uses equal-width bins (an option); MatchIt's cem defaults to Sturges cut points.
Python

The exact script CodeSplash ran for example “Nearest lalonde” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Matching (nearest neighbor, exact, coarsened exact)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.matching 2.0.1 · spec 4b8691687a698f55
# 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 os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.causal import matching as csm
from codesplash.causal import weighting as csw
from codesplash.ml.run import out_dir as cs_out_dir

# %% 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}"
method = "nearest"  # nearest | exact | cem
ratio = int(1)
replace = False
caliper = None  # SDs of the logit propensity score; None = no caliper
order = "largest"  # MatchIt's m.order: largest | smallest | data
cem_bins = int(5)

# %% Match (ATT)
ps = None
if method == "nearest":
    # = MatchIt::matchit(treat ~ …, method = "nearest", distance = "glm", link = "linear.logit",
    #   ratio, replace, caliper, std.caliper = TRUE, m.order) in R
    ps, eta, _, converged = csw.propensity(X, t)
    w, subclass, n_unmatched = csm.nearest(eta, t, ratio, replace, caliper, order)
    vcov = "HC1" if replace else "cluster"  # pair-clustered SEs without replacement (MatchIt's guidance)
else:
    converged = True
    w, subclass, n_unmatched = csm.strata(df, covariates, t, coarsen=(method == "cem"), bins=cem_bins)
    vcov = "HC1"
if (w[t == 1] > 0).sum() < 2 or (w[t == 0] > 0).sum() < 2:
    raise ValueError("Fewer than two treated units found a match; loosen the caliper or use fewer covariates for exact matching.")
res = csw.weighted_difference(y, t, w, conf, vcov, subclass)
n_t_matched = int(((w > 0) & (t == 1)).sum())
n_c_matched = int(((w > 0) & (t == 0)).sum())

# %% Balance and checks
bal = csw.balance(X, labels, binary, t, w, "ATT")
max_before = max(abs(r["smd_before"]) for r in bal)
max_after, mean_after, bal_check = csw.balance_checks(bal)
ess_c = csw.ess(w[(t == 0) & (w > 0)])
share_lost = n_unmatched / n_treated
if share_lost <= 0.05:
    support = {"id": "support", "label": "Common support", "status": "pass", "detail": f"{n_unmatched} of {n_treated} treated units unmatched."}
else:
    support = {"id": "support", "label": "Common support", "status": "concern" if share_lost <= 0.3 else "fail",
               "detail": f"{n_unmatched} of {n_treated} treated units ({share_lost:.1%}) found no match: the estimate describes the matched treated, not all treated."}
    if share_lost > 0.3:
        support["downgrade_to"] = "L1"
checks = []
if ps is not None:
    checks.append(csw.overlap_check(ps, t))
checks += [bal_check, support, csw.no_confounding_check()]
values = {}
for r in bal:
    values[f"smd_before[{r['covariate']}]"] = r["smd_before"]
    values[f"smd_after[{r['covariate']}]"] = r["smd_after"]
    if r.get("vr_after") is not None:
        values[f"vr_after[{r['covariate']}]"] = r["vr_after"]
values["n_vr_outside"] = len(csw.variance_ratios_outside(bal))

# %% Matched rows (artifact)
out = cs_out_dir("target/academy-parity/run-8142/causal.matching/nearest-lalonde/out-python")
rows = df.index.to_numpy(dtype=np.int64)  # 0-based positions in the input file
matched = pd.DataFrame({"row": rows, "treated": t.astype(bool), "weight": w, "subclass": subclass})
matched = matched[matched["weight"] > 0]
if ps is not None:
    matched["propensity"] = ps[w > 0]
matched.to_parquet(os.path.join(out, "matched.parquet"), index=False)

# %% Result
mname = {"nearest": f"nearest-neighbor matching ({ratio}:1{', with replacement' if replace else ''}{f', caliper {caliper:g} SD' if caliper is not None else ''})",
         "exact": "exact matching", "cem": f"coarsened exact matching ({cem_bins} bins)"}[method]
pct = f"{conf:.0%}"
effect_label = f"Average treatment effect on the treated of {contrast_text} on {outcome_text}"
summary = (
    f"After {mname}, {n_t_matched} treated units are compared with {n_c_matched} controls. The ATT of {treated_level} vs "
    f"{control_level} on {outcome_text} is {cs.fmt_num(res['estimate'])} ({pct} CI [{cs.fmt_num(res['ci_low'])}, {cs.fmt_num(res['ci_high'])}], "
    f"{cs.fmt_p(res['p_value'])}). The largest standardized covariate difference fell from {max_before:.3f} to {max_after:.3f}."
)
values.update({
    "estimate": res["estimate"], "se": res["se"], "ci_low": res["ci_low"], "ci_high": res["ci_high"], "z": res["z"],
    "p_value": res["p_value"], "n": n, "n_treated": n_treated, "n_control": n_control, "n_treated_matched": n_t_matched,
    "n_control_matched": n_c_matched, "n_treated_unmatched": int(n_unmatched), "mu_treated": res["mu_treated"],
    "mu_control": res["mu_control"], "estimand": "ATT", "effect_label": effect_label, "claim_level_max": "L2",
    "ess_control": ess_c, "max_abs_smd_before": max_before, "max_abs_smd_after": max_after, "mean_abs_smd_after": mean_after,
    "method": method, "treated_level": treated_level, "control_level": control_level,
})
charts = [cs.chart(
    "balance", "love-plot", "Covariate balance before and after matching",
    {"covariate": cs.col("Covariate", [r["covariate"] for r in bal] * 2, kind="categorical"),
     "smd": cs.col("Standardized mean difference", [r["smd_before"] for r in bal] + [r["smd_after"] for r in bal]),
     "stage": cs.col("Stage", ["before"] * len(bal) + ["matched"] * len(bal), kind="categorical")},
    {"threshold": 0.1},
)]
if ps is not None:
    charts.append(cs.chart(
        "overlap", "overlap-density", "Propensity scores by group (matched weights)",
        {"score": cs.col("Propensity score", ps), "group": cs.col(treatment, np.where(t == 1, str(treated_level), str(control_level)), kind="categorical"),
         "weight": cs.col("Matching weight", w)},
    ))
cs.publish({
    "method": "causal.matching",
    "methodVersion": "2.0.1",
    "title": f"Matching ({ {'nearest': 'nearest neighbor', 'exact': 'exact', 'cem': 'coarsened exact'}[method] })",
    "engine": cs.engine_info("numpy", "pandas", "scipy"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "estimate", "label": "ATT (matched difference)", "value": res["estimate"]},
        {"key": "ci", "label": f"{pct} CI", "value": [res["ci_low"], res["ci_high"]]},
        {"key": "p_value", "label": "p", "value": res["p_value"], "format": "p"},
        {"key": "matched", "label": "Matched treated / controls", "value": [n_t_matched, n_c_matched]},
        {"key": "max_abs_smd_after", "label": "Max |SMD| after", "value": max_after},
    ],
    "tables": [
        {"key": "effect", "title": "Matched estimate", "columns": [
            {"key": "quantity", "label": "Quantity", "type": "string"}, {"key": "value", "label": "Estimate", "type": "number"},
            {"key": "se", "label": "SE", "type": "number"}, {"key": "ci_low", "label": f"{pct} CI low", "type": "number"},
            {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
         "rows": [
            {"quantity": f"ATT ({treated_level} − {control_level})", "value": res["estimate"], "se": res["se"], "ci_low": res["ci_low"], "ci_high": res["ci_high"]},
            {"quantity": f"Mean, matched {treated_level}", "value": res["mu_treated"], "se": None, "ci_low": None, "ci_high": None},
            {"quantity": f"Weighted mean, matched {control_level}", "value": res["mu_control"], "se": None, "ci_low": None, "ci_high": None}],
         "note": ("Standard error clustered on matched sets (HC1)." if vcov == "cluster" else "Robust (HC1) standard error with the matching weights treated as known.")},
        {"key": "balance", "title": "Covariate balance", "columns": [
            {"key": "covariate", "label": "Covariate", "type": "string"}, {"key": "type", "label": "Type", "type": "string"},
            {"key": "mean_treated_before", "label": f"Mean {treated_level}", "type": "number"},
            {"key": "mean_control_before", "label": f"Mean {control_level}", "type": "number"},
            {"key": "smd_before", "label": "SMD before", "type": "number"}, {"key": "smd_after", "label": "SMD matched", "type": "number"},
            {"key": "vr_after", "label": "Variance ratio matched", "type": "number"}],
         "rows": bal, "note": "Standardized by the treated group's SD (ATT); binary covariates as differences in proportions."},
    ],
    "assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
    "checks": checks,
    "artifacts": [{"key": "matched", "path": "matched.parquet", "format": "parquet", "title": "Matched rows with weights"}],
    "warnings": warnings + ([] if converged else ["The propensity model did not converge (a covariate predicts treatment perfectly)."]),
    "notes": [f"Estimand: ATT. Treated = {treated_level}; covariates: {', '.join(covariates)}."],
    "charts": charts,
    "values": values,
})
R

The exact script CodeSplash ran for example “Nearest lalonde” · R version 4.5.1 (2025-06-13)

# Matching (nearest neighbor, exact, coarsened exact)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.matching 2.0.1 · spec 4b8691687a698f55
# 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)
method <- "nearest"  # nearest | exact | cem
ratio <- as.integer(1)
replace <- FALSE
caliper <- NULL  # SDs of the logit propensity score; NULL = no caliper
m_order <- "largest"  # MatchIt's m.order: largest | smallest | data
cem_bins <- as.integer(5)

# %% Match (ATT)
ps <- NULL
converged <- TRUE
if (method == "nearest") {
  # = MatchIt::matchit(treat ~ ..., method = "nearest", distance = "glm", link = "linear.logit",
  #   ratio, replace, caliper, m.order) — the twin below follows MatchIt's rules exactly.
  p <- cs_causal_ps(X, t)
  ps <- p$ps
  converged <- p$converged
  m <- cs_causal_match_nearest(p$eta, t, ratio, replace, caliper, m_order)
  w <- m$w
  subclass <- m$subclass
  n_unmatched <- m$discarded
  vcov <- if (replace) "HC1" else "cluster"  # pair-clustered SEs without replacement (MatchIt's guidance)
} else {
  m <- cs_causal_match_strata(df, covariates, t, coarsen = method == "cem", bins = cem_bins)
  w <- m$w
  subclass <- m$stratum
  n_unmatched <- m$dropped
  vcov <- "HC1"
}
if (sum(w[t == 1] > 0) < 2 || sum(w[t == 0] > 0) < 2) stop("Fewer than two treated units found a match; loosen the caliper or use fewer covariates for exact matching.")
res <- cs_causal_wdiff(y, t, w, conf, vcov, subclass)
n_t_matched <- sum(w > 0 & t == 1)
n_c_matched <- sum(w > 0 & t == 0)

# %% Balance and checks
bal <- cs_causal_balance(X, labels, binary, t, w, "ATT")
max_before <- max(vapply(bal, function(r) abs(r$smd_before), numeric(1)))
bc <- cs_causal_balance_check(bal)
ess_c <- cs_causal_ess(w[t == 0 & w > 0])
share_lost <- n_unmatched / n_treated
support <- if (share_lost <= 0.05) {
  list(id = "support", label = "Common support", status = "pass", detail = sprintf("%d of %d treated units unmatched.", n_unmatched, n_treated))
} else {
  s <- list(id = "support", label = "Common support", status = if (share_lost <= 0.3) "concern" else "fail",
            detail = sprintf("%d of %d treated units (%s) found no match: the estimate describes the matched treated, not all treated.",
                             n_unmatched, n_treated, cs_causal_pct1(share_lost)))
  if (share_lost > 0.3) s$downgrade_to <- "L1"
  s
}
checks <- list()
if (!is.null(ps)) checks[[1]] <- cs_causal_overlap_check(ps, t)
checks <- c(checks, list(bc$check, support, cs_causal_no_confounding_check()))
values <- list()
for (r in bal) {
  values[[sprintf("smd_before[%s]", r$covariate)]] <- r$smd_before
  values[[sprintf("smd_after[%s]", r$covariate)]] <- r$smd_after
  if (!is.null(r$vr_after)) values[[sprintf("vr_after[%s]", r$covariate)]] <- r$vr_after
}
values$n_vr_outside <- length(cs_causal_vr_outside(bal))

# %% Matched rows (artifact)
out <- cs_ml_out_dir("target/academy-parity/run-8142/causal.matching/nearest-lalonde/out-r")
rows <- as.integer(rownames(df)) - 1L  # 0-based positions in the input file
keep <- w > 0
matched <- data.frame(row = rows[keep], treated = t[keep] == 1, weight = w[keep], subclass = as.integer(subclass[keep]))
if (!is.null(ps)) matched$propensity <- ps[keep]
nanoparquet::write_parquet(matched, file.path(out, "matched.parquet"))

# %% Result
mname <- switch(method,
  nearest = sprintf("nearest-neighbor matching (%d:1%s%s)", ratio, if (replace) ", with replacement" else "",
                    if (!is.null(caliper)) sprintf(", caliper %s SD", sprintf("%g", caliper)) else ""),
  exact = "exact matching", cem = sprintf("coarsened exact matching (%d bins)", cem_bins))
pct <- sprintf("%.0f%%", conf * 100)
effect_label <- sprintf("Average treatment effect on the treated of %s on %s", contrast_text, outcome_text)
summary <- paste0(
  sprintf("After %s, %d treated units are compared with %d controls. ", mname, n_t_matched, n_c_matched),
  sprintf("The ATT of %s vs %s on %s is %s (%s CI [%s, %s], %s). ", treated_level, control_level, outcome_text, cs_fmt_num(res$estimate), pct,
          cs_fmt_num(res$ci_low), cs_fmt_num(res$ci_high), cs_fmt_p(res$p_value)),
  sprintf("The largest standardized covariate difference fell from %.3f to %.3f.", max_before, bc$max))
values <- c(values, list(
  estimate = res$estimate, se = res$se, ci_low = res$ci_low, ci_high = res$ci_high, z = res$z, p_value = res$p_value,
  n = n, n_treated = n_treated, n_control = n_control, n_treated_matched = n_t_matched, n_control_matched = n_c_matched,
  n_treated_unmatched = as.integer(n_unmatched), mu_treated = res$mu_treated, mu_control = res$mu_control, estimand = "ATT",
  effect_label = effect_label, claim_level_max = "L2", ess_control = ess_c, max_abs_smd_before = max_before,
  max_abs_smd_after = bc$max, mean_abs_smd_after = bc$mean, method = method, treated_level = treated_level, control_level = control_level))
charts <- list(cs_chart("balance", "love-plot", "Covariate balance before and after matching", list(
  covariate = cs_col("Covariate", rep(vapply(bal, `[[`, "", "covariate"), 2), kind = "categorical"),
  smd = cs_col("Standardized mean difference", c(vapply(bal, `[[`, 0, "smd_before"), vapply(bal, `[[`, 0, "smd_after"))),
  stage = cs_col("Stage", rep(c("before", "matched"), each = length(bal)), kind = "categorical")),
  controls = list(threshold = 0.1)))
if (!is.null(ps)) {
  charts[[2]] <- cs_chart("overlap", "overlap-density", "Propensity scores by group (matched weights)", list(
    score = cs_col("Propensity score", ps), group = cs_col(treatment, ifelse(t == 1, treated_level, control_level), kind = "categorical"),
    weight = cs_col("Matching weight", w)))
}
cs_publish(list(
  method = "causal.matching",
  methodVersion = "2.0.1",
  title = sprintf("Matching (%s)", switch(method, nearest = "nearest neighbor", exact = "exact", cem = "coarsened exact")),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "estimate", label = "ATT (matched difference)", value = res$estimate),
    list(key = "ci", label = paste(pct, "CI"), value = c(res$ci_low, res$ci_high)),
    list(key = "p_value", label = "p", value = res$p_value, format = "p"),
    list(key = "matched", label = "Matched treated / controls", value = c(n_t_matched, n_c_matched)),
    list(key = "max_abs_smd_after", label = "Max |SMD| after", value = bc$max)),
  tables = list(
    list(key = "effect", title = "Matched estimate", columns = list(
      list(key = "quantity", label = "Quantity", type = "string"), list(key = "value", label = "Estimate", type = "number"),
      list(key = "se", label = "SE", type = "number"), list(key = "ci_low", label = paste(pct, "CI low"), type = "number"),
      list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
      rows = list(
        list(quantity = sprintf("ATT (%s − %s)", treated_level, control_level), value = res$estimate, se = res$se, ci_low = res$ci_low, ci_high = res$ci_high),
        list(quantity = sprintf("Mean, matched %s", treated_level), value = res$mu_treated, se = NULL, ci_low = NULL, ci_high = NULL),
        list(quantity = sprintf("Weighted mean, matched %s", control_level), value = res$mu_control, se = NULL, ci_low = NULL, ci_high = NULL)),
      note = if (vcov == "cluster") "Standard error clustered on matched sets (HC1)." else "Robust (HC1) standard error with the matching weights treated as known."),
    list(key = "balance", title = "Covariate balance", columns = list(
      list(key = "covariate", label = "Covariate", type = "string"), list(key = "type", label = "Type", type = "string"),
      list(key = "mean_treated_before", label = paste("Mean", treated_level), type = "number"),
      list(key = "mean_control_before", label = paste("Mean", control_level), type = "number"),
      list(key = "smd_before", label = "SMD before", type = "number"), list(key = "smd_after", label = "SMD matched", type = "number"),
      list(key = "vr_after", label = "Variance ratio matched", type = "number")),
      rows = bal, note = "Standardized by the treated group's SD (ATT); binary covariates as differences in proportions.")),
  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,
  artifacts = list(list(key = "matched", path = "matched.parquet", format = "parquet", title = "Matched rows with weights")),
  warnings = c(warnings, if (!converged) list("The propensity model did not converge (a covariate predicts treatment perfectly).") else list()),
  notes = list(sprintf("Estimand: ATT. Treated = %s; covariates: %s.", treated_level, paste(covariates, collapse = ", "))),
  charts = charts,
  values = values
))

Sources

  • Ho, D. E., Imai, K., King, G., & Stuart, E. A. (2011). MatchIt: Nonparametric preprocessing for parametric causal inference. Journal of Statistical Software, 42(8).
  • Stuart, E. A. (2010). Matching methods for causal inference: A review and a look forward. Statistical Science, 25, 1–21.
  • Austin, P. C. (2011). Optimal caliper widths for propensity-score matching. Pharmaceutical Statistics, 10, 150–161.
  • Iacus, S. M., King, G., & Porro, G. (2012). Causal inference without balance checking: Coarsened exact matching. Political Analysis, 20, 1–24.

From the CodeSplash method registry · causal.matching v2.0.1.