---
title: "Getting Started with cdid"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting Started with cdid}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  error = FALSE
)
```

`cdid` estimates treatment effects from changes within units, even when some outcomes are missing. This guide fits a cohort model, summarizes the results in an event study, and then shows how to estimate effects when treatment can stop or restart. See the [full user guide](https://github.com/dvbn/cdid/tree/main/docs) for other specifications. The package builds on [Callaway and Sant'Anna (2021)](https://doi.org/10.1016/j.jeconom.2020.12.001) and [Bellégo, Benatia and Dortet-Bernadet (2025)](https://doi.org/10.1016/j.jeconom.2024.105783).

## 1. Create an incomplete panel

This example follows 900 units for up to five periods. Treatment starts in period 3 for one group. The other group remains untreated. Each unit has two consecutive observed outcomes, so different units contribute changes over different intervals. The treatment effect starts at 1 and increases by 0.25 per period.

```{r simulate-panel}
library(cdid)
set.seed(20261029)

n_units <- 900
n_periods <- 5

units <- data.frame(
  id = seq_len(n_units),
  x = rbinom(n_units, size = 1, prob = 0.5)
)
units$g <- ifelse(
  runif(n_units) < plogis(-0.2 + 0.4 * units$x),
  3,
  0
)
unit_alpha <- rnorm(n_units)
window_start <- sample.int(n_periods - 1L, size = n_units, replace = TRUE)

panel_data <- data.frame(
  id = rep(units$id, each = n_periods),
  time = rep(seq_len(n_periods), times = n_units),
  g = rep(units$g, each = n_periods),
  x = rep(units$x, each = n_periods)
)

treated_post <- panel_data$g == 3 & panel_data$time >= 3
true_effect <- ifelse(treated_post, 1 + 0.25 * (panel_data$time - 3), 0)
y_latent <- rep(unit_alpha, each = n_periods) +
  (0.4 + 0.2 * panel_data$x) * panel_data$time +
  true_effect +
  rnorm(nrow(panel_data), sd = 0.5)

in_window <- panel_data$time == rep(window_start, each = n_periods) |
  panel_data$time == rep(window_start + 1L, each = n_periods)
