Skip to content

CCausal inference · causal.did

Difference-in-differences (2 × 2, two-way fixed effects, event study)

Did the outcome change more for the treated group than for the comparison group after treatment began?

Compares the before–after change in the treated group with the change in a comparison group. With a panel (unit and time) it fits two-way fixed effects with standard errors clustered by unit, and an optional event study with leads (a pre-trend test) and lags (dynamic effects). Use the staggered design when units start treatment at different times.

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

A real result

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

Difference-in-differencesRecorded · Python and R agreeRecorded 2026-11-17 · 25 values compared
R

DiD = 1.37, SE = 0.10, t(49) = 13.90, p < .001, 95% CI [1.17, 1.56]

Difference-in-differences
1.366
95% CI
[1.169, 1.564]
SE
0.0983
p
< .001

Plots

Mean log wage by groupWhere is the series heading, and how uncertain is the forecast?
View data
kindGroupyearlog wage
actualComparison2,0111.500
actualComparison2,0121.517
actualComparison2,0131.919
actualComparison2,0141.738
actualComparison2,0152.080
actualComparison2,0162.195
actualComparison2,0172.568
actualComparison2,0182.851
actualComparison2,0192.722
actualComparison2,0203.067
actualTreated2,0112.172
actualTreated2,0121.922
actualTreated2,0132.262
actualTreated2,0142.418
actualTreated2,0152.431
actualTreated2,0163.918
actualTreated2,0174.032
actualTreated2,0184.678
actualTreated2,0194.925
actualTreated2,0205.501

Assumptions

  • Parallel pre-trends — Turn on the event study to test whether the groups trended in parallel before treatment.
  • Clustered standard errors — Standard errors clustered on 50 clusters.
  • Common treatment timing — All treated units start treatment in the same period.

Difference-in-differences regression (fixed effects: unit + time)

TermEstimateSE
Treated × post (treated)1.3660.0983
x0.49370.0236

Group means

GroupBeforeAfterChange
Treated2.2414.6112.370
Comparison1.7512.6810.9299
  • Design: twfe; standard errors clustered by firm; t with 49 df.
Python

DiD = 1.37, SE = 0.10, t(49) = 13.90, p < .001, 95% CI [1.17, 1.56]

Difference-in-differences
1.366
95% CI
[1.169, 1.564]
SE
0.0983
p
< .001

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

Assumptions

  • Parallel pre-trends — Turn on the event study to test whether the groups trended in parallel before treatment.
  • Clustered standard errors — Standard errors clustered on 50 clusters.
  • Common treatment timing — All treated units start treatment in the same period.

Difference-in-differences regression (fixed effects: unit + time)

TermEstimateSE
Treated × post (treated)1.3660.0983
x0.49370.0236

Group means

GroupBeforeAfterChange
Treated2.2414.6112.370
Comparison1.7512.6810.9299
  • Design: twfe; standard errors clustered by firm; t with 49 df.

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

  • Twfec1_panel · covariates: x · outcome: log wage · post: post · time: year · treatment: treated · unit: firm
  • Event studyc1_panel · outcome: log wage · time: year · treatment: treated · unit: firm
  • Pretrend failsc1_panel · outcome: sales · post: post · time: date · treatment: treated · unit: firm
  • Two by twoc1_panel · cluster: region · outcome: log wage · post: post · treatment: treated
  • Degenerate constantc1_panel · covariates: x · outcome: log wage · post: post · time: year · treatment: treated · unit: firm
  • Degenerate n1c1_panel · covariates: x · outcome: log wage · post: post · time: year · treatment: treated · unit: firm
  • Degenerate single levelc1_panel · covariates: x · outcome: log wage · post: post · time: year · treatment: treated · unit: firm
  • Degenerate huge cardinalityc1_panel · covariates: x · outcome: log wage · post: post · time: year · treatment: treated · unit: firm

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 · 1 column
The numeric outcome.
Treated groupboolean / categorical · 1 column · 2–2 levels
Which units belong to the treated group (constant within a unit).
After treatmentboolean / categorical · 0–1 column · 2–2 levels
Marks periods after treatment began. Leave empty and set "Treatment starts" when a time column is given.
Unitcategorical / numeric · 0–1 column
Panel unit (person, firm, region). Adds unit fixed effects and clusters standard errors by unit.
Timenumeric / temporal · 0–1 column
Period (year, month, date). Adds time fixed effects; needed for the event study.
Covariatesnumeric / boolean · 0–20 columns
Time-varying controls. Avoid variables the treatment itself could change.
Clustercategorical / numeric · 0–1 column
Clusters for standard errors (default the unit). Treatment is usually assigned at this level.

Choices you make

hypothesis

Treated leveldefault —

The level of the treated group (default "true" or the last level).

After-treatment leveldefault —

The level that marks post-treatment periods (default "true" or the last level).

Treatment starts (first treated period)default —

With a numeric time column, periods at or after this value are post-treatment.

Confidence leveldefault 0.95

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

statistics

Event study (leads and lags)default off

Estimates effects period by period relative to the start of treatment (needs unit and time). Leads test parallel pre-trends.

