---
title: "Extended TWFE and other DiD estimators"
date: "2024-12-09"
---
## Staggered DiD without treatment reversal
This blog is adopted from the tutorial of paneltools package.
https://yiqingxu.org/tutorials/panel.html#Installing_Packages
I added Wooldridge's ETWFE, which is my favorite estimator with staggered DiD. It is easy to understand and implement. It also works with nonlinear model such as logit and poisson.
```{r}
#| message: false
#| warning: false
#| cache: true
#devtools:: install_github("xuyiqing/paneltools")
library(paneltools)
data(paneltools)
library(tidyverse)
hh2019 <- as_tibble(hh2019)
hh2019
```
This data is from @hainmueller-hangartner-2019, in which the authors investigate the effects of indirect democracy (versus direct democracy) on naturalization rates in Switzerland using municipality-year level panel data from 1991 to 2009. The study shows that a switch from direct to indirect democracy increased naturalization rates by an average of 1.22 percentage points (Model 1 of Table 1 in the paper).
```{r}
#| message: false
#| warning: false
#| cache: true
#devtools:: install_github("xuyiqing/panelView")
library(panelView)
panelview(nat_rate_ord ~ indirect, data = hh2019, index = c("bfs","year"),
xlab = "Year", ylab = "Unit", display.all = T,
gridOff = TRUE, by.timing = TRUE)
```
The panel is 22,971 municipality-years: 1,209 Swiss municipalities observed from
1991 to 2009. The outcome `nat_rate_ord` is the ordinary naturalization rate and
`indirect` marks the switch from direct to indirect democracy, adopted at
different dates by different municipalities — staggered treatment timing.
### TWFE
First we do a TWFE model on it.
```{r}
#| message: false
#| warning: false
#| cache: true
library(fixest)
model_twfe <- feols(nat_rate_ord~indirect|bfs+year,
data=hh2019, cluster = "bfs")
summary( model_twfe)
```
TWFE gives 1.33932 with a municipality-clustered standard error of 0.1865, close
to the 1.22 the original authors report. Keep that number in view: everything
below is an attempt to work out whether it can be trusted.
TWFE has issues when there is staggered adoption and heterogeneous treatment effects.
@goodman-bacon-2021 demonstrates that the two-way fixed-effects (TWFE) estimator in a staggered adoption setting can be represented as a weighted average of all possible 2x2 difference-in-differences (DID) estimates between different cohorts. However, when treatment effects change over time heterogeneously across cohorts, the “forbidden” comparisons that use post-treatment data from early adopters as controls for late adopters may introduce bias in the TWFE estimator. We employ the procedure outlined in @goodman-bacon-2021 and decompose the TWFE estimate using the command bacon in the bacondecomp package.
"Negative weights" can be the other issue. Basically it is a weighted average of comparison between different cohorts. The weights can be negative in a TWFE model.
```{r}
#| message: false
#| warning: false
#| cache: true
library(bacondecomp)
df_bacon <- bacon(nat_rate_ord~indirect,
data = hh2019,
id_var = "bfs",
time_var = "year")
coef_bacon <- sum(df_bacon$estimate * df_bacon$weight)
coef_bacon
ggplot(df_bacon) +
aes(x = weight, y = estimate, shape = factor(type), color = factor(type)) +
labs(x = "Weight", y = "Estimate", shape = "Type", color = 'Type') +
geom_point()
```
The decomposition sums to 1.339325, reproducing the TWFE estimate exactly. It
splits into four kinds of 2x2 comparison:
| comparison | weight | average estimate |
|---|---:|---:|
| Treated vs Untreated | 0.458 | 1.612 |
| Later vs Always Treated | 0.314 | 0.752 |
| Earlier vs Later Treated | 0.176 | 1.978 |
| Later vs Earlier Treated | 0.052 | 0.323 |
The clean comparisons — treated against never-treated — carry 46% of the weight
and give 1.61. The forbidden ones, which use already-treated units as controls,
carry 0.314 + 0.052 = 37% and give much smaller numbers, 0.75 and 0.32. That is
what pulls the TWFE estimate down from 1.61 to 1.34.
The problem shown in Bacon decomposition here is the comparison between "Later" and "Earlier Treated". It's a "forbidden" comparison.
TWFE with event history type of graph.
```{r}
#| message: false
#| warning: false
#| cache: true
df.use <- hh2019 |>
na.omit()
df <- as.data.frame(
hh2019 |>
group_by(bfs) |>
mutate(treatment_mean = mean(indirect,na.rm = TRUE))
)
df.use <- df[which(df$treatment_mean<1),]
df.twfe <- as_tibble(get.cohort(df.use,D="indirect",index=c("bfs","year"),start0 = TRUE))
# time_to_treatment is NA when the unit is always treated, or never treated. It needs to be set to an arbitrary value for the twfe model.
df.twfe$treat <- as.numeric(df.twfe$treatment_mean>0) # drop always treated units
df.twfe[which(is.na(df.twfe$Time_to_Treatment)),'Time_to_Treatment'] <- 0 # can be an arbitrary value
twfe.est <- feols(nat_rate_ord ~ i(Time_to_Treatment, treat, ref = -1)| bfs + year,
data = df.twfe, cluster = "bfs")
summary(twfe.est)
twfe.output <- as.matrix(twfe.est$coeftable)
twfe.output <- as.data.frame(twfe.output)
twfe.output$Time <- c(c(-18:-2),c(0:17))+1
p.twfe <- esplot(twfe.output,Period = 'Time',Estimate = 'Estimate',
SE = 'Std. Error', xlim = c(-12,10))
p.twfe
```
The event study and every estimator below use `df.use`, which drops the 283
always-treated municipalities. The static TWFE above used the full panel, where
"later vs always treated" comparisons carry 31% of the weight. On the same
restricted sample, static TWFE gives:
```{r}
#| label: twfe-same-sample
model_twfe_use <- fixest::feols(nat_rate_ord ~ indirect | bfs + year,
data = df.use, cluster = "bfs")
summary(model_twfe_use)
```
### Sun and Abraham
The @sun-abraham-2021 estimator is a weighted average of the average treatment effect (ATT) estimates for each cohort, obtained from a TWFE regression that includes cohort dummies fully interacted with indicators of relative time to the treatment’s onset. The iw estimator is robust to heterogeneous treatment effects (HTE) and can be implemented using the command sunab in the package fixest.
```{r}
#| message: false
#| warning: false
#| cache: true
df.sa <- df.twfe
df.sa[which(is.na(df.sa$FirstTreat)),"FirstTreat"] <- 1000 # replace NA with an arbitrary number
model.sa.1 <- feols(nat_rate_ord~sunab(FirstTreat,year)|bfs+year,
data = df.sa, cluster = "bfs")
summary(model.sa.1,agg = "ATT")
sa.output <- as.matrix(model.sa.1$coeftable)
sa.output <- as.data.frame(sa.output)
sa.output$Time <- c(c(-18:-2),c(0:17))+1
p.sa <- esplot(sa.output,Period = 'Time',Estimate = 'Estimate',
SE = 'Std. Error', xlim = c(-12,10))
p.sa
```
## Callaway and Sant’Anna
@callaway-santanna-2021 build the estimator from group-time average treatment effects $ATT(g,t)$ — the effect on cohort $g$ at time $t$ — each identified by comparing the treated cohort to a never-treated or not-yet-treated comparison group. The $ATT(g,t)$ are estimated by outcome regression, inverse-probability weighting, or a doubly-robust combination of the two, rather than from a single fully-interacted TWFE regression. These group-time effects are then aggregated with weights into summary parameters (overall, event-study, or by cohort). The estimator is robust to heterogeneous treatment effects (HTE) and can be implemented with the `att_gt` function in the `did` package.
```{r}
#| message: false
#| warning: false
#| cache: true
library(did)
df.cs <- df.twfe
df.cs[which(is.na(df.cs$FirstTreat)),"FirstTreat"] <- 0 # replace NA with 0
cs.est.1 <- att_gt(yname = "nat_rate_ord",
gname = "FirstTreat",
idname = "bfs",
tname = "year",
xformla = ~1,
control_group = "nevertreated",
allow_unbalanced_panel = TRUE,
data = df.cs,
est_method = "reg")
cs.est.att.1 <- aggte(cs.est.1, type = "simple", na.rm=T, bstrap = F)
print(cs.est.att.1)
cs.att.1 <- aggte(cs.est.1, type = "dynamic",
bstrap=FALSE, cband=FALSE, na.rm=T)
print(cs.att.1)
cs.output <- cbind.data.frame(Estimate = cs.att.1$att.egt,
SE = cs.att.1$se.egt,
time = cs.att.1$egt + 1)
p.cs.1 <- esplot(cs.output,Period = 'time',Estimate = 'Estimate',
SE = 'SE', xlim = c(-12,10))
p.cs.1
```
### Imai, Kim, and Wang
PanelMatch is an R package implementing a set of methodological tools proposed by @imai-2023 that enables researchers to apply matching methods for causal inference on time-series cross-sectional data with binary treatments. The package includes implementations of matching methods based on propensity scores and Mahalanobis distance, as well as weighting methods. PanelMatch enables users to easily calculate a variety of possible quantities of interest, along with standard errors. The software is flexible, allowing users to tune the matching, refinement, and estimation procedures with a large number of parameters. The package also offers a variety of visualization and diagnostic tools for researchers to better understand their data and assess their results.
```{r}
#| message: false
#| warning: false
#| cache: true
library(PanelMatch)
df.pm <- as.data.frame(df.twfe)
# we need to convert the unit and time indicator to integer
df.pm[,"bfs"] <- as.integer(as.factor(df.pm[,"bfs"]))
df.pm[,"year"] <- as.integer(as.factor(df.pm[,"year"]))
df.pm <- df.pm[,c("bfs","year","nat_rate_ord","indirect")]
# Create PanelData object (new API)
pd <- PanelData(df.pm, unit.id = "bfs", time.id = "year",
treatment = "indirect", outcome = "nat_rate_ord")
PM.results <- PanelMatch(lag=3,
panel.data = pd,
refinement.method = "none",
qoi = "att",
lead = c(0:3),
match.missing = TRUE)
## For pre-treatment dynamic effects
PM.results.placebo <- PanelMatch(lag=3,
panel.data = pd,
refinement.method = "none",
qoi = "att",
lead = c(0:3),
match.missing = TRUE,
placebo.test = TRUE)
PE.results.pool <- PanelEstimate(PM.results, panel.data = pd, pooled = TRUE)
summary(PE.results.pool)
PE.results <- PanelEstimate(PM.results, panel.data = pd)
PE.results.placebo <- placebo_test(PM.results.placebo, panel.data = pd, plot = F)
est_lead <- as.vector(estimates(PE.results))
est_lag <- tryCatch(as.vector(estimates(PE.results.placebo)),
error = function(e) as.vector(PE.results.placebo$estimates))
sd_lead <- tryCatch(apply(PE.results$bootstrapped.estimates,2,sd),
error = function(e) rep(NA, length(est_lead)))
sd_lag <- tryCatch(apply(PE.results.placebo$bootstrapped.estimates,2,sd),
error = function(e) rep(NA, length(est_lag)))
coef <- c(est_lag, 0, est_lead)
sd <- c(sd_lag, 0, sd_lead)
pm.output <- cbind.data.frame(ATT=coef, se=sd, t=c(-2:4))
p.pm <- esplot(data = pm.output,Period = 't',
Estimate = 'ATT',SE = 'se')
p.pm
```
### Liu, Wang and Xu
@liu-wang-xu-2024 proposes a method for estimating the fixed effect counterfactual model by utilizing the untreated observations. It is essentially an imputation method that uses the untreated observations to estimate the counterfactual outcome for the treated.
```{r}
#| message: false
#| warning: false
#| cache: true
library(fect)
out.fect <- fect(nat_rate_ord~indirect, data = df,
index = c("bfs","year"),
method = 'fe', se = TRUE)
print(out.fect$est.avg)
fect.output <- as.matrix(out.fect$est.att)
print(fect.output)
fect.output <- as.data.frame(fect.output)
fect.output$Time <- c(-17:18)
p.fect <- esplot(fect.output,Period = 'Time',Estimate = 'ATT',
SE = 'S.E.',CI.lower = "CI.lower",
CI.upper = 'CI.upper',xlim = c(-12,10))
p.fect
```
@borusyak-jaravel-spiess-2024 with package didimputation almost gives the same result as @liu-wang-xu-2024.
### Wooldridge
@wooldridge-2021-etwfe, also called extended TWFE (ETWFE), is to allow more flexibility to make TWFE work properly. The problem with TWFE is that we do not specify it flexibly enough. If we allow heterogeneous treatment effect, then we cannot expect the canonical TWFE to work properly.
```{r}
#| message: false
#| warning: false
#| cache: true
df.wool <- df.twfe
df.wool[which(is.na(df.wool$FirstTreat)),"FirstTreat"] <- 0 # replace NA with 0
library(etwfe)
model.wool = etwfe(
fml = nat_rate_ord ~ 1, # outcome ~ controls
tvar = year, # time variable
gvar = FirstTreat, # group variable
data = df.wool, # dataset
vcov = ~bfs, # vcov adjustment (here: clustered)
cgroup = "never"
)
model.wool
emfx(model.wool)
mod_es = emfx(model.wool, type = "event", post_only=FALSE)
mod_es
wool.output <- mod_es |>
filter(event != -1) |>
mutate(Time = event + 1) |>
as.data.frame()
p.wool <- esplot(wool.output,Period = 'Time',Estimate = 'estimate',
SE = 'std.error', xlim = c(-12,10))
p.wool
```
Note that in order to get pre-event estimates, we need to set "cgroup=never" in the etwfe function. Otherwise, ETWFE will only give us post-event estimates. Under the default setting, the control group comprises the “not-yet” treated units, therefore all pre-treatment effects are mechanistically set to zero. By setting "cgroup=never", we only use never treated units as the control group. This way we can get pre-treatment estimates, but we are not using all available information for the control group, therefore the estimates may not be as efficient as the default setting. That cost is visible in the two runs below: the never-treated version gives an ATT of 1.33 with a standard error of 0.288, while the default not-yet-treated version gives 1.51 with a standard error of 0.188 --- a little over a third narrower.
Also we don't have control variable here. If we have, it is very easy to incorporate into ETWFE. Wooldridge used the Mundlak device to incorporate control variables, which is a very simple and intuitive way to do it.
If we do the default setting and plot only post-event estimates:
```{r}
#| message: false
#| warning: false
#| cache: true
model.wool2 = etwfe(
fml = nat_rate_ord ~ 1, # outcome ~ controls
tvar = year, # time variable
gvar = FirstTreat, # group variable
data = df.wool, # dataset
vcov = ~bfs # vcov adjustment (here: clustered)
)
model.wool2
emfx(model.wool2)
mod_es2 = emfx(model.wool2, type = "event")
mod_es2
wool.output2 <- mod_es2 |>
filter(event != -1) |>
mutate(Time = event + 1) |>
as.data.frame()
p.wool2 <- esplot(wool.output2, Period = 'Time',Estimate = 'estimate',
SE = 'std.error', xlim = c(0,10))
p.wool2
```
## Comparing the estimators
It is worth collecting what all of these produced on the same data:
| estimator | ATT | s.e. |
|---|---:|---:|
| TWFE (full panel) | 1.339 | 0.187 |
| TWFE (without always-treated) | 1.609 | 0.195 |
| Sun and Abraham | 1.331 | 0.288 |
| Callaway and Sant'Anna (simple) | 1.331 | 0.302 |
| Callaway and Sant'Anna (dynamic) | 1.221 | 0.631 |
| Imai, Kim and Wang | 1.178 | 0.335 |
| Liu, Wang and Xu | 1.506 | 0.204 |
| Wooldridge ETWFE | 1.330 | 0.288 |
Three things stand out. Sun-Abraham, Callaway-Sant'Anna and ETWFE agree to three
digits at 1.33 — they are different routes to the same never-treated-control
estimand, and they land on the same number. The spread across the six heterogeneity-robust estimators, 1.18 to 1.51, is
smaller than their standard errors, so on this data the choice among them does
not change the conclusion.
TWFE needs more care, because the two TWFE rows use different samples. On the
full panel it gives 1.339, close to the robust estimators. But those estimators
all use `df.use`, which drops the 283 always-treated municipalities. On that same
sample TWFE gives 1.609, about 0.28 above Sun-Abraham, Callaway-Sant'Anna and
ETWFE, or about 1.4 of its standard errors. The full-panel TWFE lands near 1.33
because its "later vs always treated" comparisons, 31% of the weight with an
average of 0.75, pull it down. So the closeness says nothing
about how small the contamination is. Compared on the same sample, TWFE is the
outlier.
## Staggered DiD with treatment reversal
With treatment reversal (ie., the treated units go back to control), Wooldridge's method still works. However, I don't think package "etwfe" has it implemented.
Several packages handle treatment reversal. Besides `fect` and `PanelMatch`, the estimator of @dechaisemartin-dhaultfoeuille-2020, implemented in `DIDmultiplegt` and its successor `did_multiplegt_dyn` (R and Stata), was designed for treatments that switch on and off. It compares units whose treatment changes between two periods with units whose treatment does not, so it never uses a switching unit as a control.
We can probably manually do ETWFE with treatment reversal. See Wooldridge's dropbox for the code in Stata. The basic idea is to treat cohorts as different treatment beginning time and exit time combinations. Then do the same regression with interactions of cohort dummies with the time dummies. It is very flexible. The tricky part is to get the marginal effect and its standard error right.
## Summary
With staggered adoption and effects that vary across cohorts, a single TWFE coefficient mixes clean comparisons with forbidden ones that use already-treated units as controls. The Goodman-Bacon decomposition shows the mix. Sun-Abraham, Callaway-Sant'Anna, imputation (Borusyak et al., Liu-Wang-Xu), PanelMatch and Wooldridge's ETWFE all avoid the forbidden comparisons in different ways. ETWFE is the simplest: a TWFE regression flexible enough to give each cohort its own effect in each period.
On the Swiss naturalization data, TWFE on the full panel gives 1.339. The decomposition shows 37% of the weight on forbidden comparisons, which pull the estimate down from the clean comparisons' 1.61. Sun-Abraham, Callaway-Sant'Anna and ETWFE agree at 1.33, and the six robust estimators fall between 1.18 and 1.51. They drop the always-treated municipalities, and on that sample TWFE gives 1.609, so the full-panel agreement is a coincidence of samples. Treatment reversal needs `fect`, PanelMatch or `did_multiplegt_dyn`, or ETWFE built by hand with exit cohorts.
---
<!-- see-also-footer -->
*Systematic treatment: [R](https://xiangao.github.io/causal_econometrics_guide/did.html) · [Julia](https://xiangao.github.io/causal_econometrics_julia/did.html).*