panel_data$y <- ifelse(in_window, y_latent, NA_real_)
```

We verify that `(id, time)` pairs are unique and count observed outcomes per unit across the unit table `units`:

```{r check-structure}
stopifnot(!anyDuplicated(panel_data[c("id", "time")]))
obs_per_unit <- tabulate(
  match(panel_data$id[!is.na(panel_data$y)], units$id),
  nbins = nrow(units)
)
table(cohort = units$g, observed_dates = obs_per_unit)
```

## 2. Data requirements and identification conditions

In chained mode, `data` must have unique `(idname, tname)` rows, finite numeric calendar dates `tname`, numeric outcomes `yname` that are finite when observed and kept as `NA` when missing (never replaced by `0`), and a constant known treatment cohort `gname` per unit (`0` for never treated). No unit is required to have a complete history or an observed outcome at the cohort baseline date ($t = 2$). The unit table `frame` defines the study population $F$ of size $N = |F|$: units observed at two or more dates ($A$) supply within-unit changes $\Delta Y_{s,t} = Y_t - Y_s$, while singletons (one observed outcome) and units with no observed outcomes supply no differences but remain in $F$ for population counts, cohort shares, active selection or imputation models, and influence functions for all study units.

With the default `selection = "none"`, no observation-probability or imputation model is fitted. Instead, for each cohort and each date pair $(s, t)$ used by the estimator, the subset of units observed at both $s$ and $t$ is assumed representative of its cohort in the study population with respect to the mean outcome change:
$$E[Y_t - Y_s \mid G = g, S_{s,t} = 1] = E[Y_t - Y_s \mid G = g].$$
This is a population expectation condition in the study population; it does not require individual units to have identical outcome changes, realized sample means to agree across observation windows, or arbitrary missingness patterns to identify every target. Observation may depend on the time-invariant unit fixed effect $\alpha_i$ removed by within-unit differencing, provided it does not select on the mean change.

Identification and inference also require: no treatment anticipation before $g$ (`anticipation = 0`, so $t = 2$ is cohort 3's reference date); conditional parallel trends from the reference period (`pt_assumption = "post"`); overlap in the active comparison risk sets; for doubly robust estimation (`est_method = "dr"`), either a correctly specified treatment propensity logit or a correctly specified control outcome-change regression given `xformla`; and catalog support connecting each target date to the reference date with eligible controls.

In this design, the untreated conditional mean change from $s$ to $t$ is $(t - s)(0.4 + 0.2x)$ in both cohorts, so conditional parallel trends and the control regressions hold under either outcome-pooling choice. By default, `outcome_pooling = "separate"` lets each comparison have its own outcome-regression slopes. Set `outcome_pooling = "pooled"` to share slopes per calendar step when that restriction is credible. The treatment logit is also correctly specified by `~ x`, and the independently assigned observation windows preserve the cohort mean changes in population.

## 3. Estimating and inspecting group-time effects

We fit chained doubly robust estimation with `xformla = ~ x` and `selection = "none"`, combining the overlapping adjacent-period comparisons by feasible two-step GMM (`gmm_weighting = "optimal"`). Here we set `bstrap = FALSE` and `cband = FALSE` to compute fast analytical standard errors and pointwise normal confidence intervals; by default (`bstrap = TRUE, cband = TRUE`), `cdid` computes multiplier-bootstrap standard errors and simultaneous confidence bands.

```{r fit-att-gt}
fit <- cdid::att_gt(
  yname = "y",
  tname = "time",
  idname = "id",
  gname = "g",
  xformla = ~ x,
  data = panel_data,
  frame = units,
  control_group = "nevertreated",
  est_method = "dr",
  mode = "chained",
  selection = "none",
  pt_assumption = "post",
  bstrap = FALSE,
  cband = FALSE
)
summary(fit)
```

Compare the estimates with the population targets: `0` for the pre-treatment comparison reported at period `2`, and `1.00`, `1.25`, `1.50` at periods `3`, `4`, `5`. Realized estimates vary across samples; one draw does not establish bias, coverage, or relative efficiency. `tidy()` exposes cell-level estimates, availability and support reasons; `glance()` gives a one-row fit summary:

```{r inspect-tidy-glance}
cells <- cdid::tidy(fit)
cells[, c("target.id", "role", "estimate", "std.error",
          "conf.low", "conf.high", "available",
          "support.status", "support.reason")]
cdid::glance(fit)
```

## 4. Aggregating effects and event-study plotting

`cdid::aggte()` aggregates the retained `cdid_MP` result without refitting and inherits its inference settings unless overridden. We compute the overall post-treatment average (`type = "simple"`) and event-time estimates (`type = "dynamic"`), inspect the tidy dynamic table, and plot the event study with `cdid::ggdid()`:

```{r aggregate-and-plot, fig.width = 6, fig.height = 3.5}
agg_simple <- cdid::aggte(fit, type = "simple")
agg_dynamic <- cdid::aggte(fit, type = "dynamic")

summary(agg_simple)
cdid::tidy(agg_dynamic)[, c("label", "estimate",
                            "std.error", "conf.low", "conf.high",
                            "available", "reason")]
