Skip to content

CCausal inference · causal.staggered

Staggered difference-in-differences (Callaway–Sant'Anna)

What was the effect of a treatment that different units adopted at different times?

Estimates group-time average treatment effects ATT(g, t) — for each cohort first treated in period g, at each period t — against never-treated or not-yet-treated units, with outcome regression, inverse probability weighting or the doubly robust estimator, and aggregates them overall, by event time (an event study), by cohort and by calendar period. Avoids the bias of two-way fixed effects with staggered adoption and heterogeneous effects.

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

A real result

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

Staggered difference-in-differences (Callaway–Sant'Anna)Recorded · Python and R agreeRecorded 2026-11-17 · 73 values compared
R

ATT = −0.04, SE = 0.01, 95% CI [−0.06, −0.02], p < .001

ATT
−0.0400
95% CI
[−0.0635, −0.0164]
p
< .001

Plots

Effect on lemp by periods since treatmentWere treated and control units on parallel paths before treatment, and how did the effect evolve after?
View data
ATTUpperLowerPeriods since treatment
0.03050.06000.0010−3
−0.00060.0255−0.0266−2
−0.02450.0034−0.0524−1
−0.01990.0032−0.04310
−0.0510−0.0178−0.08411
−0.1373−0.0658−0.20872
−0.1008−0.0335−0.16823

Assumptions

  • Parallel pre-trends — Pre-treatment ATT(g, t) are jointly compatible with zero (χ²(5) = 7.79, p = .168).
  • Comparison units — 309 never-treated units form the comparison group.

Aggregated effects

AggregationATTSE
simple−0.04000.0120
dynamic−0.07720.0200
group−0.03100.0124
calendar−0.04170.0160

By event time (periods since treatment)

Event timeATTSELowerUpper
−30.03050.01500.00100.0600
−2−0.00060.0133−0.02660.0255
−1−0.02450.0142−0.05240.0034
0−0.01990.0118−0.04310.0032
1−0.05100.0169−0.0841−0.0178
2−0.13730.0364−0.2087−0.0658
3−0.10080.0344−0.1682−0.0335

Group-time effects ATT(g, t)

CohortPeriodATTSE
2,0042,004−0.01050.0233
2,0042,005−0.07040.0310
2,0042,006−0.13730.0364
2,0042,007−0.10080.0344
2,0062,0040.00650.0233
2,0062,005−0.00280.0196
2,0062,006−0.00460.0178
2,0062,007−0.04120.0202
2,0072,0040.03050.0150
2,0072,005−0.00270.0164
2,0072,006−0.03110.0179
2,0072,007−0.02610.0167
  • Estimator dr, varying base period, anticipation 0; analytic standard errors from influence functions (no bootstrap).
Python

ATT = −0.04, SE = 0.01, 95% CI [−0.06, −0.02], p < .001

ATT
−0.0400
95% CI
[−0.0635, −0.0164]
p
< .001

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

Assumptions

  • Parallel pre-trends — Pre-treatment ATT(g, t) are jointly compatible with zero (χ²(5) = 7.79, p = .168).
  • Comparison units — 309 never-treated units form the comparison group.

Aggregated effects

AggregationATTSE
simple−0.04000.0120
dynamic−0.07720.0200
group−0.03100.0124
calendar−0.04170.0160

By event time (periods since treatment)

Event timeATTSELowerUpper
−30.03050.01500.00100.0600
−2−0.00060.0133−0.02660.0255
−1−0.02450.0142−0.05240.0034
0−0.01990.0118−0.04310.0032
1−0.05100.0169−0.0841−0.0178
2−0.13730.0364−0.2087−0.0658
3−0.10080.0344−0.1682−0.0335

Group-time effects ATT(g, t)

CohortPeriodATTSE
2,0042,004−0.01050.0233
2,0042,005−0.07040.0310
2,0042,006−0.13730.0364
2,0042,007−0.10080.0344
2,0062,0040.00650.0233
2,0062,005−0.00280.0196
2,0062,006−0.00460.0178
2,0062,007−0.04120.0202
2,0072,0040.03050.0150
2,0072,005−0.00270.0164
2,0072,006−0.03110.0179
2,0072,007−0.02610.0167
  • Estimator dr, varying base period, anticipation 0; analytic standard errors from influence functions (no bootstrap).

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

  • Mpdta neverc1_mpdta · cohort: first treat · outcome: lemp · time: year · unit: county
  • Mpdta dr covariatec1_mpdta · cohort: first treat · covariates: lpop · outcome: lemp · time: year · unit: county
  • Notyet ipw universalc1_mpdta · cohort: first treat · covariates: lpop · outcome: lemp · time: year · unit: county
  • No never treatedc1_stagger · cohort: cohort · covariates: size · outcome: y · time: year · unit: unit
  • Degenerate constantc1_mpdta · cohort: first treat · outcome: lemp · time: year · unit: county
  • Degenerate n3c1_mpdta · cohort: first treat · outcome: lemp · time: year · unit: county

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 outcome measured for each unit in each period.
Unitcategorical / numeric · 1 column
Panel unit; the panel is balanced (units missing a period are dropped).
Timenumeric · 1 column
Period as a number (year, month index).
First treated periodnumeric · 1 column
The period a unit was first treated (constant within a unit); 0 for never-treated units.
Covariatesnumeric / boolean · 0–10 columns
Pre-treatment covariates for conditional parallel trends (values from the base period are used).

Choices you make

hypothesis

Comparison unitsdefault never_treated

Units used as comparisons: never treated, or not yet treated (more units, needs no anticipation).

  • Never treated(default) — Compares cohorts only with units never treated; the cleaner choice when you have enough of them.
  • Not yet treated — Also uses units as controls until they're treated; more data, assuming they don't react before treatment starts.
Confidence leveldefault 0.95

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

statistics

Estimatordefault dr

With no covariates the three estimators are identical.

  • Doubly robust(default) — Combines propensity weights and an outcome regression, and stays consistent if either is right; the usual choice.
  • Inverse probability weighting — Reweights comparison units by propensity score; pick it when you trust the treatment model more.
  • Outcome regression — Adjusts with an outcome regression; pick it when you trust the outcome model more.
Base perioddefault varying

Pre-period comparisons: short differences (varying) or all relative to the period before treatment (universal).

  • Varying (pre-periods: short differences)(default) — Compares each pre-period with the one before it; good for spotting a sudden jump before treatment.
  • Universal (period before treatment) — Compares every period with the one before treatment; the event-study plot reads like a classic one.
Anticipation (periods)default 0

Periods before treatment in which units may already react.

Headline aggregationdefault simple

How group-time effects are combined into the headline number: overall, by event time, by cohort or by period.

  • Overall (weighted by cohort size)(default) — Averages every group-time effect, weighted by cohort size, into one number; use it for a single headline effect.
  • Event study (average of post-treatment event times) — Averages effects by time since treatment; pick it to see how the effect builds or fades.
  • By cohort — Averages effects within each treatment cohort; pick it when early and late adopters may respond differently.
  • By calendar period — Averages effects by calendar period; pick it when the effect may change with outside events.

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

    Cohorts would have followed the comparison units' trend without treatment (conditional on covariates). Pre-treatment ATT(g, t) test it.

  • No anticipationNot checked from data: state why it holds

    Units do not react before their cohort's treatment period (beyond the anticipation set).

  • Overlap

    Treated and comparison units have comparable covariates (propensity scores away from 0 and 1).

  • Comparison units

    Never-treated or not-yet-treated units stand in for each cohort's counterfactual; too few of them make the estimates unstable.

What it reports

  • Tests: Average effect on the treated
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.
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.
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.
att_simple
The average effect among those who actually received treatment.
se_simple
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
att_dynamic
The average effect among those who actually received treatment.
se_dynamic
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
att_group
The average effect among those who actually received treatment.
se_group
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
att_calendar
The average effect among those who actually received treatment.
se_calendar
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
n_cohorts
How many independent units the analysis used; it sets precision and power.
n_never_treated
How many independent units the analysis used; it sets precision and power.
n_periods
How many independent units the analysis used; it sets precision and power.

Per group, level or term: pretrend_p, check[<id>], attgt[<cohort, period>], attgt_se[…], group_estimate[<cohort>], group_se[…], calendar_estimate[<period>], es_estimate[<event time>], es_se[…], headline, pretrend_chi2

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses pandas, numpy, scipy, codesplash; R uses did, nanoparquet, codesplashr.

Default traps between the two languages

  • R calls did::att_gt (analytic influence-function standard errors: bstrap = FALSE, cband = FALSE) and did::aggte; Python computes the same estimators (doubly robust, IPW and outcome-regression panel DiD), their influence functions and the aggregations. Logit propensity scores are fit by IRLS in both (agreement ≈ 1e-10). Against did on a 632-scenario sweep, 628 agree at the parity tolerance; the other 4 are one panel, worst 2.0e-7, where did's logit stops early.
  • The pre-trend Wald statistic is computed from the influence functions in both engines; did rounds its own p-value to 5 decimals, so the unrounded value is reported.
Python

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

# Staggered difference-in-differences (Callaway–Sant'Anna)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.staggered 1.0.2 · spec c4b7ba7e55b878c5
# Dataset: c1_mpdta (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
from scipy import stats

import codesplash as cs
from codesplash import ml as csml
from codesplash.causal import staggered as csdid  # twin of R's did::att_gt / did::aggte

# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_mpdta.parquet", columns=["lemp", "county", "year", "first treat"])
n_input = len(df)
df["county"] = pd.Categorical(df["county"], categories=sorted(df["county"].dropna().unique()))
df = df.dropna(subset=["lemp", "county", "year", "first treat"])  # listwise deletion over the analysis columns
df["county"] = df["county"].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, ["lemp", "county", "year", "first treat"])  # infinite values stop the run (registry/errors.yaml)

# %% Design: a balanced panel (units × periods)
Y, UNIT, TIME, COHORT = "lemp", "county", "year", "first treat"
COVARIATES = []
control_group = "never_treated"
estimator = "dr"
base_period = "varying"
anticipation = float(0)
headline = "simple"
conf = 0.95
d = df.assign(_unit=df[UNIT].astype(str), _time=df[TIME].astype(float), _g=df[COHORT].astype(float))
if d.groupby("_unit")["_g"].nunique().max() > 1:
    raise ValueError(f"{COHORT} must be constant within each unit (the period it was first treated, 0 if never).")
times_all = np.sort(d["_time"].unique())
counts = d.groupby("_unit")["_time"].nunique()
balanced = counts[counts == len(times_all)].index
if len(balanced) < d["_unit"].nunique():
    warnings.append(f"{d['_unit'].nunique() - len(balanced)} unit(s) not observed in every period were dropped (balanced panel).")
d = d[d["_unit"].isin(balanced)]
units = np.sort(d["_unit"].unique())
if len(units) < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=UNIT, min=2, k=len(units))
if np.unique(d[Y].to_numpy(dtype=float)).size < 2:  # every ATT(g, t) would be 0 with a zero standard error
    cs.cs_error("CS_E_CONSTANT", column=Y)