Leads (pre-periods)default 4

Pre-treatment periods shown; earlier periods are pooled into the first lead. Period −1 is the reference.

Lags (post-periods)default 4

Post-treatment periods shown; later periods are pooled into the last lag.

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.

  • Parallel pre-trends

    Without treatment, the treated group's outcome would have followed the comparison group's trend. Untestable after treatment; leads in the event study test it before.

  • No anticipationNot checked from data: state why it holds

    Outcomes do not react before treatment starts.

  • Enough clusters

    Clustered standard errors need roughly 30 or more clusters.

  • Common treatment timing

    Two-way fixed effects can be biased when units start treatment in different periods; use the staggered design then.

What it reports

  • Tests: Difference-in-differences effect
estimate
How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
t
An estimate divided by its standard error, compared with a t distribution.
p_value
How surprising your data would be if the null hypothesis were true, as a probability.
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.
n
How many independent units the analysis used; it sets precision and power.
n_units
How many independent units the analysis used; it sets precision and power.
n_treated_units
How many independent units the analysis used; it sets precision and power.
n_clusters
How many independent units the analysis used; it sets precision and power.
df_t
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
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.
did_raw
Compares the change over time in a treated group with the change in a control group.
mean_treated_pre
Compares the change over time in a treated group with the change in a control group.
mean_treated_post
Compares the change over time in a treated group with the change in a control group.
mean_control_pre
Compares the change over time in a treated group with the change in a control group.
mean_control_post
Compares the change over time in a treated group with the change in a control group.
design
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.

Per group, level or term: pretrend_p, check[<id>], es_estimate[<event time>], es_se[…], es_p[…], pretrend_f

Python and R

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

Default traps between the two languages

  • pyfixest and fixest share the estimator and small-sample corrections (fixest defaults: K adjustment, G/(G−1), fixed effects nested in clusters not counted); p-values and intervals are computed from t with df = clusters − 1 (or n − k) in both engines because pyfixest's p-values underflow below 1e-16.
Python

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

# Difference-in-differences (2 × 2, two-way fixed effects, event study)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.did 1.0.2 · spec 49014fb385e27e84
# Dataset: c1_panel (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 pyfixest as pf
from scipy import stats

import codesplash as cs
from codesplash import ml as csml

# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_panel.parquet", columns=["log wage", "treated", "post", "firm", "year", "x"])
n_input = len(df)
df["treated"] = pd.Categorical(df["treated"], categories=["false", "true"])  # stored level order
df["post"] = pd.Categorical(df["post"], categories=["false", "true"])  # stored level order
df["firm"] = pd.Categorical(df["firm"], categories=["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34", "f35", "f36", "f37", "f38", "f39", "f40", "f41", "f42", "f43", "f44", "f45", "f46", "f47", "f48", "f49", "f50"])  # stored level order
df = df.dropna(subset=["log wage", "treated", "post", "firm", "year", "x"])  # listwise deletion over the analysis columns
df["treated"] = df["treated"].cat.remove_unused_categories()
df["post"] = df["post"].cat.remove_unused_categories()
df["firm"] = df["firm"].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, ["log wage", "treated", "post", "firm", "year", "x"])  # infinite values stop the run (registry/errors.yaml)

# %% Design
Y = "log wage"
TREAT = "treated"
POST = "post"
UNIT = "firm"
TIME = "year"
CLUSTER = None
COVARIATES = ["x"]
TIME_TEMPORAL = False
conf = 0.95
event_study = False
leads, lags = int(4), int(4)


def level_of(col, chosen):
    levels = [str(x) for x in df[col].cat.categories]
    return chosen if chosen is not None else ("true" if "true" in levels else levels[-1])


treated_level = level_of(TREAT, None)
d = pd.DataFrame({"y": df[Y].astype(float).to_numpy()})
d["treated"] = (df[TREAT].astype(str) == treated_level).astype(float).to_numpy()
if TIME:
    tvals = pd.to_datetime(df[TIME]) if TIME_TEMPORAL else df[TIME].astype(float)
    periods = np.sort(tvals.unique())
    d["time"] = np.searchsorted(periods, tvals.to_numpy()).astype(int)  # period index
treatment_start = None
if POST:
    d["post"] = (df[POST].astype(str) == level_of(POST, None)).astype(float).to_numpy()
elif treatment_start is not None and TIME and not TIME_TEMPORAL:
    d["post"] = (tvals.to_numpy() >= float(treatment_start)).astype(float)
else:
    raise ValueError("Choose an 'After treatment' column, or a numeric time column and 'Treatment starts'.")
if UNIT:
    d["unit"] = df[UNIT].astype(str).to_numpy()
cluster_col = CLUSTER or UNIT
if cluster_col:
    d["cl"] = df[cluster_col].astype(str).to_numpy()
for j, c in enumerate(COVARIATES):
    d[f"x{j + 1}"] = df[c].astype(float).to_numpy()
xs = [f"x{j + 1}" for j in range(len(COVARIATES))]
d["d"] = d["treated"] * d["post"]
if d["d"].sum() == 0 or (d["d"] == 1).all():
    cs.cs_error("CS_E_UNDEFINED", what="Difference-in-differences", reason="it needs both treated post-treatment rows and other rows")