cdid::ggdid(agg_dynamic)
```

## 5. Advanced options and further documentation

Choose the treatment adjustment with `est_method`. Use `"reg"` for outcome regression, `"ipw"` for weighting, or `"dr"` for both. To adjust for missing outcomes that depend on covariates, set `selection = "conditional_mtar"` and choose observation weighting, change imputation or their augmented combination with `selection_est_method`.

Use `chain_report(fit)` to read the comparisons that identify each effect. If target and control cohorts are observed over different date pairs, the guide describes when `cross_pair = TRUE` can connect their changes. To inspect fitted equations and coefficient tables, use `control = list(keep_nuisance = TRUE)` when fitting and then call `nuisance_models(fit)`.

## 6. When treatment can stop and restart

The example above uses `gname`: after their first treatment date, units remain treated. The resulting cohort effects can be followed over time and aggregated into an event study.

For a history such as `0, 1, 0, 1`, supply current binary treatment through `dname` instead. This requests a static model: earlier treatment has no lingering effect beyond current status, although effects can differ across units and dates. It compares entrants with units that remain untreated and exiters with units that remain treated, under the corresponding parallel-trends assumptions. Both directions are reported as treatment effects, `Y(1) - Y(0)`.

Keep treatment known at every study date, including rows with missing outcomes. The example below has a treatment effect of 1.5, allows exit and re-entry, and makes observation depend on `x`. It combines treatment DR (`est_method`) with augmented missing-outcome correction (`selection_est_method`). These are separate choices.

```{r static-entry-exit}
set.seed(20261106)
n_st <- 320
t_st <- 4
d_paths <- rbind(
  c(0L, 0L, 0L, 0L),
  c(0L, 1L, 1L, 0L),
  c(1L, 1L, 0L, 1L),
  c(1L, 0L, 0L, 1L),
  c(1L, 1L, 1L, 1L)
)
path_idx <- sample.int(nrow(d_paths), size = n_st, replace = TRUE)
x_st <- rnorm(n_st)
alpha_st <- rnorm(n_st, sd = 0.5)

static_panel <- data.frame(
  id = rep(seq_len(n_st), each = t_st),
  time = rep(seq_len(t_st), times = n_st),
  x = rep(x_st, each = t_st),
  d = as.integer(t(d_paths[path_idx, ]))
)
y_st_latent <- rep(alpha_st, each = t_st) +
  (0.3 + 0.2 * static_panel$x) * static_panel$time +
  1.5 * static_panel$d +
  rnorm(nrow(static_panel), sd = 0.4)
static_panel$y <- ifelse(
  runif(nrow(static_panel)) < plogis(0.8 + 0.4 * static_panel$x),
  y_st_latent,
  NA_real_
)

fit_static <- cdid::att_gt(
  yname = "y",
  tname = "time",
  idname = "id",
  dname = "d",
  xformla = ~ x,
  data = static_panel,
  est_method = "dr",
  selection = "conditional_mtar",
  selection_est_method = "dr",
  selection_model = "pair_logit",
  selection_pooling = "within_group",
  imputation_pooling = "within_group",
  imputation_scale = "per_period",
  outcome_pooling = "separate",
  switchers = "both",
  bstrap = FALSE,
  cband = FALSE
)
summary(fit_static)
fit_static$aggregate[c("estimate", "se", "ci_lower", "ci_upper", "total_switchers")]
```

The static model adapts the binary specialization of de Chaisemartin et al. (2026), <https://arxiv.org/abs/2201.06898v7>, using chained comparisons for missing outcomes. Its switcher-weighted average is stored in `fit_static$aggregate`; `aggte()` remains for cohort effects. The cohort options of section 5 (`cross_pair = TRUE`, `pt_assumption = "ctrl"` or `"all"`, and `gmm_weighting = "within"`) do not apply to this static model and are refused with `dname`. See the entry and exit guide in the repository for the model assumptions and other treatment and missing-outcome adjustments.

See the installed help pages (`?cdid::att_gt`, `?cdid::chain_report`, `?cdid::aggte`, `?cdid::conditional_did_pretest`, `?cdid::reexports`) and the repository documentation at <https://github.com/dvbn/cdid>, especially `docs/methods/cross-pair-chaining.md`, `docs/examples/short-pretreatment-windows.md`, `docs/help/prepare-data.md`, `docs/help/investigate-missingness.md`, `docs/methods/missing-outcomes.md`, `docs/methods/static-entry-exit.md`, and the companion notebook.