cohort0 = d.groupby("_unit")["_g"].first().reindex(units).to_numpy()
keep_t, cohort, keep_u, glist, notes = csdid.prepare(times_all, cohort0, control_group, anticipation)
tlist = times_all[keep_t]
units, cohort = units[keep_u], cohort[keep_u]
d = d[d["_unit"].isin(units) & d["_time"].isin(tlist)]
if len(glist) == 0:
    cs.cs_error("CS_E_UNDEFINED", what="The staggered difference-in-differences", reason="no treated cohort has a period before its treatment")
wide = d.pivot_table(index="_unit", columns="_time", values=Y, aggfunc="first").reindex(index=units, columns=tlist)
Ym = wide.to_numpy(dtype=float)
Xs = []
for t in tlist:
    cols = [np.ones(len(units))]
    for c in COVARIATES:
        cols.append(d[d["_time"] == t].set_index("_unit")[c].reindex(units).to_numpy(dtype=float))
    Xs.append(np.column_stack(cols))
n = len(units)

# %% ATT(g, t), aggregations and the pre-trend test
cells, psi = csdid.att_gt(Ym, Xs, cohort, tlist, glist, control_group, estimator, base_period, anticipation)
se_cells = csdid.cell_se(psi)
agg = csdid.aggregate(cells, psi, cohort, tlist, glist)
W, pretrend_p, n_pre = csdid.pretest(cells, psi)
z = stats.norm.ppf(0.5 + conf / 2)
est, se = agg[headline]["att"], agg[headline]["se"]
p = float(2 * stats.norm.sf(abs(est / se)))
ci_low, ci_high = est - z * se, est + z * se