if d["y"].nunique() < 2:
    cs.cs_error("CS_E_CONSTANT", column=Y)
if UNIT:
    rows_per_unit = d["unit"].value_counts()
    if len(rows_per_unit) < 2:
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=UNIT, min=2, k=len(rows_per_unit))
    if rows_per_unit.max() < 2:  # unit fixed effects would absorb every row
        cs.cs_error("CS_E_UNDEFINED", what="Difference-in-differences with unit fixed effects", reason=f"every value of {UNIT} has only one row")
if UNIT and d.groupby("unit")["treated"].nunique().max() > 1:
    warnings.append(f"{TREAT} changes within some units; the treated group is defined row by row.")

# %% Fit: two-way fixed effects (pyfixest ≡ R fixest; fixest small-sample conventions)
vcov = {"CRV1": "cl"} if cluster_col else "hetero"
if UNIT and TIME:
    rhs, fe = ["d"], "unit + time"
elif UNIT:
    rhs, fe = ["d", "post"], "unit"
elif TIME:
    rhs, fe = ["d", "treated"], "time"
else:
    rhs, fe = ["d", "treated", "post"], None
formula = "y ~ " + " + ".join(rhs + xs) + (f" | {fe}" if fe else "")
fit = pf.feols(formula, data=d, vcov=vcov)
names = list(fit.coef().index)
b = fit.coef().to_numpy()
V = np.asarray(fit._vcov)
df_t = float(fit._df_t)
qt = stats.t.ppf(0.5 + conf / 2, df_t)
i = names.index("d")
est, se = float(b[i]), float(np.sqrt(V[i, i]))
tstat = est / se
p = float(2 * stats.t.sf(abs(tstat), df_t))
ci_low, ci_high = est - qt * se, est + qt * se
n = int(fit._N)
n_clusters = int(d["cl"].nunique()) if cluster_col else None

# Raw 2 × 2 means.
means = d.groupby(["treated", "post"])["y"].mean()
m = {(int(a), int(b_)): float(v) for (a, b_), v in means.items()}
did_raw = (m.get((1, 1), np.nan) - m.get((1, 0), np.nan)) - (m.get((0, 1), np.nan) - m.get((0, 0), np.nan))

# %% Event study: leads and lags relative to each treated unit's first post-treatment period
es_rows, pretrend_f, pretrend_p = [], None, None
starts = None
if UNIT and TIME:
    first_post = d[(d["treated"] == 1) & (d["post"] == 1)].groupby("unit")["time"].min()
    starts = first_post.unique()
if event_study:
    if not (UNIT and TIME):
        raise ValueError("The event study needs a unit and a time column.")
    rel = d["unit"].map(first_post)
    rel = (d["time"] - rel).where(rel.notna())
    rel = rel.clip(lower=-leads, upper=lags)
    ev = []
    for e in range(-leads, lags + 1):
        if e == -1:
            continue  # reference period
        name = f"lead{-e}" if e < 0 else f"lag{e}"
        col = (rel == e).astype(float)
        if col.sum() > 0:
            d[name] = col
            ev.append((e, name))
    es_fit = pf.feols("y ~ " + " + ".join([nm for _, nm in ev] + xs) + " | unit + time", data=d, vcov=vcov)
    es_names = list(es_fit.coef().index)
    eb, eV, edf = es_fit.coef().to_numpy(), np.asarray(es_fit._vcov), float(es_fit._df_t)
    eq = stats.t.ppf(0.5 + conf / 2, edf)
    for e, nm in ev:
        j = es_names.index(nm)
        s = float(np.sqrt(eV[j, j]))
        es_rows.append({"rel_time": e, "estimate": float(eb[j]), "se": s, "low": float(eb[j]) - eq * s, "high": float(eb[j]) + eq * s,
                        "p": float(2 * stats.t.sf(abs(eb[j] / s), edf))})
    es_rows.append({"rel_time": -1, "estimate": 0.0, "se": 0.0, "low": 0.0, "high": 0.0, "p": None})
    es_rows.sort(key=lambda r: r["rel_time"])
    pre = [es_names.index(nm) for e, nm in ev if e <= -2]
    if pre:
        bp = eb[pre]
        Vp = eV[np.ix_(pre, pre)]
        pretrend_f = float(bp @ np.linalg.solve(Vp, bp) / len(pre))
        pretrend_p = float(stats.f.sf(pretrend_f, len(pre), edf))

# %% Checks
checks = []
if pretrend_p is not None:
    if pretrend_p < 0.05:
        checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "concern", "downgrade_to": "L2",
                       "detail": f"Leads before treatment differ from zero jointly (F = {pretrend_f:.2f}, {cs.fmt_p(pretrend_p)}): the groups were already diverging, so parallel trends are doubtful."})
    else:
        checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "pass",
                       "detail": f"Leads before treatment are jointly compatible with zero (F = {pretrend_f:.2f}, {cs.fmt_p(pretrend_p)}). This supports, but cannot prove, parallel trends after treatment."})
