Package 'etwfe'

Title: Extended Two-Way Fixed Effects
Description: Convenience functions for implementing extended two-way fixed effect regressions a la Wooldridge (2023, 2025, 2026) <doi:10.1093/ectj/utad016>, <doi:10.1007/s00181-025-02807-z>, <doi:10.2139/ssrn.7530698>.
Authors: Grant McDermott [aut, cre] (ORCID: <https://orcid.org/0000-0001-7883-8573>), Frederic Kluser [ctb], Ulrich Morawetz [ctb]
Maintainer: Grant McDermott <[email protected]>
License: MIT + file LICENSE
Version: 0.6.2.99
Built: 2026-11-25 13:30:47 UTC
Source: https://github.com/grantmcdermott/etwfe

Help Index


Post-estimation aggregation of ETWFE results

Description

Companion function to etwfe, enabling the recovery of aggregate treatment effects along different dimensions of interest (e.g, an event study of dynamic average treatment effects). emfx is a light wrapper around the slopes function from the marginaleffects package. If the original etwfe model was estimated with regression weights (e.g., weights = ~pop), these are also used to weight the aggregation.

Usage

emfx(
  object,
  type = c("simple", "group", "calendar", "event"),
  by_xvar = "auto",
  compress = "auto",
  collapse = compress,
  predict = c("response", "link"),
  wlevels = NULL,
  post_only = TRUE,
  window = NULL,
  lean = FALSE,
  ...
)

Arguments

object

An etwfe model object.

type

Character. The desired type of post-estimation aggregation.

by_xvar

Logical. Should the results account for heterogeneous treatment effects? Only relevant if the preceding etwfe call included a specified xvar argument, i.e. interacted categorical covariate. The default behaviour ("auto") is to automatically estimate heterogeneous treatment effects for each level of xvar if these are detected as part of the underlying etwfe model object. Users can override by setting to either FALSE or TRUE. See the "Heterogeneous treatment effects" section below.

compress

Logical. Compress the data by (period by cohort) groups before calculating marginal effects? This legacy argument was originally intended as a shortcut to reduce estimation times for large datasets. However, it is largely irrelevant as of etwfe v0.7.0, which introduced fast analytic standard errors (see the "Standard errors" section below). The default "auto" is retained for backwards compatibility and is equivalent to FALSE. Note that switching to TRUE also means losing the default unconditional standard errors, since these are not supported with data compression.

collapse

Logical. An alias for compress (only used for backwards compatability and ignored if both arguments are provided). The behaviour is identical, but it will trigger a message nudging users to rather use the compress argument.

predict

Character. The type (scale) of prediction used to compute the marginal effects. If "response" (the default), then the output is at the level of the response variable, i.e. it is the expected predictor E(Y∣X)E(Y|X). If "link", the value returned is the linear predictor of the fitted model, i.e. X⋅βX\cdot \beta. The difference should only matter for nonlinear models. (Note: This argument is typically called type when use in predict or slopes, but we rename it here to avoid a clash with the top-level type argument above.)

wlevels

Only relevant for non-binary treatments, i.e. if the preceding etwfe call included a wvar argument. Controls the treatment level(s) at which effects are evaluated:

  • NULL (default): Equivalent to "slope", except for event studies with the "never" treated control group, where it is equivalent to "observed" (since the pre-treatment estimates are level differences).

  • "slope": Average marginal effect of a one-unit change in wvar.

  • "observed": Average effect of each unit's observed treatment level, relative to no treatment (wvar = 0). This also reflects how treatment levels evolve over time, and is the closest analogue to a binary ATT.

  • Numeric vector: Effects of setting the treatment level to each of the supplied values, relative to no treatment, e.g. wlevels = c(1, 2, 5). Results are reported (and plotted) separately for each treatment level.

  • Function: As above, but with treatment levels computed by applying the function to the treated observations' wvar values, e.g. wlevels = fivenum or ⁠wlevels = \(x) quantile(x, c(0.25, 0.5, 0.75))⁠.

These options mirror the ergonomics of datagrid, which similarly accepts values or functions (e.g., datagrid(x = fivenum)). Note that effects at fixed treatment levels are linear in wvar by construction, and that levels far from the bulk of the data (e.g., the minimum and maximum in fivenum) are extrapolations.

For event studies with the "never" treated control group, the pre-treatment estimates do not depend on wvar, and are reported only once (with a missing wvar value, and as a "Pre" group in plots).

post_only

Logical. Drop pre-treatment ATTs? Only evaluated if (a) type = "event" and (b) the original etwfe model object was estimated using the default "notyet" treated control group. If conditions (a) and (b) are met then the pre-treatment effects will be zero as a mechanical result of ETWFE's estimation setup. The default behaviour (TRUE) is thus to drop these nuisance rows from the dataset. The post_only argument recognises that you may still want to keep them for presentation purposes (e.g., plotting an event study). Nevertheless, be forewarned that enabling that behaviour via FALSE is strictly performative: the "zero" treatment effects for any pre-treatment periods is purely an artefact of the estimation setup.

window

Numeric of length 1 or 2. Limits the temporal window of consideration around treatment.

  • NULL (default): Include all available periods.

  • Length 1: Truncate to a symmetric window around the treatment event. E.g., window = 2 will truncate to two pre-treatment periods and two post-treatment periods.

  • Length 2: Asymmetric window, where the first number gives the maximum number of pre-treatment periods and the second number gives the maximum number of post-treatment periods. E.g., window = c(5, 2) will truncate to five pre-treatment periods and two post-treatment periods.

Note that the pre-treatment truncation is only ever binding in cases where the "never" treated group is used as a control, i.e., etwfe(..., cgroup = "never") in the original call.

lean

Logical. Default is FALSE. Switching to TRUE enforces a lean return object; namely a simple data.frame of the main results, stripped of ancillary attributes. Note that this will disable some advanced marginaleffects post-processing features, but those are unlikely to be used in the emfx context. The upside is a potentially dramatic reduction in the size of the return object. Consequently, we may change the default to TRUE in a future version of etwfe.

...

Additional arguments passed to marginaleffects::slopes. For example, you can pass vcov = FALSE to skip standard errors entirely, or your own vcov argument (see the "Standard errors" section below). Another potentially useful application is testing whether heterogeneous treatment effects (i.e., the levels of any xvar covariate) are equal by invoking the hypothesis argument, e.g. hypothesis = "b1 = b2".

Value

A data.frame of aggregated treatment effects along the dimension(s) of interested. Note that this data.frame will have been overloaded with the slopes class, and so will come with a special print method. But the underlying columns will usually include:

  • term

  • contrast

  • ⁠<type>⁠ (i.e., the name of your type string)

  • estimate

  • std.error

  • statistic

  • p.value

  • s.value

  • conf.low

  • conf.high

Standard errors

As of etwfe v0.7.0, emfx computes its standard errors using a fast and exact analytic path, which yields both greater performance and precision than the old numeric approach (which was based on the delta method).

Moreover, we now also report "unconditional" standard errors by default, which account for sampling variation in the covariate distribution over which the treatment effects are averaged (see: marginaleffects::vcovUnconditional). Any one-way clustering in the original etwfe model (e.g., vcov = ~countyreal) is carried over automatically.

Exceptions to this rule, where emfx instead falls back to the model's own (conditional) variance-covariance matrix, are as follows:

  • Compressed data (compress = TRUE), since the compressed groups no longer map to the original observations. (Explicitly requesting unconditional standard errors for compressed data, e.g. vcov = "unconditional", is an error.)

  • Multiway or interacted clustering (e.g., vcov = ~countyreal + year), which vcovUnconditional does not support.

A warning is triggered in both cases.

Users can override the default by passing their own vcov argument, e.g. vcov = TRUE to recover the model's conditional standard errors (the default behaviour prior to etwfe v0.7.0), or vcov = marginaleffects::vcovUnconditional(type = "HC1", cluster = ~id) for finer control.

Performance

Both etwfe and emfx should be fast, even for large datasets. In particular, as of etwfe v0.7.0, emfx is orders of magnitude faster than it used to be, because it now computes standard errors using exact analytic Jacobians. (Earlier versions relied on a numerical delta method, which required estimating two prediction models for each coefficient in the model.)

Heterogeneous treatment effects

Specifying ⁠etwfe(..., xvar = <xvar>)⁠ will generate interaction effects for all levels of ⁠<xvar>⁠ as part of the main regression model. The reason that this is useful (as opposed to a regular, non-interacted covariate in the formula RHS) is that it allows us to estimate heterogeneous treatment effects as part of the larger ETWFE framework. Specifically, we can recover heterogeneous treatment effects for each level of ⁠<xvar>⁠ by passing the resulting etwfe model object on to emfx().

For example, imagine that we have a categorical variable called "age" in our dataset, with two distinct levels "adult" and "child". Running emfx(etwfe(..., xvar = age)) will tell us how the efficacy of treatment varies across adults and children. We can then also leverage the in-built hypothesis testing infrastructure of marginaleffects to test whether the treatment effect is statistically different across these two age groups; see Examples below. Note the same principles carry over to categorical variables with multiple levels, or even continuous variables (although continuous variables are not as well supported yet).

References

Wong, Jeffrey et al. (2021). You Only Compress Once: Optimal Data Compression for Estimating Linear Models. Working paper (version: March 16, 2021). Available: https://doi.org/10.48550/arXiv.2102.11297

See Also

marginaleffects::slopes which does the heavily lifting behind the scenes. etwfe is the companion estimating function that should be run before emfx.

Examples

# We'll use the base_stagg dataset from the fixest package, which simulates a
# staggered treatment rollout across 100 units over 10 years. Never-treated
# units have `year_treated = 10000`.
data("base_stagg", package = "fixest")

#
# Basic example
#

# The basic ETWFE workflow involves two consecutive function calls:
# 1) `etwfe` and 2) `emfx`

# 1) `etwfe`: Estimate a regression model with saturated interaction terms.
mod = etwfe(
  fml  = y ~ x1,       # outcome ~ controls (use 0 or 1 if none)
  tvar = year,         # time variable
  gvar = year_treated, # group variable
  data = base_stagg,   # dataset
  vcov = ~id           # vcov adjustment (here: clustered by unit)
  )

# mod ## A fixest model object with fully saturated interaction effects.

# 2) `emfx`: Recover the treatment effects of interest.

(mod_es = emfx(mod, type = "event")) # dynamic ATE a la an event study

# Etc. Other aggregation type options are "simple" (the default), "group"
# and "calendar"

# To visualize results, use the native plot method (see `?plot.emfx`)
plot(mod_es)

# Aside: With R >= 4.1.0, you can also chain the whole workflow together with
# the native pipe, e.g.:
# etwfe(
#   fml  = y ~ x1,
#   tvar = year,
#   gvar = year_treated,
#   data = base_stagg,
#   vcov = ~id
#   ) |>
#   emfx(type = "event") |>
#   plot()

# Notice that we don't get any pre-treatment effects with the default
# "notyet" treated control group. Switch to the "never" treated control
# group if you want this.
mod_never = etwfe(
  y ~ x1, tvar = year, gvar = year_treated, data = base_stagg,
  vcov = ~id,
  cgroup = "never"    ## <= use never treated group as control
  )
plot(emfx(mod_never, "event"))

#
# Heterogeneous treatment effects
#

# Example where we estimate heterogeneous treatment effects for two
# (arbitrary) groups of units.

base_stagg$grp = base_stagg$id > 50

hmod = etwfe(
  y ~ x1, tvar = year, gvar = year_treated, data = base_stagg,
  vcov = ~id,
  xvar = grp           ## <= het. TEs by grp
  )

# Heterogeneous ATEs (could also specify "event", etc.)

emfx(hmod)

# To test whether the ATEs across these two groups are statistically
# different, simply pass an appropriate "hypothesis" argument.

emfx(hmod, hypothesis = "b1 = b2")

plot(emfx(hmod))

#
# Nonlinear model (distribution / link) families
#

# Poisson example (using a transformed, strictly positive outcome)

base_stagg$y_exp = exp(base_stagg$y / 10)

pmod = etwfe(
  y_exp ~ x1, tvar = year, gvar = year_treated, data = base_stagg,
  vcov = ~id,
  family = "poisson"   ## <= family arg for nonlinear options
  )
emfx(pmod, "event")

#
# Non-binary treatments
#

# Walmart store openings and county retail employment, where the treatment
# is the number of Walmart stores in a county. Note that `ivar` is required.
data("walmart", package = "etwfe")

wmod = etwfe(
  log_retail_emp ~ 0, tvar = year, gvar = cohort, data = walmart,
  ivar = fips, vcov = ~fips,
  wvar = n_open        ## <= non-binary treatment
  )
emfx(wmod)             ## effect of each additional store

# Effects at specific treatment levels (relative to no treatment)
plot(emfx(wmod, "event", wlevels = 1:3))

Extended two-way fixed effects

Description

Estimates an "extended" two-way fixed effects regression, with fully saturated interaction effects a la Wooldridge (2023, 2025, 2026). At its heart, etwfe is a convenience function that automates a number of tedious and error prone preparation steps involving both the data and model formulae. Computation is passed on to the feols (linear) / feglm (nonlinear) functions from the fixest package. etwfe should be paired with its companion emfx function.

Usage

etwfe(
  fml = NULL,
  tvar = NULL,
  gvar = NULL,
  data = NULL,
  ivar = NULL,
  wvar = NULL,
  xvar = NULL,
  tref = NULL,
  gref = NULL,
  cgroup = c("notyet", "never"),
  fe = NULL,
  family = NULL,
  trend = FALSE,
  ...
)

Arguments

fml

A two-side formula representing the outcome (lhs) and any control variables (rhs), e.g. y ~ x1 + x2. If no controls are required, the rhs must take the value of 0 or 1, e.g. y ~ 0.

tvar

Time variable. Can be a string (e.g., "year") or an expression (e.g., year).

gvar

Group variable. Can be either a string (e.g., "first_treated") or an expression (e.g., first_treated). In a staggered treatment setting, the group variable typically denotes treatment cohort.

data

The data frame that you want to run ETWFE on.

ivar

Optional index variable. Can be a string (e.g., "country") or an expression (e.g., country). Leaving as NULL (the default) will result in group-level fixed effects being used, which is more efficient and necessary for nonlinear models (see family argument below). For binary treatments in balanced panels, group-level and unit-level fixed effects yield identical treatment effect estimates (Wooldridge, 2025). However, you may still want to cluster your standard errors by your index variable through the vcov argument. See Examples below. Note that ivar is required for non-binary treatments (see wvar below), since the equivalence no longer holds.

wvar

Optional non-binary treatment variable, e.g. a treatment intensity or dose. Can be a string (e.g., "n_stores") or an expression (e.g., n_stores). If specified, etwfe estimates heterogeneous slopes on wvar for each cohort-period combination, and the downstream emfx function aggregates these slopes (i.e., the marginal effect of a one-unit change in wvar) rather than binary ATTs. gvar should still denote the first treatment period. Requires a linear model (family = NULL) and a non-NULL ivar. See the "Non-binary treatments" section below.

xvar

Optional interacted categorical covariate for estimating heterogeneous treatment effects. Enables recovery of the marginal treatment effect for distinct levels of xvar, e.g. "child", "teenager", or "adult". Note that the "x" prefix in "xvar" represents a covariate that is interacted with treatment, as opposed to a regular control variable.

tref

Optional reference value for tvar. Defaults to its minimum value (i.e., the first time period observed in the dataset).

gref

Optional reference value for gvar. You shouldn't need to provide this if your gvar variable is well specified. But providing an explicit reference value can be useful/necessary if the desired control group takes an unusual value.

cgroup

What control group do you wish to use for estimating treatment effects. Either "notyet" treated (the default) or "never" treated.

fe

What category of fixed effects should be used? One of either "vs" (varying slopes), "feo" (fixed effects only), or "none" (no fixed effects whatsoever). If left as NULL (i.e., no explicit choice) then will default to "vs" for linear/Gaussian models, since this is the most efficient estimation option and further limits the number of "nuisance" parameters in the return model object. However, for non-Gaussian families will default to "none", since the downstream emfx function cannot compute standard errors for these models in the presence of fixed-effects. (See: https://github.com/vincentarelbundock/marginaleffects/issues/1487) Please note that the primary treatment parameters of interest should remain unchanged regardless of fe argument choice.

family

Which family to use for the estimation. Defaults to NULL, in which case fixest::feols is used. Otherwise passed to fixest::feglm, so that valid entries include "logit", "poisson", and "negbin". Note that if a non-NULL family entry is detected, ivar will automatically be set to NULL.

trend

Logical. Include cohort-specific linear time trends? Defaults to FALSE. Useful when parallel trends is in doubt (Wooldridge, 2025, 2026). Requires a numeric tvar and at least two pre-treatment periods for each treated cohort. Not available with cgroup = "never" (since cohort-specific trends and a full set of pre-treatment effects cannot both be identified). The trends enter the model as regular coefficients—rather than absorbed fixed-effect slopes—so that they can be inspected and jointly tested with pretrends().

...

Additional arguments passed to fixest::feols (or fixest::feglm). The most common example would be a vcov argument. Note that incomplete cases are dropped before any controls (or xvar) are demeaned, but only for variables in fml, the gvar, tvar, ivar and xvar arguments, and one-sided formula weights (e.g., weights = ~pop). Other sample restrictions passed here (e.g., subset, or vector weights with missing values) are applied by feols after demeaning, so you should remove the affected rows from data beforehand.

Value

A fixest object with fully saturated interaction effects, and a few additional attributes used for post-estimation in emfx.

Heterogeneous treatment effects

Specifying ⁠etwfe(..., xvar = <xvar>)⁠ will generate interaction effects for all levels of ⁠<xvar>⁠ as part of the main regression model. The reason that this is useful (as opposed to a regular, non-interacted covariate in the formula RHS) is that it allows us to estimate heterogeneous treatment effects as part of the larger ETWFE framework. Specifically, we can recover heterogeneous treatment effects for each level of ⁠<xvar>⁠ by passing the resulting etwfe model object on to emfx().

For example, imagine that we have a categorical variable called "age" in our dataset, with two distinct levels "adult" and "child". Running emfx(etwfe(..., xvar = age)) will tell us how the efficacy of treatment varies across adults and children. We can then also leverage the in-built hypothesis testing infrastructure of marginaleffects to test whether the treatment effect is statistically different across these two age groups; see Examples below. Note the same principles carry over to categorical variables with multiple levels, or even continuous variables (although continuous variables are not as well supported yet).

Non-binary treatments

Following Wooldridge (2026), we can specify a non-binary treatment variable with ⁠etwfe(..., wvar = <wvar>)⁠. This treatment can be continuous (e.g., a dollar amount), a count (e.g., number of stores), or discrete, and may vary over time after the initial treatment period.

Each cohort-period cell gets its own slope on wvar, and emfx aggregates these slopes along the usual dimensions (e.g., type = "event"). With the "never" treated control group, the pre-treatment periods enter as binary cohort-period indicators—since treatment levels are zero before treatment—while the post-treatment periods enter as slopes on wvar. The pre-treatment estimates thus test for pre-trends in levels, and emfx(..., type = "event") reports the post-treatment effects at the observed treatment level by default, so that both sides of the event study are on the same scale.

Beyond the usual no anticipation and parallel trends assumptions, identification requires a "limited selection" assumption: i.e., the expected gain from treatment may vary by cohort (and covariates), but must not otherwise depend on the level of treatment that a unit receives.

NB. Compared with the binary case, non-binary etwfe estimation imposes two additional practical constraints. First, it requires unit-level fixed effects, i.e. a non-NULL ivar (and fe != "none"). This is because the treatment intensity (dose) can vary across units within a cohort (gvar), so cohort-level fixed effects would yield inconsistent estimates. In other words, we need ivar to absorb unit heterogeneity that is potentially correlated with the treatment dose. Second, non-binary treatments are currently only supported for linear models (i.e., family = NULL).

Performance

Both etwfe and emfx should be fast, even for large datasets. In particular, as of etwfe v0.7.0, emfx is orders of magnitude faster than it used to be, because it now computes standard errors using exact analytic Jacobians. (Earlier versions relied on a numerical delta method, which required estimating two prediction models for each coefficient in the model.)

References

Wooldridge, Jeffrey M. (2025). Two-way fixed effects, the two-way Mundlak regression, and difference-in-differences estimators. Empirical Economics, 69, 2545-2587. Available: https://doi.org/10.1007/s00181-025-02807-z

Wooldridge, Jeffrey M. (2023). Simple Approaches to Nonlinear Difference-in-Differences with Panel Data. The Econometrics Journal, 26(3), C31-C66. Available: https://doi.org/10.1093/ectj/utad016

Wooldridge, Jeffrey M. (2026). A Heterogeneous Slopes Approach to Difference-in-Differences with Non-Binary Treatments. Working paper. Available: https://doi.org/10.2139/ssrn.7530698

See Also

fixest::feols(), fixest::feglm() which power the underlying estimation routines. emfx is a companion function that handles post-estimation aggregation to extract quantities of interest.

Examples

# We'll use the base_stagg dataset from the fixest package, which simulates a
# staggered treatment rollout across 100 units over 10 years. Never-treated
# units have `year_treated = 10000`.
data("base_stagg", package = "fixest")

#
# Basic example
#

# The basic ETWFE workflow involves two consecutive function calls:
# 1) `etwfe` and 2) `emfx`

# 1) `etwfe`: Estimate a regression model with saturated interaction terms.
mod = etwfe(
  fml  = y ~ x1,       # outcome ~ controls (use 0 or 1 if none)
  tvar = year,         # time variable
  gvar = year_treated, # group variable
  data = base_stagg,   # dataset
  vcov = ~id           # vcov adjustment (here: clustered by unit)
  )

# mod ## A fixest model object with fully saturated interaction effects.

# 2) `emfx`: Recover the treatment effects of interest.

(mod_es = emfx(mod, type = "event")) # dynamic ATE a la an event study

# Etc. Other aggregation type options are "simple" (the default), "group"
# and "calendar"

# To visualize results, use the native plot method (see `?plot.emfx`)
plot(mod_es)

# Aside: With R >= 4.1.0, you can also chain the whole workflow together with
# the native pipe, e.g.:
# etwfe(
#   fml  = y ~ x1,
#   tvar = year,
#   gvar = year_treated,
#   data = base_stagg,
#   vcov = ~id
#   ) |>
#   emfx(type = "event") |>
#   plot()

# Notice that we don't get any pre-treatment effects with the default
# "notyet" treated control group. Switch to the "never" treated control
# group if you want this.
mod_never = etwfe(
  y ~ x1, tvar = year, gvar = year_treated, data = base_stagg,
  vcov = ~id,
  cgroup = "never"    ## <= use never treated group as control
  )
plot(emfx(mod_never, "event"))

#
# Heterogeneous treatment effects
#

# Example where we estimate heterogeneous treatment effects for two
# (arbitrary) groups of units.

base_stagg$grp = base_stagg$id > 50

hmod = etwfe(
  y ~ x1, tvar = year, gvar = year_treated, data = base_stagg,
  vcov = ~id,
  xvar = grp           ## <= het. TEs by grp
  )

# Heterogeneous ATEs (could also specify "event", etc.)

emfx(hmod)

# To test whether the ATEs across these two groups are statistically
# different, simply pass an appropriate "hypothesis" argument.

emfx(hmod, hypothesis = "b1 = b2")

plot(emfx(hmod))

#
# Nonlinear model (distribution / link) families
#

# Poisson example (using a transformed, strictly positive outcome)

base_stagg$y_exp = exp(base_stagg$y / 10)

pmod = etwfe(
  y_exp ~ x1, tvar = year, gvar = year_treated, data = base_stagg,
  vcov = ~id,
  family = "poisson"   ## <= family arg for nonlinear options
  )
emfx(pmod, "event")

#
# Non-binary treatments
#

# Walmart store openings and county retail employment, where the treatment
# is the number of Walmart stores in a county. Note that `ivar` is required.
data("walmart", package = "etwfe")

wmod = etwfe(
  log_retail_emp ~ 0, tvar = year, gvar = cohort, data = walmart,
  ivar = fips, vcov = ~fips,
  wvar = n_open        ## <= non-binary treatment
  )
emfx(wmod)             ## effect of each additional store

# Effects at specific treatment levels (relative to no treatment)
plot(emfx(wmod, "event", wlevels = 1:3))

Plot method for emfx objects

Description

Visualize the results of an emfx call.

Usage

## S3 method for class 'emfx'
plot(
  x,
  type = c("pointrange", "errorbar", "ribbon"),
  pch = 16,
  zero = TRUE,
  grid = TRUE,
  ref = -1,
  ...
)

Arguments

x

An emfx object.

type

Character. The type of plot display. One of "pointrange" (default), "errorbar", or "ribbon".

pch

Integer or character. Which plotting character or symbol to use (see points). Defaults to 16 (i.e., small solid circle). Ignored if type = "ribbon".

zero

Logical. Should 0-zero line be emphasized? Default is TRUE.

grid

Logical. Should a background grid be displayed? Default is TRUE.

ref

Integer. Reference line marker for event-study plot. Default is -1 (i.e., the period immediately preceding treatment). To remove completely, set to NA, NULL, or FALSE. Only used if the underlying object was computed using emfx(..., type = "event").

...

Additional arguments passed to tinyplot::tinyplot.

Value

No return value, called for its side effect of producing a plot.

Examples

# We'll use the base_stagg dataset from the fixest package, which simulates a
# staggered treatment rollout across 100 units over 10 years. Never-treated
# units have `year_treated = 10000`.
data("base_stagg", package = "fixest")

#
# Basic example
#

# The basic ETWFE workflow involves two consecutive function calls:
# 1) `etwfe` and 2) `emfx`

# 1) `etwfe`: Estimate a regression model with saturated interaction terms.
mod = etwfe(
  fml  = y ~ x1,       # outcome ~ controls (use 0 or 1 if none)
  tvar = year,         # time variable
  gvar = year_treated, # group variable
  data = base_stagg,   # dataset
  vcov = ~id           # vcov adjustment (here: clustered by unit)
  )

# mod ## A fixest model object with fully saturated interaction effects.

# 2) `emfx`: Recover the treatment effects of interest.

(mod_es = emfx(mod, type = "event")) # dynamic ATE a la an event study

# Etc. Other aggregation type options are "simple" (the default), "group"
# and "calendar"

# To visualize results, use the native plot method (see `?plot.emfx`)
plot(mod_es)

# Aside: With R >= 4.1.0, you can also chain the whole workflow together with
# the native pipe, e.g.:
# etwfe(
#   fml  = y ~ x1,
#   tvar = year,
#   gvar = year_treated,
#   data = base_stagg,
#   vcov = ~id
#   ) |>
#   emfx(type = "event") |>
#   plot()

# Notice that we don't get any pre-treatment effects with the default
# "notyet" treated control group. Switch to the "never" treated control
# group if you want this.
mod_never = etwfe(
  y ~ x1, tvar = year, gvar = year_treated, data = base_stagg,
  vcov = ~id,
  cgroup = "never"    ## <= use never treated group as control
  )
plot(emfx(mod_never, "event"))

#
# Heterogeneous treatment effects
#

# Example where we estimate heterogeneous treatment effects for two
# (arbitrary) groups of units.

base_stagg$grp = base_stagg$id > 50

hmod = etwfe(
  y ~ x1, tvar = year, gvar = year_treated, data = base_stagg,
  vcov = ~id,
  xvar = grp           ## <= het. TEs by grp
  )

# Heterogeneous ATEs (could also specify "event", etc.)

emfx(hmod)

# To test whether the ATEs across these two groups are statistically
# different, simply pass an appropriate "hypothesis" argument.

emfx(hmod, hypothesis = "b1 = b2")

plot(emfx(hmod))

#
# Nonlinear model (distribution / link) families
#

# Poisson example (using a transformed, strictly positive outcome)

base_stagg$y_exp = exp(base_stagg$y / 10)

pmod = etwfe(
  y_exp ~ x1, tvar = year, gvar = year_treated, data = base_stagg,
  vcov = ~id,
  family = "poisson"   ## <= family arg for nonlinear options
  )
emfx(pmod, "event")

#
# Non-binary treatments
#

# Walmart store openings and county retail employment, where the treatment
# is the number of Walmart stores in a county. Note that `ivar` is required.
data("walmart", package = "etwfe")

wmod = etwfe(
  log_retail_emp ~ 0, tvar = year, gvar = cohort, data = walmart,
  ivar = fips, vcov = ~fips,
  wvar = n_open        ## <= non-binary treatment
  )
emfx(wmod)             ## effect of each additional store

# Effects at specific treatment levels (relative to no treatment)
plot(emfx(wmod, "event", wlevels = 1:3))

Test for pre-trends

Description

Jointly tests the null hypothesis of parallel (common) trends prior to treatment, following Wooldridge (2025, Sec. 7). A light wrapper around fixest::wald() that selects the relevant coefficients on your behalf. The test depends on how the etwfe model was estimated:

  • trend = TRUE: tests that the cohort-specific linear trends are jointly zero.

  • cgroup = "never": tests that the pre-treatment cohort-period effects (i.e., the "leads" in an event study) are jointly zero.

These are alternative tests of the same null hypothesis, and cannot be combined in a single model; cohort trends and a full set of pre-treatment effects are not separately identified. Note that the cgroup = "never" model is equivalent to augmenting the default "notyet" model with the pre-treatment effects, as per Wooldridge's test regression.

Usage

pretrends(x, interactions = FALSE, ...)

Arguments

x

An etwfe model object.

interactions

Logical. Should interactions between the tested terms and any (demeaned) controls or xvar covariates also be included in the joint null? Defaults to FALSE, following Wooldridge (2025), who notes that testing for covariate-dependent violations of parallel trends comes at a considerable cost in power.

...

Additional arguments passed to fixest::wald(), e.g. print or vcov.

Details

The cgroup = "never" test involves roughly one restriction per pre-treatment period per cohort, which can be a lot. Each cohort's restrictions are informed mainly by that cohort's own units, so a cluster-robust test needs many clusters (units) per cohort. With few clusters per cohort, the cluster-robust vcov can badly underestimate the variance of some combinations of the pre-treatment effects, leading the joint test to over-reject (sometimes wildly) even when the individual estimates look unremarkable. The cohort trends test (one restriction per cohort) is much less susceptible to this problem.

Value

The result of fixest::wald(): a list containing the test statistic, p-value, degrees of freedom, and vcov type.

References

Wooldridge, Jeffrey M. (2025). Two-way fixed effects, the two-way Mundlak regression, and difference-in-differences estimators. Empirical Economics, 69, 2545-2587. Available: https://doi.org/10.1007/s00181-025-02807-z

See Also

fixest::wald(), which performs the underlying test.

Examples

#
# Option 1: cgroup = "notyet" (default) + trend = TRUE
#

# Tests whether the cohort-specific linear trends are jointly zero. Requires
# at least two pre-treatment periods per cohort, so we drop the cohort
# treated in year 2.
data("base_stagg", package = "fixest")
mod_trend = etwfe(
  y ~ x1, tvar = year, gvar = year_treated,
  data = subset(base_stagg, year_treated != 2), vcov = ~id,
  trend = TRUE # <= cohort trends (with default cgroup = "notyet")
)
pretrends(mod_trend)

#
# Option 2: cgroup = "never"
#

# Tests whether the pre-treatment effects (event study leads) are jointly
# zero. This involves many more restrictions, so we switch to the bundled
# walmart dataset, which has enough units per cohort for a reliable
# cluster-robust test.
mod_never = etwfe(
  log_retail_emp ~ 0, tvar = year, gvar = cohort,
  ivar = fips, wvar = n_open,
  data = walmart, vcov = ~fips,
  cgroup = "never" # <= never-treated control group
)
pretrends(mod_never)

Walmart openings and county retail employment

Description

A balanced county-level panel of Walmart store openings and retail employment in the United States, 1977–1999. No county in the panel housed a Walmart before 1986, and openings are staggered thereafter, so that the data are a natural testbed for (non-binary) staggered difference-in-differences. This is the dataset used in the empirical application of Wooldridge (2026).

Usage

walmart

Format

A data frame with 29,624 rows (1,288 counties x 23 years) and 5 variables:

fips

County FIPS code.

year

Year (1977–1999).

cohort

Year in which the county's first Walmart opened (1986–1999), or 0 if the county did not have a Walmart by 1999 (never treated).

n_open

Number of Walmart stores open in the county in that year.

log_retail_emp

Log of county retail employment (rounded to four decimal places).

Details

The underlying data were constructed by Brown and Butts (2025), with the sample of counties following the selection criteria of Basker (2005), and were subsequently used by Wooldridge (2025, 2026). We are grateful to the original authors for permission to redistribute them here.

Please note that this is a subset of the original data. It retains only the five variables needed to illustrate the etwfe functionality, whereas the original contains many more (e.g., employment in other sectors and pre-treatment county characteristics). The outcome variable has also been rounded to reduce file size, although this does not affect results at the precision reported by Wooldridge (2026). Users interested in the full dataset should consult the original sources.

Source

Subset of the data constructed by Brown and Butts (2025), as distributed with the replication files for Wooldridge (2026). See the References below.

References

Basker, Emek (2005). Job Creation or Destruction? Labor Market Effects of Wal-Mart Expansion. Review of Economics and Statistics, 87(1), 174-183. Available: https://doi.org/10.1162/0034653053327568

Brown, Nicholas and Kyle Butts (2025). Dynamic Treatment Effect Estimation with Interactive Fixed Effects and Short Panels. Journal of Econometrics, 250, 106013. Available: https://doi.org/10.1016/j.jeconom.2025.106013

Wooldridge, Jeffrey M. (2025). Two-way fixed effects, the two-way Mundlak regression, and difference-in-differences estimators. Empirical Economics, 69, 2545-2587. Available: https://doi.org/10.1007/s00181-025-02807-z

Wooldridge, Jeffrey M. (2026). A Heterogeneous Slopes Approach to Difference-in-Differences with Non-Binary Treatments. Working paper. Available: https://doi.org/10.2139/ssrn.7530698

Examples

data("walmart", package = "etwfe")

# Effect of each additional Walmart store on (log) retail employment, cf.
# Wooldridge (2026, Table 7.1)
mod = etwfe(
  log_retail_emp ~ 0, tvar = year, gvar = cohort, data = walmart,
  ivar = fips, vcov = ~fips,
  wvar = n_open
  )
emfx(mod)