# %% 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"Pre-treatment ATT(g, t) differ from zero jointly (χ²({n_pre}) = {W:.2f}, {cs.fmt_p(pretrend_p)}): parallel trends are doubtful."})
    else:
        checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "pass",
                       "detail": f"Pre-treatment ATT(g, t) are jointly compatible with zero (χ²({n_pre}) = {W:.2f}, {cs.fmt_p(pretrend_p)})."})
else:
    checks.append({"id": "pretrend", "label": "Parallel pre-trends", "status": "info", "detail": "No pre-treatment cells to test parallel trends."})
n_never = int((cohort == 0).sum())
if control_group == "never_treated" and n_never < 20:
    checks.append({"id": "comparison_group", "label": "Comparison units", "status": "concern",
                   "detail": f"Only {n_never} never-treated units: estimates rest on a small comparison group; consider not-yet-treated units."})
else:
    checks.append({"id": "comparison_group", "label": "Comparison units", "status": "pass",
                   "detail": f"{n_never} never-treated units" + (" plus not-yet-treated units" if control_group == "not_yet_treated" else "") + " form the comparison group."})
if COVARIATES and estimator in ("dr", "ipw"):
    checks.append({"id": "overlap", "label": "Overlap", "status": "info",
                   "detail": "Propensity scores near 1 for comparison units are trimmed (above 0.995) as in DRDID; check covariate overlap between cohorts and comparison units."})