elif UNIT and TIME:
    checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "info",
                   "detail": "Turn on the event study to test whether the groups trended in parallel before treatment."})
else:
    checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "info",
                   "detail": "With only before/after periods, parallel trends cannot be tested; attest why the comparison group's change is a good counterfactual."})
if not cluster_col:
    checks.append({"id": "clusters", "label": "Clustered standard errors", "status": "concern",
                   "detail": "No unit or cluster column: standard errors assume independent rows, which overstates precision when units are observed repeatedly."})
elif n_clusters < 30:
    checks.append({"id": "clusters", "label": "Clustered standard errors", "status": "concern",
                   "detail": f"Only {n_clusters} clusters: clustered standard errors can be too small; consider a wild cluster bootstrap."})
else:
    checks.append({"id": "clusters", "label": "Clustered standard errors", "status": "pass", "detail": f"Standard errors clustered on {n_clusters} clusters."})
if starts is not None and len(starts) > 1:
    checks.append({"id": "staggered_timing", "label": "Common treatment timing", "status": "concern", "downgrade_to": "L2",
                   "detail": f"Treated units start in {len(starts)} different periods: two-way fixed effects can be biased with staggered adoption and changing effects. Use the staggered (Callaway–Sant'Anna) design."})
elif starts is not None:
    checks.append({"id": "staggered_timing", "label": "Common treatment timing", "status": "pass", "detail": "All treated units start treatment in the same period."})

# %% Result
out = csml.out_dir("target/academy-parity/run-953/causal.did/twfe/out-python")
artifacts = []
if es_rows:
    pd.DataFrame(es_rows).to_parquet(os.path.join(out, "event_study.parquet"), index=False)
    artifacts.append({"key": "event_study", "path": os.path.join(out, "event_study.parquet"), "format": "parquet", "title": "Event-study coefficients"})
charts = []
if es_rows:
    charts.append(cs.chart("event_study", "event-study", f"Effect on {Y} by period relative to treatment", {
        "rel_time": cs.col("Periods relative to treatment", [r["rel_time"] for r in es_rows], kind="numeric"),
        "estimate": cs.col("Estimate", [r["estimate"] for r in es_rows], kind="numeric"),
        "low": cs.col("Lower", [r["low"] for r in es_rows], kind="numeric"),
        "high": cs.col("Upper", [r["high"] for r in es_rows], kind="numeric"),
    }, controls={"reference": -1}))
if TIME:
    trend = d.groupby(["time", "treated"])["y"].mean().reset_index().sort_values(["treated", "time"], kind="mergesort")
    label = (lambda t: pd.Timestamp(periods[t]).strftime("%Y-%m-%d")) if TIME_TEMPORAL else (lambda t: float(periods[t]))
    charts.append(cs.chart("trends", "forecast-fan", f"Mean {Y} by group", {
        "time": cs.col(TIME, [label(int(t)) for t in trend["time"]], kind="temporal" if TIME_TEMPORAL else "numeric"),
        "value": cs.col(Y, trend["y"].to_numpy(dtype=float), kind="numeric"),
        "kind": cs.col("kind", ["actual"] * len(trend), kind="categorical", levels=["actual"]),
        "series": cs.col("Group", np.where(trend["treated"] == 1, "Treated", "Comparison"), kind="categorical", levels=["Comparison", "Treated"]),
    }))
direction = "more" if est > 0 else "less"
summary = (
    f"After treatment began, {Y} changed by {abs(est):.2f} {direction} in the treated group than in the comparison group "
    f"(difference-in-differences {est:.2f}, {conf:.0%} CI [{ci_low:.2f}, {ci_high:.2f}], {cs.fmt_p(p)})."
)
if pretrend_p is not None:
    summary += (f" Leads before treatment differ from zero ({cs.fmt_p(pretrend_p)}): parallel trends are doubtful." if pretrend_p < 0.05
                else f" Leads before treatment are compatible with parallel trends ({cs.fmt_p(pretrend_p)}).")
design = "twfe" if (UNIT and TIME) else ("unit_fe" if UNIT else ("time_fe" if TIME else "2x2"))
values = {
    "estimate": est, "se": se, "t": tstat, "p_value": p, "ci_low": ci_low, "ci_high": ci_high, "n": n,
    "n_units": int(d["unit"].nunique()) if UNIT else None,
    "n_treated_units": int(d.loc[d["treated"] == 1, "unit"].nunique()) if UNIT else None,
    "n_clusters": n_clusters, "df_t": df_t, "design": design,
    "did_raw": did_raw, "mean_treated_pre": m.get((1, 0)), "mean_treated_post": m.get((1, 1)),
    "mean_control_pre": m.get((0, 0)), "mean_control_post": m.get((0, 1)),
    "pretrend_f": pretrend_f, "pretrend_p": pretrend_p,
    "estimand": "ATT",
    "effect_label": f"Average effect of treatment on {Y} for the treated group after treatment began",
    "claim_level_max": "L3",
}
for r in es_rows:
    if r["rel_time"] != -1:
        values[f"es_estimate[{r['rel_time']}]"] = r["estimate"]
        values[f"es_se[{r['rel_time']}]"] = r["se"]
        values[f"es_p[{r['rel_time']}]"] = r["p"]