# %% Result
out = csml.out_dir("target/academy-parity/run-953/causal.staggered/mpdta-never/out-python")
cell_df = pd.DataFrame(cells).assign(se=se_cells)
cell_df.to_parquet(os.path.join(out, "att_gt.parquet"), index=False)
artifacts = [{"key": "att_gt", "path": os.path.join(out, "att_gt.parquet"), "format": "parquet", "title": "Group-time average treatment effects"}]
dyn = agg["dynamic"]["by"]
summary = (
    f"Averaged {'over cohorts and post-treatment periods' if headline == 'simple' else {'dynamic': 'over post-treatment event times', 'group': 'over cohorts', 'calendar': 'over calendar periods'}[headline]}, "
    f"treatment changed {Y} by {est:.3g} ({conf:.0%} CI [{ci_low:.3g}, {ci_high:.3g}], {cs.fmt_p(p)}), estimated cohort by cohort against "
    f"{'never-treated' if control_group == 'never_treated' else 'not-yet-treated'} units."
)
if pretrend_p is not None:
    summary += (f" Pre-treatment effects differ from zero ({cs.fmt_p(pretrend_p)}): parallel trends are doubtful." if pretrend_p < 0.05
                else f" Pre-treatment effects are compatible with parallel trends ({cs.fmt_p(pretrend_p)}).")
fin = lambda v: None if v is None or not np.isfinite(v) else float(v)
values = {
    "estimate": est, "se": fin(se), "ci_low": ci_low, "ci_high": ci_high, "p_value": p, "n": n,
    "att_simple": agg["simple"]["att"], "se_simple": fin(agg["simple"]["se"]), "att_dynamic": agg["dynamic"]["att"], "se_dynamic": fin(agg["dynamic"]["se"]),
    "att_group": agg["group"]["att"], "se_group": fin(agg["group"]["se"]), "att_calendar": agg["calendar"]["att"], "se_calendar": fin(agg["calendar"]["se"]),
    "n_cohorts": len(glist), "n_never_treated": n_never, "n_periods": len(tlist), "pretrend_chi2": W, "pretrend_p": pretrend_p,
    "estimand": "ATT", "headline": headline,
    "effect_label": f"Average effect of treatment on {Y} for treated cohorts after they were treated",
    "claim_level_max": "L3",
}
for e, a, s in dyn:
    values[f"es_estimate[{e:g}]"] = a
    values[f"es_se[{e:g}]"] = fin(s)
for g, a, s in agg["group"]["by"]:
    values[f"group_estimate[{g:g}]"] = a
    values[f"group_se[{g:g}]"] = fin(s)
for t, a, s in agg["calendar"]["by"]:
    values[f"calendar_estimate[{t:g}]"] = a
for c, s in zip(cells, se_cells):
    values[f"attgt[{c['group']:g}:{c['time']:g}]"] = c["att"]
    values[f"attgt_se[{c['group']:g}:{c['time']:g}]"] = float(s)
for c in checks:
    values[f"check[{c['id']}]"] = c["status"]
by_rows = lambda kind: [{"key": k, "estimate": a, "se": s, "low": a - z * s, "high": a + z * s} for k, a, s in agg[kind]["by"]]
cs.publish({
    "method": "causal.staggered",
    "methodVersion": "1.0.2",
    "title": "Staggered difference-in-differences (Callaway–Sant'Anna)",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"ATT = {cs.fmt_num(est)}, SE = {cs.fmt_num(se)}, {conf:.0%} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}], {cs.fmt_p(p)}",
    "statistics": [
        {"key": "estimate", "label": "ATT", "value": est},
        {"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
        {"key": "p_value", "label": "p", "value": p, "format": "p"},
    ],
    "tables": [
        {"key": "aggregations", "title": "Aggregated effects",
         "columns": [{"key": "type", "label": "Aggregation", "type": "string"}, {"key": "estimate", "label": "ATT", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}],
         "rows": [{"type": k, "estimate": agg[k]["att"], "se": agg[k]["se"]} for k in ("simple", "dynamic", "group", "calendar")]},
        {"key": "event_study", "title": "By event time (periods since treatment)",
         "columns": [{"key": "key", "label": "Event time", "type": "number"}, {"key": "estimate", "label": "ATT", "type": "number"},
                     {"key": "se", "label": "SE", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"}, {"key": "high", "label": "Upper", "type": "number"}],
         "rows": by_rows("dynamic")},
        {"key": "att_gt", "title": "Group-time effects ATT(g, t)",
         "columns": [{"key": "group", "label": "Cohort", "type": "number"}, {"key": "time", "label": "Period", "type": "number"},
                     {"key": "att", "label": "ATT", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}],
         "rows": cell_df[["group", "time", "att", "se"]].to_dict("records")},
    ],
    "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,
    "notes": [f"Estimator {estimator}, {base_period} base period, anticipation {anticipation:g}; analytic standard errors from influence functions (no bootstrap)."],
    "values": values,
    "artifacts": artifacts,
    "charts": [cs.chart("event_study", "event-study", f"Effect on {Y} by periods since treatment", {
        "rel_time": cs.col("Periods since treatment", [r[0] for r in dyn], kind="numeric"),
        "estimate": cs.col("ATT", [r[1] for r in dyn], kind="numeric"),
        "low": cs.col("Lower", [r[1] - z * r[2] for r in dyn], kind="numeric"),
        "high": cs.col("Upper", [r[1] + z * r[2] for r in dyn], kind="numeric"),
    }, controls={"reference": -1 if base_period == "universal" else None})],
})
R

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

# Staggered difference-in-differences (Callaway–Sant'Anna)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.staggered 1.0.2 · spec c4b7ba7e55b878c5
# Dataset: c1_mpdta (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
library(did)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_mpdta.parquet", col_select = c("lemp", "county", "year", "first treat")))
n_input <- nrow(df)
df[["county"]] <- factor(df[["county"]], levels = sort(unique(df[["county"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("lemp", "county", "year", "first treat")]), , 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("lemp", "county", "year", "first treat"))  # infinite values stop the run (registry/errors.yaml)

# %% Design: a balanced panel (units × periods)
Y <- "lemp"
UNIT <- "county"
TIME <- "year"
COHORT <- "first treat"
COVARIATES <- c()
control_group <- "never_treated"
estimator <- "dr"
base_period <- "varying"
anticipation <- 0
headline <- "simple"
conf <- 0.95
d <- data.frame(unit = as.character(df[[UNIT]]), t = as.numeric(df[[TIME]]), g = as.numeric(df[[COHORT]]), y = as.numeric(df[[Y]]))
for (j in seq_along(COVARIATES)) d[[paste0("x", j)]] <- as.numeric(df[[COVARIATES[j]]])
if (any(tapply(d$g, d$unit, function(v) length(unique(v))) > 1)) {
  stop(sprintf("%s must be constant within each unit (the period it was first treated, 0 if never).", COHORT))
}
counts <- tapply(d$t, d$unit, function(v) length(unique(v)))
balanced <- names(counts)[counts == length(unique(d$t))]
if (length(balanced) < length(counts)) {
  warnings <- c(warnings, sprintf("%d unit(s) not observed in every period were dropped (balanced panel).", length(counts) - length(balanced)))
}
d <- d[d$unit %in% balanced, ]
units <- sort(unique(d$unit), method = "radix")
if (length(units) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = UNIT, min = 2, k = length(units))
if (length(unique(d$y)) < 2) cs_error("CS_E_CONSTANT", column = Y)  # every ATT(g, t) would be 0 with a zero standard error
d$id <- match(d$unit, units)  # did needs a numeric id
# Treated cohorts with a period before their treatment (did's rule): cohorts after the last period count as never
# treated, units treated in the first period drop out, and without never-treated units the last cohort is the comparison.
times_all <- sort(unique(d$t))
cohorts <- d$g[match(units, d$unit)]
cohorts[cohorts > max(times_all) + anticipation] <- 0
glist <- unique(cohorts[cohorts > 0 & cohorts > min(times_all) + anticipation])
if (!any(cohorts == 0)) glist <- glist[glist != max(cohorts)]
if (!length(glist)) {
  cs_error("CS_E_UNDEFINED", what = "The staggered difference-in-differences", reason = "no treated cohort has a period before its treatment")
}

# %% ATT(g, t) with did (analytic influence-function standard errors: no bootstrap)
xformla <- if (length(COVARIATES)) as.formula(paste("~", paste(paste0("x", seq_along(COVARIATES)), collapse = " + "))) else ~1
res <- suppressWarnings(att_gt(
  yname = "y", tname = "t", idname = "id", gname = "g", xformla = xformla, data = d, panel = TRUE,
  control_group = if (control_group == "never_treated") "nevertreated" else "notyettreated",
  est_method = estimator, base_period = base_period, anticipation = anticipation,
  bstrap = FALSE, cband = FALSE, alp = 1 - conf, allow_unbalanced_panel = FALSE, print_details = FALSE
))
aggs <- lapply(c(simple = "simple", dynamic = "dynamic", group = "group", calendar = "calendar"),
               function(tp) suppressWarnings(aggte(res, type = tp, bstrap = FALSE, cband = FALSE, na.rm = TRUE)))
psi <- as.matrix(res$inffunc)
n <- nrow(psi)
se_cells <- sqrt(colSums(psi^2) / n / n)
# did's own pre-test p-value is rounded to 5 decimals: recompute it from the influence functions.
pre <- which(res$group > res$t & se_cells > 0 & is.finite(se_cells))
if (length(pre)) {
  Vp <- crossprod(psi[, pre, drop = FALSE]) / n
  W <- if (rcond(Vp) > .Machine$double.eps) as.numeric(n * t(res$att[pre]) %*% solve(Vp, res$att[pre])) else NULL
  pretrend_p <- if (!is.null(W)) pchisq(W, length(pre), lower.tail = FALSE) else NULL
} else {
  W <- NULL
  pretrend_p <- NULL
}
z <- qnorm(0.5 + conf / 2)
est <- aggs[[headline]]$overall.att
se <- aggs[[headline]]$overall.se
p <- 2 * pnorm(-abs(est / se))
ci_low <- est - z * se
ci_high <- est + z * se

# %% 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("Pre-treatment ATT(g, t) differ from zero jointly (χ²(%d) = %.2f, %s): parallel trends are doubtful.", length(pre), W, cs_fmt_p(pretrend_p)))
  } else {
    add_check(id = "pretrend", label = "Parallel pre-trends", status = "pass",
              detail = sprintf("Pre-treatment ATT(g, t) are jointly compatible with zero (χ²(%d) = %.2f, %s).", length(pre), W, cs_fmt_p(pretrend_p)))
  }
} else {
  add_check(id = "pretrend", label = "Parallel pre-trends", status = "info", detail = "No pre-treatment cells to test parallel trends.")
}
# Never-treated units after did's recoding (cohorts after the last period count as never treated;
# without never-treated units the last cohort is the comparison group when control = never treated).
g_unit <- tapply(d$g, d$id, `[`, 1)
g_unit[g_unit > max(d$t) + anticipation] <- 0
if (!any(g_unit == 0) && control_group == "never_treated") g_unit[g_unit == max(g_unit)] <- 0
n_never <- sum(g_unit == 0)
if (control_group == "never_treated" && n_never < 20) {
  add_check(id = "comparison_group", label = "Comparison units", status = "concern",
            detail = sprintf("Only %d never-treated units: estimates rest on a small comparison group; consider not-yet-treated units.", n_never))
} else {
  add_check(id = "comparison_group", label = "Comparison units", status = "pass",
            detail = paste0(sprintf("%d never-treated units", n_never), if (control_group == "not_yet_treated") " plus not-yet-treated units" else "", " form the comparison group."))
}
if (length(COVARIATES) && estimator %in% c("dr", "ipw")) {
  add_check(id = "overlap", label = "Overlap", status = "info",
            detail = "Propensity scores near 1 for comparison units are trimmed (above 0.995) as in DRDID; check covariate overlap between cohorts and comparison units.")
}

# %% Result
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.staggered/mpdta-never/out-r")
cell_df <- data.frame(group = res$group, time = res$t, post = as.integer(res$group <= res$t), att = res$att, se = se_cells)
nanoparquet::write_parquet(cell_df, file.path(out, "att_gt.parquet"))
artifacts <- list(list(key = "att_gt", path = file.path(out, "att_gt.parquet"), format = "parquet", title = "Group-time average treatment effects"))
fin <- function(v) if (is.null(v) || is.na(v)) NULL else v
dyn <- aggs$dynamic
g3 <- function(v) formatC(v, digits = 3, format = "g")
how <- switch(headline, simple = "over cohorts and post-treatment periods", dynamic = "over post-treatment event times", group = "over cohorts", calendar = "over calendar periods")
summary <- sprintf("Averaged %s, treatment changed %s by %s (%.0f%% CI [%s, %s], %s), estimated cohort by cohort against %s units.",
                   how, Y, g3(est), conf * 100, g3(ci_low), g3(ci_high), cs_fmt_p(p), if (control_group == "never_treated") "never-treated" else "not-yet-treated")
if (!is.null(pretrend_p)) {
  summary <- paste(summary, if (pretrend_p < 0.05) sprintf("Pre-treatment effects differ from zero (%s): parallel trends are doubtful.", cs_fmt_p(pretrend_p))
                   else sprintf("Pre-treatment effects are compatible with parallel trends (%s).", cs_fmt_p(pretrend_p)))
}
values <- list(
  estimate = est, se = fin(se), ci_low = ci_low, ci_high = ci_high, p_value = p, n = n,
  att_simple = aggs$simple$overall.att, se_simple = fin(aggs$simple$overall.se), att_dynamic = aggs$dynamic$overall.att, se_dynamic = fin(aggs$dynamic$overall.se),
  att_group = aggs$group$overall.att, se_group = fin(aggs$group$overall.se), att_calendar = aggs$calendar$overall.att, se_calendar = fin(aggs$calendar$overall.se),
  n_cohorts = length(unique(res$group)), n_never_treated = n_never, n_periods = length(unique(res$t)) + if (base_period == "varying") 1L else 0L,
  pretrend_chi2 = W, pretrend_p = pretrend_p,
  estimand = "ATT", headline = headline,
  effect_label = sprintf("Average effect of treatment on %s for treated cohorts after they were treated", Y),
  claim_level_max = "L3"
)
for (i in seq_along(dyn$egt)) {
  values[[sprintf("es_estimate[%s]", format(dyn$egt[i]))]] <- dyn$att.egt[i]
  values[sprintf("es_se[%s]", format(dyn$egt[i]))] <- list(fin(dyn$se.egt[i]))
}
for (i in seq_along(aggs$group$egt)) {
  values[[sprintf("group_estimate[%s]", format(aggs$group$egt[i]))]] <- aggs$group$att.egt[i]
  values[sprintf("group_se[%s]", format(aggs$group$egt[i]))] <- list(fin(aggs$group$se.egt[i]))
}
for (i in seq_along(aggs$calendar$egt)) values[[sprintf("calendar_estimate[%s]", format(aggs$calendar$egt[i]))]] <- aggs$calendar$att.egt[i]
for (i in seq_along(res$att)) {
  values[[sprintf("attgt[%s:%s]", format(res$group[i]), format(res$t[i]))]] <- res$att[i]
  values[[sprintf("attgt_se[%s:%s]", format(res$group[i]), format(res$t[i]))]] <- se_cells[i]
}
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
by_rows <- function(a) data.frame(key = a$egt, estimate = a$att.egt, se = a$se.egt, low = a$att.egt - z * a$se.egt, high = a$att.egt + z * a$se.egt)
cs_publish(list(
  method = "causal.staggered",
  methodVersion = "1.0.2",
  title = "Staggered difference-in-differences (Callaway–Sant'Anna)",
  engine = cs_engine_info("did", "DRDID", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("ATT = %s, SE = %s, %.0f%% CI [%s, %s], %s", cs_fmt_num(est), cs_fmt_num(se), conf * 100, cs_fmt_num(ci_low), cs_fmt_num(ci_high), cs_fmt_p(p)),
  statistics = list(
    list(key = "estimate", label = "ATT", value = est),
    list(key = "ci", label = sprintf("%.0f%% CI", conf * 100), value = c(ci_low, ci_high)),
    list(key = "p_value", label = "p", value = p, format = "p")
  ),
  tables = list(
    list(key = "aggregations", title = "Aggregated effects",
         columns = list(list(key = "type", label = "Aggregation", type = "string"), list(key = "estimate", label = "ATT", type = "number"), list(key = "se", label = "SE", type = "number")),
         rows = data.frame(type = names(aggs), estimate = vapply(aggs, function(a) a$overall.att, numeric(1)), se = vapply(aggs, function(a) a$overall.se, numeric(1)))),
    list(key = "event_study", title = "By event time (periods since treatment)",
         columns = list(list(key = "key", label = "Event time", type = "number"), list(key = "estimate", label = "ATT", type = "number"),
                        list(key = "se", label = "SE", type = "number"), list(key = "low", label = "Lower", type = "number"), list(key = "high", label = "Upper", type = "number")),
         rows = by_rows(dyn)),
    list(key = "att_gt", title = "Group-time effects ATT(g, t)",
         columns = list(list(key = "group", label = "Cohort", type = "number"), list(key = "time", label = "Period", type = "number"),
                        list(key = "att", label = "ATT", type = "number"), list(key = "se", label = "SE", type = "number")),
         rows = cell_df[, c("group", "time", "att", "se")])
  ),
  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("Estimator %s, %s base period, anticipation %s; analytic standard errors from influence functions (no bootstrap).", estimator, base_period, format(anticipation))),
  values = values,
  artifacts = artifacts,
  charts = list(cs_chart("event_study", "event-study", sprintf("Effect on %s by periods since treatment", Y), list(
    rel_time = cs_col("Periods since treatment", dyn$egt, kind = "numeric"),
    estimate = cs_col("ATT", dyn$att.egt, kind = "numeric"),
    low = cs_col("Lower", dyn$att.egt - z * dyn$se.egt, kind = "numeric"),
    high = cs_col("Upper", dyn$att.egt + z * dyn$se.egt, kind = "numeric")
  ), controls = list(reference = if (base_period == "universal") -1 else NULL)))
))

Sources

  • Callaway, B., & Sant'Anna, P. H. C. (2021). Difference-in-differences with multiple time periods. Journal of Econometrics, 225, 200–230.
  • Sant'Anna, P. H. C., & Zhao, J. (2020). Doubly robust difference-in-differences estimators. Journal of Econometrics, 219, 101–122.

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