for c in checks:
    values[f"check[{c['id']}]"] = c["status"]
coef_rows = [{"term": nm, "estimate": float(b[j]), "se": float(np.sqrt(V[j, j]))} for j, nm in enumerate(names)]
for r in coef_rows:
    r["term"] = {"d": f"Treated × post ({TREAT})", "post": "Post", "treated": "Treated group"}.get(r["term"], COVARIATES[int(r["term"][1:]) - 1] if r["term"].startswith("x") else r["term"])
tables = [
    {"key": "coefficients", "title": "Difference-in-differences regression" + (f" (fixed effects: {fe})" if fe else ""),
     "columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                 {"key": "se", "label": "SE", "type": "number"}],
     "rows": coef_rows},
    {"key": "means", "title": "Group means",
     "columns": [{"key": "group", "label": "Group", "type": "string"}, {"key": "pre", "label": "Before", "type": "number"},
                 {"key": "post", "label": "After", "type": "number"}, {"key": "change", "label": "Change", "type": "number"}],
     "rows": [{"group": "Treated", "pre": m.get((1, 0)), "post": m.get((1, 1)), "change": m.get((1, 1), np.nan) - m.get((1, 0), np.nan)},
              {"group": "Comparison", "pre": m.get((0, 0)), "post": m.get((0, 1)), "change": m.get((0, 1), np.nan) - m.get((0, 0), np.nan)}]},
]
if es_rows:
    tables.append({"key": "event_study", "title": "Event study (reference: period −1)",
                   "columns": [{"key": "rel_time", "label": "Period", "type": "integer"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                               {"key": "se", "label": "SE", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"},
                               {"key": "high", "label": "Upper", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
                   "rows": es_rows})
cs.publish({
    "method": "causal.did",
    "methodVersion": "1.0.2",
    "title": "Difference-in-differences",
    "engine": cs.engine_info("pandas", "numpy", "pyfixest"),
    "n": n,
    "summary": summary,
    "apa": f"DiD = {cs.fmt_num(est)}, SE = {cs.fmt_num(se)}, t({df_t:.0f}) = {cs.fmt_num(tstat)}, {cs.fmt_p(p)}, {conf:.0%} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}]",
    "statistics": [
        {"key": "estimate", "label": "Difference-in-differences", "value": est},
        {"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
        {"key": "se", "label": "SE", "value": se},
        {"key": "p_value", "label": "p", "value": p, "format": "p"},
    ],
    "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": [f"Design: {design}; standard errors " + (f"clustered by {cluster_col}" if cluster_col else "heteroskedasticity-robust (HC1)") + f"; t with {df_t:.0f} df."],
    "values": values,
    "artifacts": artifacts,
    "charts": charts,
})
R

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

# Difference-in-differences (2 × 2, two-way fixed effects, event study)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.did 1.0.2 · spec 49014fb385e27e84
# Dataset: c1_panel (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
library(fixest)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_panel.parquet", col_select = c("log wage", "treated", "post", "firm", "year", "x")))
n_input <- nrow(df)
df[["treated"]] <- factor(df[["treated"]], levels = c("false", "true"))  # stored level order
df[["post"]] <- factor(df[["post"]], levels = c("false", "true"))  # stored level order
df[["firm"]] <- factor(df[["firm"]], levels = c("f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34", "f35", "f36", "f37", "f38", "f39", "f40", "f41", "f42", "f43", "f44", "f45", "f46", "f47", "f48", "f49", "f50"))  # stored level order
df <- df[stats::complete.cases(df[c("log wage", "treated", "post", "firm", "year", "x")]), , 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("log wage", "treated", "post", "firm", "year", "x"))  # infinite values stop the run (registry/errors.yaml)

# %% Design
Y <- "log wage"
TREAT <- "treated"
POST <- "post"
UNIT <- "firm"
TIME <- "year"
CLUSTER <- NULL
COVARIATES <- c("x")
TIME_TEMPORAL <- FALSE
conf <- 0.95
event_study <- FALSE
leads <- as.integer(4)
lags <- as.integer(4)

level_of <- function(col, chosen) {
  lv <- levels(df[[col]])
  if (!is.null(chosen)) chosen else if ("true" %in% lv) "true" else lv[length(lv)]
}

treated_level <- level_of(TREAT, NULL)
d <- data.frame(y = as.numeric(df[[Y]]))
d$treated <- as.numeric(as.character(df[[TREAT]]) == treated_level)
if (!is.null(TIME)) {
  tvals <- if (TIME_TEMPORAL) as.Date(df[[TIME]], tz = "UTC") else as.numeric(df[[TIME]])
  periods <- sort(unique(tvals))
  d$time <- match(tvals, periods) - 1L  # period index
}
treatment_start <- NULL
if (!is.null(POST)) {
  d$post <- as.numeric(as.character(df[[POST]]) == level_of(POST, NULL))
} else if (!is.null(treatment_start) && !is.null(TIME) && !TIME_TEMPORAL) {
  d$post <- as.numeric(tvals >= treatment_start)
} else {
  stop("Choose an 'After treatment' column, or a numeric time column and 'Treatment starts'.")
}
if (!is.null(UNIT)) d$unit <- as.character(df[[UNIT]])
cluster_col <- if (!is.null(CLUSTER)) CLUSTER else UNIT
if (!is.null(cluster_col)) d$cl <- as.character(df[[cluster_col]])
xs <- character(0)
for (j in seq_along(COVARIATES)) {
  d[[paste0("x", j)]] <- as.numeric(df[[COVARIATES[j]]])
  xs <- c(xs, paste0("x", j))
}
d$d <- d$treated * d$post
if (sum(d$d) == 0 || all(d$d == 1)) {
  cs_error("CS_E_UNDEFINED", what = "Difference-in-differences", reason = "it needs both treated post-treatment rows and other rows")
}
if (length(unique(d$y)) < 2) cs_error("CS_E_CONSTANT", column = Y)
if (!is.null(UNIT)) {
  rows_per_unit <- table(d$unit)
  if (length(rows_per_unit) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = UNIT, min = 2, k = length(rows_per_unit))
  if (max(rows_per_unit) < 2) {  # unit fixed effects would absorb every row
    cs_error("CS_E_UNDEFINED", what = "Difference-in-differences with unit fixed effects", reason = sprintf("every value of %s has only one row", UNIT))
  }
}
if (!is.null(UNIT) && max(tapply(d$treated, d$unit, function(v) length(unique(v)))) > 1) {
  warnings <- c(warnings, sprintf("%s changes within some units; the treated group is defined row by row.", TREAT))
}

# %% Fit: two-way fixed effects with fixest (default small-sample corrections)
vc <- if (!is.null(cluster_col)) ~cl else "hetero"
if (!is.null(UNIT) && !is.null(TIME)) {
  rhs <- "d"; fe <- "unit + time"
} else if (!is.null(UNIT)) {
  rhs <- c("d", "post"); fe <- "unit"
} else if (!is.null(TIME)) {
  rhs <- c("d", "treated"); fe <- "time"
} else {
  rhs <- c("d", "treated", "post"); fe <- NULL
}
fml <- as.formula(paste("y ~", paste(c(rhs, xs), collapse = " + "), if (!is.null(fe)) paste("|", fe) else ""))
fit <- feols(fml, data = d, vcov = vc)
b <- coef(fit)
V <- vcov(fit)
df_t <- unname(degrees_freedom(fit, "t"))
qt_ <- qt(0.5 + conf / 2, df_t)
est <- unname(b["d"])
se <- sqrt(V["d", "d"])
tstat <- est / se
p <- 2 * pt(-abs(tstat), df_t)
ci_low <- est - qt_ * se
ci_high <- est + qt_ * se
n <- nobs(fit)
n_clusters <- if (!is.null(cluster_col)) length(unique(d$cl)) else NULL

# Raw 2 × 2 means.
cell <- function(tr, po) { v <- d$y[d$treated == tr & d$post == po]; if (length(v)) mean(v) else NA_real_ }
m <- list(tp = cell(1, 0), tq = cell(1, 1), cp = cell(0, 0), cq = cell(0, 1))
did_raw <- (m$tq - m$tp) - (m$cq - m$cp)

# %% Event study: leads and lags relative to each treated unit's first post-treatment period
es_rows <- NULL
pretrend_f <- NULL
pretrend_p <- NULL
starts <- NULL
if (!is.null(UNIT) && !is.null(TIME)) {
  tp <- d[d$treated == 1 & d$post == 1, ]
  first_post <- tapply(tp$time, tp$unit, min)
  starts <- unique(as.numeric(first_post))
}
if (event_study) {
  if (is.null(UNIT) || is.null(TIME)) stop("The event study needs a unit and a time column.")
  rel <- d$time - as.numeric(first_post[d$unit])
  rel <- pmin(pmax(rel, -leads), lags)
  ev <- list()
  for (e in seq(-leads, lags)) {
    if (e == -1) next  # reference period
    nm <- if (e < 0) paste0("lead", -e) else paste0("lag", e)
    col <- as.numeric(!is.na(rel) & rel == e)
    if (sum(col) > 0) {
      d[[nm]] <- col
      ev[[length(ev) + 1]] <- list(e = e, name = nm)
    }
  }
  ev_names <- vapply(ev, function(x) x$name, character(1))
  es_fit <- feols(as.formula(paste("y ~", paste(c(ev_names, xs), collapse = " + "), "| unit + time")), data = d, vcov = vc)
  eb <- coef(es_fit)
  eV <- vcov(es_fit)
  edf <- unname(degrees_freedom(es_fit, "t"))
  eq <- qt(0.5 + conf / 2, edf)
  es_rows <- do.call(rbind, lapply(ev, function(x) {
    s <- sqrt(eV[x$name, x$name])
    data.frame(rel_time = x$e, estimate = unname(eb[x$name]), se = s, low = unname(eb[x$name]) - eq * s,
               high = unname(eb[x$name]) + eq * s, p = 2 * pt(-abs(unname(eb[x$name]) / s), edf))
  }))
  es_rows <- rbind(es_rows, data.frame(rel_time = -1, estimate = 0, se = 0, low = 0, high = 0, p = NA_real_))
  es_rows <- es_rows[order(es_rows$rel_time), ]
  pre <- vapply(ev, function(x) x$e <= -2, logical(1))
  if (any(pre)) {
    bp <- eb[ev_names[pre]]
    Vp <- eV[ev_names[pre], ev_names[pre], drop = FALSE]
    pretrend_f <- as.numeric(t(bp) %*% solve(Vp, bp)) / sum(pre)
    pretrend_p <- pf(pretrend_f, sum(pre), edf, lower.tail = FALSE)
  }
}

# %% Checks
checks <- list()
add_check <- function(...) checks[[length(checks) + 1]] <<- list(...)
if (!is.null(pretrend_p)) {
  if (pretrend_p < 0.05) {
    add_check(id = "pretrend", label = "Parallel pre-trends", status = "concern", downgrade_to = "L2",
              detail = sprintf("Leads before treatment differ from zero jointly (F = %.2f, %s): the groups were already diverging, so parallel trends are doubtful.", pretrend_f, cs_fmt_p(pretrend_p)))
  } else {
    add_check(id = "pretrend", label = "Parallel pre-trends", status = "pass",
              detail = sprintf("Leads before treatment are jointly compatible with zero (F = %.2f, %s). This supports, but cannot prove, parallel trends after treatment.", pretrend_f, cs_fmt_p(pretrend_p)))
  }
} else if (!is.null(UNIT) && !is.null(TIME)) {
  add_check(id = "pretrend", label = "Parallel pre-trends", status = "info",
            detail = "Turn on the event study to test whether the groups trended in parallel before treatment.")
} else {
  add_check(id = "pretrend", label = "Parallel pre-trends", status = "info",
            detail = "With only before/after periods, parallel trends cannot be tested; attest why the comparison group's change is a good counterfactual.")
}
if (is.null(cluster_col)) {
  add_check(id = "clusters", label = "Clustered standard errors", status = "concern",
            detail = "No unit or cluster column: standard errors assume independent rows, which overstates precision when units are observed repeatedly.")
} else if (n_clusters < 30) {
  add_check(id = "clusters", label = "Clustered standard errors", status = "concern",
            detail = sprintf("Only %d clusters: clustered standard errors can be too small; consider a wild cluster bootstrap.", n_clusters))
} else {
  add_check(id = "clusters", label = "Clustered standard errors", status = "pass", detail = sprintf("Standard errors clustered on %d clusters.", n_clusters))
}
if (!is.null(starts) && length(starts) > 1) {
  add_check(id = "staggered_timing", label = "Common treatment timing", status = "concern", downgrade_to = "L2",
            detail = sprintf("Treated units start in %d different periods: two-way fixed effects can be biased with staggered adoption and changing effects. Use the staggered (Callaway–Sant'Anna) design.", length(starts)))
} else if (!is.null(starts)) {
  add_check(id = "staggered_timing", label = "Common treatment timing", status = "pass", detail = "All treated units start treatment in the same period.")
}

# %% Result
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.did/twfe/out-r")
artifacts <- list()
charts <- list()
if (!is.null(es_rows)) {
  nanoparquet::write_parquet(es_rows, file.path(out, "event_study.parquet"))
  artifacts[[1]] <- list(key = "event_study", path = file.path(out, "event_study.parquet"), format = "parquet", title = "Event-study coefficients")
  charts[[length(charts) + 1]] <- cs_chart("event_study", "event-study", sprintf("Effect on %s by period relative to treatment", Y), list(
    rel_time = cs_col("Periods relative to treatment", es_rows$rel_time, kind = "numeric"),
    estimate = cs_col("Estimate", es_rows$estimate, kind = "numeric"),
    low = cs_col("Lower", es_rows$low, kind = "numeric"),
    high = cs_col("Upper", es_rows$high, kind = "numeric")
  ), controls = list(reference = -1))
}
if (!is.null(TIME)) {
  trend <- aggregate(y ~ time + treated, data = d, FUN = mean)
  trend <- trend[order(trend$treated, trend$time), ]
  label <- if (TIME_TEMPORAL) format(periods[trend$time + 1], "%Y-%m-%d") else as.numeric(periods[trend$time + 1])
  charts[[length(charts) + 1]] <- cs_chart("trends", "forecast-fan", sprintf("Mean %s by group", Y), list(
    time = cs_col(TIME, label, kind = if (TIME_TEMPORAL) "temporal" else "numeric"),
    value = cs_col(Y, trend$y, kind = "numeric"),
    kind = cs_col("kind", rep("actual", nrow(trend)), kind = "categorical", levels = "actual"),
    series = cs_col("Group", ifelse(trend$treated == 1, "Treated", "Comparison"), kind = "categorical", levels = c("Comparison", "Treated"))
  ))
}
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("After treatment began, %s changed by %.2f %s in the treated group than in the comparison group (difference-in-differences %.2f, %s CI [%.2f, %.2f], %s).",
                   Y, abs(est), if (est > 0) "more" else "less", est, pct, ci_low, ci_high, cs_fmt_p(p))
if (!is.null(pretrend_p)) {
  summary <- paste(summary, if (pretrend_p < 0.05) sprintf("Leads before treatment differ from zero (%s): parallel trends are doubtful.", cs_fmt_p(pretrend_p))
                   else sprintf("Leads before treatment are compatible with parallel trends (%s).", cs_fmt_p(pretrend_p)))
}
design <- if (!is.null(UNIT) && !is.null(TIME)) "twfe" else if (!is.null(UNIT)) "unit_fe" else if (!is.null(TIME)) "time_fe" else "2x2"
values <- list(
  estimate = est, se = se, t = tstat, p_value = p, ci_low = ci_low, ci_high = ci_high, n = n,
  n_units = if (!is.null(UNIT)) length(unique(d$unit)) else NULL,
  n_treated_units = if (!is.null(UNIT)) length(unique(d$unit[d$treated == 1])) else NULL,
  n_clusters = n_clusters, df_t = df_t, design = design,
  did_raw = did_raw, mean_treated_pre = m$tp, mean_treated_post = m$tq, mean_control_pre = m$cp, mean_control_post = m$cq,
  pretrend_f = pretrend_f, pretrend_p = pretrend_p,
  estimand = "ATT",
  effect_label = sprintf("Average effect of treatment on %s for the treated group after treatment began", Y),
  claim_level_max = "L3"
)
if (!is.null(es_rows)) {
  for (i in seq_len(nrow(es_rows))) {
    e <- es_rows$rel_time[i]
    if (e == -1) next
    values[[sprintf("es_estimate[%d]", e)]] <- es_rows$estimate[i]
    values[[sprintf("es_se[%d]", e)]] <- es_rows$se[i]
    values[[sprintf("es_p[%d]", e)]] <- es_rows$p[i]
  }
}
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
term_label <- function(nm) {
  if (nm == "d") return(sprintf("Treated × post (%s)", TREAT))
  if (nm == "post") return("Post")
  if (nm == "treated") return("Treated group")
  if (startsWith(nm, "x")) return(COVARIATES[as.integer(substring(nm, 2))])
  nm
}
coef_rows <- data.frame(term = vapply(names(b), term_label, character(1)), estimate = unname(b), se = unname(sqrt(diag(V))))
tables <- list(
  list(key = "coefficients", title = paste0("Difference-in-differences regression", if (!is.null(fe)) sprintf(" (fixed effects: %s)", fe) else ""),
       columns = list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
                      list(key = "se", label = "SE", type = "number")),
       rows = coef_rows),
  list(key = "means", title = "Group means",
       columns = list(list(key = "group", label = "Group", type = "string"), list(key = "pre", label = "Before", type = "number"),
                      list(key = "post", label = "After", type = "number"), list(key = "change", label = "Change", type = "number")),
       rows = data.frame(group = c("Treated", "Comparison"), pre = c(m$tp, m$cp), post = c(m$tq, m$cq), change = c(m$tq - m$tp, m$cq - m$cp)))
)
if (!is.null(es_rows)) {
  tables[[length(tables) + 1]] <- list(key = "event_study", title = "Event study (reference: period −1)",
    columns = list(list(key = "rel_time", label = "Period", type = "integer"), list(key = "estimate", label = "Estimate", type = "number"),
                   list(key = "se", label = "SE", type = "number"), list(key = "low", label = "Lower", type = "number"),
                   list(key = "high", label = "Upper", type = "number"), list(key = "p", label = "p", type = "p")),
    rows = es_rows)
}
cs_publish(list(
  method = "causal.did",
  methodVersion = "1.0.2",
  title = "Difference-in-differences",
  engine = cs_engine_info("fixest", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("DiD = %s, SE = %s, t(%.0f) = %s, %s, %s CI [%s, %s]", cs_fmt_num(est), cs_fmt_num(se), df_t, cs_fmt_num(tstat), cs_fmt_p(p), pct,
                cs_fmt_num(ci_low), cs_fmt_num(ci_high)),
  statistics = list(
    list(key = "estimate", label = "Difference-in-differences", value = est),
    list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high)),
    list(key = "se", label = "SE", value = se),
    list(key = "p_value", label = "p", value = p, format = "p")
  ),
  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(sprintf("Design: %s; standard errors %s; t with %.0f df.", design,
                       if (!is.null(cluster_col)) paste("clustered by", cluster_col) else "heteroskedasticity-robust (HC1)", df_t)),
  values = values,
  artifacts = artifacts,
  charts = charts
))

Sources

  • Angrist, J. D., & Pischke, J.-S. (2009). Mostly harmless econometrics. Princeton University Press (ch. 5).
  • Roth, J., Sant'Anna, P. H. C., Bilinski, A., & Poe, J. (2023). What's trending in difference-in-differences? Journal of Econometrics, 235, 2218–2244.
  • Bergé, L. (2018). Efficient estimation of maximum likelihood models with multiple fixed-effects: the R package FENmlm. CREA Discussion Papers 13.

From the CodeSplash method registry · causal.did v1.0.2.