### Install did2s package
Source: https://github.com/kylebutts/did2s/blob/main/README.md
Instructions for installing the did2s package from CRAN or the development version from GitHub.
```R
install.packages("did2s")
devtools::install_github("kylebutts/did2s")
```
--------------------------------
### Install did2s Package in R
Source: https://github.com/kylebutts/did2s/blob/main/docs/index.html
Installs the did2s package from CRAN or the development version from GitHub. Requires R and potentially the devtools package for GitHub installation.
```r
install.packages("did2s")
devtools::install_github("kylebutts/did2s")
```
--------------------------------
### Load did2s package and example dataset
Source: https://github.com/kylebutts/did2s/blob/main/docs/articles/Two-Stage-Difference-in-Differences.html
Initializes the did2s environment and loads the df_het dataset, which contains heterogeneous treatment effects for analysis.
```R
library(did2s)
library(ggplot2)
# Load heterogeneous treatment dataset from the package
data("df_het")
head(df_het)
```
--------------------------------
### Visualize Example Data for did2s in R
Source: https://github.com/kylebutts/did2s/blob/main/docs/index.html
Loads example data from the did2s package and plots the average outcome variable across different groups and years. This helps visualize the data-generating process for difference-in-differences analysis.
```r
library(did2s)
# Load Data from R package
data("df_het", package = "did2s")
# Mean for treatment group-year
agg <- aggregate(df_het$dep_var, by=list(g = df_het$g, year = df_het$year), FUN = mean)
agg$g <- as.character(agg$g)
agg$g <- ifelse(agg$g == "0", "Never Treated", agg$g)
never <- agg[agg$g == "Never Treated", ]
g1 <- agg[agg$g == "2000", ]
g2 <- agg[agg$g == "2010", ]
plot(0, 0, xlim = c(1990,2020), ylim = c(4,7.2), type = "n",
main = "Data-generating Process", ylab = "Outcome", xlab = "Year")
abline(v = c(1999.5, 2009.5), lty = 2)
lines(never$year, never$x, col = "#8e549f", type = "b", pch = 15)
lines(g1$year, g1$x, col = "#497eb3", type = "b", pch = 17)
lines(g2$year, g2$x, col = "#d2382c", type = "b", pch = 16)
legend(x=1990, y=7.1, col = c("#8e549f", "#497eb3", "#d2382c"),
pch = c(15, 17, 16),
legend = c("Never Treated", "2000", "2010"))
```
--------------------------------
### Example: Estimating and Plotting Event Study (R)
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/plot_event_study.html
This R code snippet demonstrates a typical workflow: first, it estimates an event study using the event_study function with specified data and variable names, and then it plots the results using plot_event_study. It includes example data loading.
```r
data(df_het, package = "did2s")
out = event_study(
data = df_het, yname = "dep_var", idname = "unit",
tname = "year", gname = "g"
)
plot_event_study(out)
```
--------------------------------
### Load and visualize example data
Source: https://github.com/kylebutts/did2s/blob/main/README.md
Loads the heterogeneous treatment effect dataset provided by the package and generates a plot comparing average outcomes across different treatment groups over time.
```R
library(did2s)
data("df_het", package = "did2s")
df_het = as.data.frame(df_het)
agg <- aggregate(df_het$dep_var, by = list(g = df_het$g, year = df_het$year), FUN = mean)
agg$g <- as.character(agg$g)
agg$g <- ifelse(agg$g == "0", "Never Treated", agg$g)
never <- agg[agg$g == "Never Treated", ]
g1 <- agg[agg$g == "2000", ]
g2 <- agg[agg$g == "2010", ]
plot(0, 0, xlim = c(1990, 2020), ylim = c(3.5, 7.2), type = "n", main = "Data-generating Process", ylab = "Outcome", xlab = "Year")
abline(v = c(1999.5, 2009.5), lty = 2)
lines(never$year, never$x, col = "#8e549f", type = "b", pch = 15)
lines(g1$year, g1$x, col = "#497eb3", type = "b", pch = 17)
lines(g2$year, g2$x, col = "#d2382c", type = "b", pch = 16)
legend(x = 1990, y = 7.1, col = c("#8e549f", "#497eb3", "#d2382c"), pch = c(15, 17, 16), legend = c("Never Treated", "2000", "2010"))
```
--------------------------------
### Static TWFE with did2s (R)
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did2s.html
Example of using the `did2s` function to run a static Two-Way Fixed Effects (TWFE) model. This specific example uses a simple treatment indicator and specifies fixed effects for unit and year.
```r
static <- did2s(df_hom,
yname = "dep_var", treatment = "treat", cluster_var = "state",
first_stage = ~ 0 | unit + year,
second_stage = ~ i(treat, ref=FALSE))
#> Running Two-stage Difference-in-Differences
#> - first stage formula `~ 0 | unit + year`
#> - second stage formula `~ i(treat, ref = FALSE)`
#> - The indicator variable that denotes when treatment is on is `treat`
#> - Standard errors will be clustered by `state`
fixest::esttable(static)
#> static
#> Dependent Var.: dep_var
#>
#> treat = TRUE 2.005*** (0.0202)
#> _______________ _________________
#> S.E. type Custom
#> Observations 46,500
#> R2 0.47520
#> Adj. R2 0.47520
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
```
--------------------------------
### R: Replicate Cheng and Hoekstra (2013) DID2S Example
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did3s.html
This R code replicates an example from Cheng and Hoekstra (2013) using the did2s package. It loads the 'castle.dta' dataset and applies the did2s function to estimate a difference-in-differences model. The function is configured with the dataset, dependent variable, first and second stage formulas, treatment indicator, clustering variable, and weights.
```r
# Castle Data
c_data <- haven::read_dta("https://github.com/scunning1975/mixtape/raw/master/castle.dta")
did2s(
data = c_data,
yname = "l_homicide",
first_stage = ~ 0 | sid + year,
second_stage = ~ i(post, ref=0),
treatment = "post",
cluster_var = "state", weights = "popwt"
)
#> Running Two-stage Difference-in-Differences
#> • first stage formula `~ 0 | sid + year`
#> • second stage formula `~ i(post, ref = 0)`
#> • The indicator variable that denotes when treatment is on is `post`
#> • Standard errors will be clustered by `state`
#> OLS estimation, Dep. Var.: l_homicide
#> Observations: 550
#> Standard-errors: Custom
#> Estimate Std. Error t value Pr(>|t|)
#> post::1 0.075142 0.03538 2.12387 0.034127 *
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> RMSE: 263.4 Adj. R2: 0.052465
```
--------------------------------
### Get Package Citation (R)
Source: https://github.com/kylebutts/did2s/blob/main/docs/index.html
This R code retrieves the citation information for the 'did2s' package. It provides instructions on how to cite the package in publications, including a standard text citation and a BibTeX entry for LaTeX users. This is essential for academic and research use.
```r
citation(package = "did2s")
#>
#> To cite did2s in publications use:
#>
#> Butts, Kyle (2021). did2s: Two-Stage Difference-in-Differences
#> Following Gardner (2021). R package version 1.0.2.
#>
#> A BibTeX entry for LaTeX users is
#>
#> @Manual{,
#> title = {did2s: Two-Stage Difference-in-Differences Following Gardner (2021)},
#> author = {Kyle Butts},
#> year = {2021},
#> url = {https://github.com/kylebutts/did2s/},
#> }
```
--------------------------------
### Get Citation for did2s Package in R
Source: https://github.com/kylebutts/did2s/blob/main/README.md
This code retrieves the citation information for the 'did2s' R package. It provides instructions for citing the package in publications, including a BibTeX entry for LaTeX users.
```r
citation(package = "did2s")
```
--------------------------------
### Generate Simulated Data with Heterogeneous Effects — df_het
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/df_het.html
This code snippet demonstrates how to generate simulated panel data with two treatment groups and heterogeneous treatment effects using the `gen_data` function from the `did2s` package. It specifies the panel duration, treatment start years for two groups, and different treatment effect parameters.
```r
did2s::gen_data(panel = c(1990, 2020), g1 = 2000, g2 = 2010, g3 = 0, te1 = 2, te2 = 1, te3 = 0, te_m1 = 0.05, te_m2 = 0.15, te_m3 = 0)
```
--------------------------------
### Generate TWFE Data with R
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/gen_data.html
Generates synthetic panel data for TWFE analysis. Users can control treatment group assignment dates (g1, g2, g3), panel start and end years, static treatment effects (te1, te2, te3), dynamic treatment effect slopes (te_m1, te_m2, te_m3), and the number of individuals (n). Returns a dataframe.
```r
gen_data(
g1 = 2000,
g2 = 2010,
g3 = 0,
panel = c(1990, 2020),
te1 = 2,
te2 = 2,
te3 = 2,
te_m1 = 0,
te_m2 = 0,
te_m3 = 0,
n = 1500
)
```
```r
# Homogeneous treatment effect
df_hom <- gen_data(panel = c(1990, 2020),
g1 = 2000, g2 = 2010, g3 = 0,
te1 = 2, te2 = 2, te3 = 0,
te_m1 = 0, te_m2 = 0, te_m3 = 0)
# Heterogeneous treatment effect
df_het <- gen_data(panel = c(1990, 2020),
g1 = 2000, g2 = 2010, g3 = 0,
te1 = 2, te2 = 1, te3 = 0,
te_m1 = 0.05, te_m2 = 0.15, te_m3 = 0)
```
--------------------------------
### Visualize Event Study Comparison using fixest
Source: https://github.com/kylebutts/did2s/blob/main/docs/articles/Two-Stage-Difference-in-Differences.html
This snippet demonstrates how to estimate a TWFE model using fixest::feols and visualize the comparison between two-stage estimates and TWFE results using fixest::iplot. It requires the fixest package and a pre-existing dataset.
```R
twfe = feols(dep_var ~ i(rel_year, ref=c(-1, Inf)) | unit + year, data = df_het)
fixest::iplot(list(es, twfe), sep = 0.2, ref.line = -0.5,
col = c("steelblue", "#82b446"), pt.pch = c(20, 18),
xlab = "Relative time to treatment",
main = "Event study: Staggered treatment (comparison)")
# Legend
legend(x=-20, y=3, col = c("steelblue", "#82b446"), pch = c(20, 18),
legend = c("Two-stage estimate", "TWFE"))
```
--------------------------------
### Run Static TWFE Model with did2s
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did3s.html
Demonstrates how to execute a static Two-Way Fixed Effects (TWFE) model using the did2s function. The output is a fixest object compatible with standard fixest reporting tools.
```R
data("df_hom")
static <- did2s(df_hom,
yname = "dep_var", treatment = "treat", cluster_var = "state",
first_stage = ~ 0 | unit + year,
second_stage = ~ i(treat, ref=FALSE))
fixest::esttable(static)
```
--------------------------------
### Perform Relative Magnitude Sensitivity Analysis in R
Source: https://github.com/kylebutts/did2s/blob/main/README.md
This snippet demonstrates how to perform a relative magnitude sensitivity analysis using the `es_did2s` object. It converts the `fixest` object for `honest_did_did2s` and then runs the sensitivity analysis with specified parameters. A warning is issued if the confidence interval is open at one or both endpoints.
```r
sensitivity_results <- es_did2s |>
get_honestdid_obj_did2s(coef_name = "rel_year") |>
honest_did_did2s(
e = 0,
type = "relative_magnitude",
Mbarvec = seq(from = 0.5, to = 2, by = 0.5)
)
```
--------------------------------
### Perform Sensitivity Analysis with HonestDiD
Source: https://github.com/kylebutts/did2s/blob/main/README.md
Integrates did2s with the HonestDiD package to perform sensitivity analysis on treatment effect estimates, demonstrated using Medicaid expansion data.
```R
library(HonestDiD)
# Estimate did2s for HonestDiD
es_did2s <- did2s(
df,
yname = "dins",
first_stage = ~ 0 | stfips + year,
second_stage = ~ 0 + i(rel_year, ref = -100),
treatment = "treated",
cluster_var = "stfips"
)
# Plot estimates
iplot(es_did2s, drop = "-100")
```
--------------------------------
### Implement CSS Fallback for Color Schemes
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/pipe.html
This JavaScript snippet detects if the browser supports the prefers-color-scheme media query. If unsupported, it injects a light-mode CSS stylesheet to ensure the page renders correctly.
```JavaScript
if (window.matchMedia("(prefers-color-scheme: dark)").media === "not all") {
document.documentElement.style.display = "none";
document.head.insertAdjacentHTML(
"beforeend",
""
);
}
```
--------------------------------
### Generate Simulated Panel Data with did2s
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/df_hom.html
This code snippet demonstrates how to generate the df_hom dataset using the did2s::gen_data function. It specifies the panel time range, treatment group timing, and treatment effect parameters.
```R
did2s::gen_data(panel = c(1990, 2020), g1 = 2000, g2 = 2010, g3 = 0, te1 = 2, te2 = 2, te3 = 0, te_m1 = 0, te_m2 = 0, te_m3 = 0)
```
--------------------------------
### Estimate Event Study with did2s
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did2s.html
Demonstrates how to estimate an event study model using relative-treatment indicators. It uses the did2s function with a two-stage formula and visualizes the results using fixest::coefplot.
```R
es <- did2s(df_hom,
yname = "dep_var", treatment = "treat", cluster_var = "state",
first_stage = ~ 0 | unit + year,
second_stage = ~ i(rel_year, ref=c(-1, Inf)))
fixest::esttable(es)
# plot rel_year coefficients and standard errors
fixest::coefplot(es, keep = "rel_year::(.*)")
```
--------------------------------
### Visualize heterogeneous treatment effects
Source: https://github.com/kylebutts/did2s/blob/main/docs/articles/Two-Stage-Difference-in-Differences.html
Aggregates the outcome variable by treatment group and year, then generates a plot to compare trends between never-treated units and those treated in 2000 or 2010.
```R
# Mean for treatment group-year
agg <- aggregate(df_het$dep_var, by=list(g = df_het$g, year = df_het$year), FUN = mean)
agg$g <- as.character(agg$g)
agg$g <- ifelse(agg$g == "0", "Never Treated", agg$g)
never <- agg[agg$g == "Never Treated", ]
g1 <- agg[agg$g == "2000", ]
g2 <- agg[agg$g == "2010", ]
plot(0, 0, xlim = c(1990,2020), ylim = c(4,7.2), type = "n",
main = "Data-generating Process", ylab = "Outcome", xlab = "Year")
abline(v = c(1999.5, 2009.5), lty = 2)
lines(never$year, never$x, col = "#8e549f", type = "b", pch = 15)
lines(g1$year, g1$x, col = "#497eb3", type = "b", pch = 17)
lines(g2$year, g2$x, col = "#d2382c", type = "b", pch = 16)
legend(x=1990, y=7.1, col = c("#8e549f", "#497eb3", "#d2382c"),
pch = c(15, 17, 16),
legend = c("Never Treated", "2000", "2010"))
```
--------------------------------
### Create Sensitivity Analysis Plot in R
Source: https://github.com/kylebutts/did2s/blob/main/README.md
This code generates a plot visualizing the results of the relative magnitude sensitivity analysis. It takes the robust and original confidence intervals from the sensitivity analysis results as input.
```r
HonestDiD::createSensitivityPlot_relativeMagnitudes(
sensitivity_results$robust_ci,
sensitivity_results$orig_ci
)
```
--------------------------------
### Visualize and Compare DID Estimates
Source: https://github.com/kylebutts/did2s/blob/main/README.md
Uses fixest::iplot to visualize event-study coefficients and compare two-stage estimates against traditional Two-Way Fixed Effects (TWFE) models.
```R
# Plot event study results
fixest::iplot(es, main = "Event study: Staggered treatment", xlab = "Relative time to treatment", col = "steelblue", ref.line = -0.5, drop = "Inf")
# Compare with TWFE
twfe <- feols(dep_var ~ i(rel_year, ref = c(Inf, -1)) | unit + year, data = df_het)
fixest::iplot(
list(es, twfe),
sep = 0.2, ref.line = -0.5,
col = c("steelblue", "#82b446"), pt.pch = c(20, 18),
xlab = "Relative time to treatment",
main = "Event study: Staggered treatment (comparison)",
drop = "Inf"
)
```
--------------------------------
### Estimate Static and Event-Study DID Models
Source: https://github.com/kylebutts/did2s/blob/main/README.md
Demonstrates how to use the did2s function to estimate static treatment effects and event-study coefficients. The event-study approach uses relative time indicators to capture dynamic effects.
```R
# Static Estimation
static <- did2s(
df_het,
yname = "dep_var", first_stage = ~ 0 | state + year,
second_stage = ~ i(treat, ref = FALSE), treatment = "treat",
cluster_var = "state"
)
# Event Study Estimation
es <- did2s(df_het,
yname = "dep_var", first_stage = ~ 0 | state + year,
second_stage = ~ i(rel_year, ref = Inf), treatment = "treat",
cluster_var = "state"
)
```
--------------------------------
### Implement Staggered Adoption Treatment Effect Estimation with did_impute
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did_impute.html
The did_impute function estimates treatment effects in staggered adoption designs. It requires a data frame, outcome variable, treatment timing, time period, and unit identifier, along with a first-stage formula for the untreated potential outcome.
```R
did_impute(
data,
yname,
gname,
tname,
idname,
first_stage,
weights = NULL,
wtr = NULL,
horizon = NULL
)
```
--------------------------------
### Estimate and Plot Event-Study Coefficients using did2s
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/event_study.html
This snippet demonstrates how to use the event_study function to estimate treatment effects across multiple estimators and visualize the results using plot_event_study. It requires a dataframe with outcome, unit, time, and treatment group variables.
```R
# Estimate event-study coefficients using all available estimators
out = event_study(
data = did2s::df_het,
yname = "dep_var",
idname = "unit",
tname = "year",
gname = "g",
estimator = "all"
)
# Visualize the estimated coefficients
plot_event_study(out)
```
--------------------------------
### Conditional CSS Injection for Color Scheme Fallback (JavaScript)
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/plot_event_study.html
This JavaScript code checks if the 'prefers-color-scheme' media query is supported. If not, it injects a light mode CSS stylesheet with the highest priority to ensure a fallback display. It temporarily hides the document element until the CSS is loaded.
```javascript
if (window.matchMedia("(prefers-color-scheme: dark)").media === "not all") { document.documentElement.style.display = "none"; document.head.insertAdjacentHTML( "beforeend", ""); }
```
--------------------------------
### Perform Two-Stage Difference-in-Differences Estimation
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did2s.html
Shows how to apply the did2s function to a dataset, specifically using the Cheng and Hoekstra (2013) castle data. It includes specifying the dependent variable, treatment indicator, clustering, and weights.
```R
# Castle Data
castle <- haven::read_dta("https://github.com/scunning1975/mixtape/raw/master/castle.dta")
did2s(
data = castle,
yname = "l_homicide",
first_stage = ~ 0 | sid + year,
second_stage = ~ i(post, ref=0),
treatment = "post",
cluster_var = "state", weights = "popwt"
)
```
--------------------------------
### Plot Event Study Results (R)
Source: https://github.com/kylebutts/did2s/blob/main/docs/articles/Two-Stage-Difference-in-Differences.html
Visualizes the results of an event study Difference-in-Differences estimation using `fixest::iplot`. This function plots the estimated treatment effects over time relative to the treatment event, allowing for comparison with the true effects by adding points from simulated data.
```r
fixest::iplot(es, main = "Event study: Staggered treatment", xlab = "Relative time to treatment", col = "steelblue", ref.line = -0.5)
true_effects = head(tapply((df_het$te + df_het$te_dynamic), df_het$rel_year, mean), -1)
points(-20:20, true_effects, pch = 20, col = "black")
legend(x=-20, y=3, col = c("steelblue", "black"), pch = c(20, 20),
legend = c("Two-stage estimate", "True effect"))
```
--------------------------------
### Plot Event Study Results with did2s
Source: https://github.com/kylebutts/did2s/blob/main/docs/articles/event_study.html
This code snippet shows how to visualize the event study results obtained from the `event_study` function using the `plot_event_study` function. It takes the output tibble from `event_study` and a specified horizon for plotting, allowing for easy comparison of different estimators' effects over time.
```r
plot_event_study(out, horizon = c(-5,10))
```
--------------------------------
### Estimate Event Study Two-stage Difference-in-Differences (R)
Source: https://github.com/kylebutts/did2s/blob/main/docs/articles/Two-Stage-Difference-in-Differences.html
Estimates an event study Two-stage Difference-in-Differences model. This function allows for the analysis of treatment effects over time relative to the treatment event. The `ref` argument in `i()` is used to set the reference group for relative years, handling cases like never-treated individuals.
```r
es <- did2s(df_het,
yname = "dep_var", first_stage = ~ 0 | state + year,
second_stage = ~i(rel_year, ref=c(-1, Inf)), treatment = "treat",
cluster_var = "state")
```
--------------------------------
### Estimate Event Study with Multiple Estimators in did2s
Source: https://github.com/kylebutts/did2s/blob/main/docs/articles/event_study.html
This code snippet demonstrates how to use the `event_study` function from the `did2s` package to estimate event study effects using multiple estimators. It takes a dataframe, specifies the dependent variable, unit identifier, time period, and treatment group, and requests all available estimators. The output is a tidy tibble containing estimates and standard errors for each estimator and relative time period.
```r
library(did2s)
#> Loading required package: fixest
#> did2s (v1.0.0). For more information on the methodology, visit
#>
#> To cite did2s in publications use:
#>
#> Butts, Kyle (2021). did2s: Two-Stage Difference-in-Differences
#> Following Gardner (2021). R package version 1.0.0.
#>
#> A BibTeX entry for LaTeX users is
#>
#> @Manual{
#> title = {did2s: Two-Stage Difference-in-Differences Following Gardner (2021)},
#> author = {Kyle Butts},
#> year = {2021},
#> url = {https://github.com/kylebutts/did2s/},
#> }
data(df_het, package = "did2s")
out = event_study(
data = df_het, yname = "dep_var", idname = "unit",
tname = "year", gname = "g", estimator = "all"
)
#> Note these estimators rely on different underlying assumptions. See Table 2 of `https://arxiv.org/abs/2109.05913` for an overview.
#> Estimating TWFE Model
#> Estimating using Gardner (2021)
#> Estimating using Callaway and Sant'Anna (2020)
#> Estimating using Sun and Abraham (2020)
#> Estimating using Borusyak, Jaravel, Spiess (2021)
#> Estimating using Roth and Sant'Anna (2021)
head(out)
#> estimator term estimate std.error
#>
#> 1: TWFE -20 0.04097725 0.07167704
#> 2: TWFE -19 0.13665695 0.07147683
#> 3: TWFE -18 0.14015820 0.07245520
#> 4: TWFE -17 0.15793252 0.07431871
#> 5: TWFE -16 0.09910002 0.07379570
#> 6: TWFE -15 0.20561127 0.07116478
```
--------------------------------
### Generate Event-Study Plot with Multiple Estimators in R
Source: https://github.com/kylebutts/did2s/blob/main/README.md
This snippet shows how to generate an event-study plot using data from `df_het`. It first prepares the data by handling infinite values in the 'g' column and then estimates the event study using multiple estimators. The `did2s::plot_event_study` function is then used to visualize the results.
```r
library(tidyverse)
data(df_het)
df = df_het
multiple_ests = did2s::event_study(
data = df |> mutate(g = ifelse(g == Inf, NA, g)) |> as.data.frame(),
gname = "g",
idname = "unit",
tname = "year",
yname = "dep_var",
estimator = "all"
)
did2s::plot_event_study(multiple_ests)
```
--------------------------------
### Estimate Event-Study TWFE Model with did2s
Source: https://github.com/kylebutts/did2s/blob/main/docs/articles/event_study.html
The `event_study` function estimates the event-study TWFE model using robust estimators. It requires a data frame, outcome variable name, unit identifier name, time period name, and group name indicating the first treatment period. Optional arguments include a formula, horizon, and weights.
```r
event_study(
data,
yname,
idname,
tname,
gname,
estimator,
xformla = NULL,
horizon = NULL,
weights = NULL
)
```
--------------------------------
### Estimate Static Difference-in-Differences with did2s
Source: https://github.com/kylebutts/did2s/blob/main/docs/index.html
Performs a static two-stage DiD estimation using the did2s function. It utilizes fixest-style formulas for fixed effects and treatment indicators, returning a fixest object compatible with etable.
```R
static <- did2s(df_het,
yname = "dep_var", first_stage = ~ 0 | state + year,
second_stage = ~i(treat, ref=FALSE), treatment = "treat",
cluster_var = "state")
fixest::etable(static)
```
--------------------------------
### Estimate Static Two-stage Difference-in-Differences (R)
Source: https://github.com/kylebutts/did2s/blob/main/docs/articles/Two-Stage-Difference-in-Differences.html
Estimates a static Two-stage Difference-in-Differences model using the `did2s` function. It utilizes `fixest::feols` for specifying fixed effects and `fixest::i` for factor variables. The function returns a `fixest` object, allowing for direct use with `fixest::esttable` for summary statistics.
```r
static <- did2s(df_het,
yname = "dep_var", first_stage = ~ 0 | state + year,
second_stage = ~i(treat, ref=FALSE), treatment = "treat",
cluster_var = "state")
fixest::esttable(static)
```
--------------------------------
### Estimate and Plot Event Study with TWFE Comparison (R)
Source: https://github.com/kylebutts/did2s/blob/main/docs/index.html
This code snippet estimates an event study model using `feols` and compares it to a Two-Stage Difference-in-Differences estimate. It then generates a plot visualizing the event study results, highlighting the differences between the two estimation methods. Dependencies include the `fixest` package.
```r
twfe = feols(dep_var ~ i(rel_year, ref=c(-1, Inf)) | unit + year, data = df_het)
fixest::iplot(list(es, twfe), sep = 0.2, ref.line = -0.5,
col = c("steelblue", "#82b446"), pt.pch = c(20, 18),
xlab = "Relative time to treatment",
main = "Event study: Staggered treatment (comparison)")
# Legend
legend(x=-20, y=3, col = c("steelblue", "#82b446"), pch = c(20, 18),
legend = c("Two-stage estimate", "TWFE"))
```
--------------------------------
### did2s Function
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did3s.html
Executes the two-stage difference-in-differences procedure for static or event-study models.
```APIDOC
## FUNCTION did2s
### Description
Runs a two-stage difference-in-differences estimation. The first stage estimates fixed effects, and the second stage estimates the treatment effect.
### Request Example
```r
static <- did2s(df_hom,
yname = "dep_var", treatment = "treat", cluster_var = "state",
first_stage = ~ 0 | unit + year,
second_stage = ~ i(treat, ref=FALSE))
```
### Response
- **fixest object** - A model object containing the estimation results, which can be passed to `fixest::esttable` or `fixest::coefplot`.
```
--------------------------------
### Estimate and Plot Event Study with did2s
Source: https://github.com/kylebutts/did2s/blob/main/docs/index.html
Estimates an event study model using relative time indicators and visualizes the results using fixest::iplot. It handles reference levels for never-treated units and allows for overlaying true effect benchmarks.
```R
es <- did2s(df_het,
yname = "dep_var", first_stage = ~ 0 | state + year,
second_stage = ~i(rel_year, ref=c(-1, Inf)), treatment = "treat",
cluster_var = "state")
fixest::iplot(es, main = "Event study: Staggered treatment", xlab = "Relative time to treatment", col = "steelblue", ref.line = -0.5)
true_effects = head(tapply((df_het$te + df_het$te_dynamic), df_het$rel_year, mean), -1)
points(-20:20, true_effects, pch = 20, col = "black")
legend(x=-20, y=3, col = c("steelblue", "black"), pch = c(20, 20),
legend = c("Two-stage estimate", "True effect"))
```
--------------------------------
### Inject Light Mode CSS if Dark Mode Not Supported (JavaScript)
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/theme_kyle.html
This JavaScript snippet checks for browser support of the `prefers-color-scheme` media query. If dark mode is not supported, it injects a link to a light mode stylesheet into the document's head and hides the document element until the stylesheet is loaded.
```javascript
if (window.matchMedia("(prefers-color-scheme: dark)").media === "not all") {
document.documentElement.style.display = "none";
document.head.insertAdjacentHTML("beforeend", "");
}
```
--------------------------------
### Calculate Two-Stage Difference-in-Differences (R)
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did2s.html
The `did2s` function calculates two-stage difference-in-differences. It requires a dataframe, outcome variable name, first-stage formula, second-stage formula, treatment indicator, and clustering variable. Optional arguments include weights, bootstrapping, and verbosity.
```r
did2s(
data,
yname,
first_stage,
second_stage,
treatment,
cluster_var,
weights = NULL,
bootstrap = FALSE,
n_bootstraps = 250,
return_bootstrap = FALSE,
verbose = TRUE
)
```
--------------------------------
### Implement Borusyak et al. (2021) Imputation Estimator in R
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did_imputation.html
The did_imputation function estimates treatment effects in staggered adoption designs. It requires a data frame and variable names for the outcome, treatment group, time, and unit ID, with optional parameters for first-stage formulas and event-study horizons.
```R
library(did2s)
# Static TWFE model
did_imputation(data = df_hom, yname = "dep_var", gname = "g", tname = "year", idname = "unit")
# Event study estimate
did_imputation(data = df_hom, yname = "dep_var", gname = "g", tname = "year", idname = "unit", horizon = TRUE)
# Model with custom first stage fixed effects
did_imputation(data = castle, yname = "l_homicide", gname = "effyear", first_stage = ~ 0 | sid + year, tname = "year", idname = "sid")
```
--------------------------------
### Use Pipe Operator in R
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/pipe.html
The pipe operator allows for chaining operations by passing the left-hand side value as the first argument to the right-hand side function. It follows standard magrittr semantics for clean, readable code pipelines.
```R
lhs %>% rhs
```
--------------------------------
### Calculate Two-Stage Difference-in-Differences with did3s
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did3s.html
The did3s function performs the two-stage estimation procedure. It requires a dataframe, outcome variable, group and time identifiers, and formulas for the second stage and treatment indicators.
```R
did3s(
data,
yname,
gname,
tname,
time_varying,
third_stage,
treatment,
cluster_var,
time_invariant = c("1"),
weights = NULL,
n_bootstraps = 250,
return_bootstrap = FALSE,
verbose = TRUE
)
```
--------------------------------
### R: Estimate Event Study with Relative Treatment Indicators
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did3s.html
This R code estimates an event study using the did2s function with relative treatment indicators. It specifies the dependent variable, treatment indicator, clustering variable, and formulas for the first and second stages of the regression. The output is then presented using esttable and visualized with coefplot.
```r
es <- did2s(df_hom,
yname = "dep_var", treatment = "treat", cluster_var = "state",
first_stage = ~ 0 | unit + unit + year,
second_stage = ~ i(rel_year, ref=c(-1, Inf)))
#> Running Two-stage Difference-in-Differences
#> • first stage formula `~ 0 | unit + year`
#> • second stage formula `~ i(rel_year, ref = c(-1, Inf))`
#> • The indicator variable that denotes when treatment is on is `treat`
#> • Standard errors will be clustered by `state`
fixest::esttable(es)
#> es
#> Dependent Var.: dep_var
#>
#> rel_year = -20 0.0398 (0.0463)
#> rel_year = -19 0.0761 (0.0471)
#> rel_year = -18 0.0065 (0.0437)
#> rel_year = -17 0.0811* (0.0408)
#> rel_year = -16 -0.0039 (0.0506)
#> rel_year = -15 -0.0178 (0.0403)
#> rel_year = -14 0.0154 (0.0488)
#> rel_year = -13 -0.0211 (0.0480)
#> rel_year = -12 -0.0394 (0.0497)
#> rel_year = -11 0.0052 (0.0390)
#> rel_year = -10 0.0010 (0.0245)
#> rel_year = -9 -0.0371 (0.0288)
#> rel_year = -8 -0.0133 (0.0242)
#> rel_year = -7 -0.0808*** (0.0230)
#> rel_year = -6 -0.0076 (0.0305)
#> rel_year = -5 0.0361 (0.0242)
#> rel_year = -4 0.0199 (0.0261)
#> rel_year = -3 0.0164 (0.0285)
#> rel_year = -2 -0.0412 (0.0321)
#> rel_year = 0 1.955*** (0.0526)
#> rel_year = 1 1.923*** (0.0515)
#> rel_year = 2 1.900*** (0.0530)
#> rel_year = 3 2.002*** (0.0556)
#> rel_year = 4 2.052*** (0.0541)
#> rel_year = 5 1.942*** (0.0565)
#> rel_year = 6 1.922*** (0.0504)
#> rel_year = 7 1.959*** (0.0598)
#> rel_year = 8 1.960*** (0.0554)
#> rel_year = 9 1.919*** (0.0500)
#> rel_year = 10 1.945*** (0.0496)
#> rel_year = 11 1.945*** (0.0720)
#> rel_year = 12 1.897*** (0.0800)
#> rel_year = 13 1.940*** (0.0803)
#> rel_year = 14 1.995*** (0.0811)
#> rel_year = 15 1.989*** (0.0801)
#> rel_year = 16 1.986*** (0.0820)
#> rel_year = 17 1.911*** (0.0817)
#> rel_year = 18 1.986*** (0.0819)
#> rel_year = 19 1.896*** (0.0650)
#> rel_year = 20 1.865*** (0.0750)
#> _______________ ___________________
#> S.E. type Custom
#> Observations 31,000
#> R2 0.46359
#> Adj. R2 0.46291
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# plot rel_year coefficients and standard errors
fixest::coefplot(es, keep = "rel_year::(.*)")
```
--------------------------------
### did3s Function
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/did3s.html
Calculates the two-stage difference-in-differences estimator as proposed by Gardner (2021).
```APIDOC
## FUNCTION did3s
### Description
Calculates two-stage difference-in-differences following Gardner (2021). This function is designed for complex treatment effect estimation.
### Parameters
- **data** (dataframe) - Required - The dataframe containing all variables.
- **yname** (string) - Required - Variable name for outcome variable.
- **gname** (string) - Required - Variable name for group variable.
- **tname** (string) - Required - Variable name for treatment variable.
- **time_varying** (vector) - Optional - Variable names of time-varying covariates.
- **third_stage** (formula) - Required - Second stage treatment indicators (e.g., event-study leads/lags).
- **treatment** (string) - Required - Variable that = 1 if treated, = 0 otherwise.
- **cluster_var** (string) - Required - Variable to cluster standard errors.
- **n_bootstraps** (integer) - Optional - Number of bootstraps to run (Default: 250).
### Response
- **fixest object** - Returns a fixest object with adjusted standard errors compatible with fixest methods.
```
--------------------------------
### Define theme_kyle ggplot Theme Function (R)
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/theme_kyle.html
This R code defines the `theme_kyle` function for custom ggplot themes. It accepts arguments for title position, axis title position, slide mode, subtitle presence, and base font size.
```r
theme_kyle(
title_pos = "center",
axis_title_pos = "left",
slides = FALSE,
has_subtitle = FALSE,
base_size = 14,
...
)
```
--------------------------------
### Plot Event Study Results (R)
Source: https://github.com/kylebutts/did2s/blob/main/docs/reference/plot_event_study.html
This R function, plot_event_study, visualizes the output from the event_study function. It takes the results tibble and optional arguments for separating plots and specifying the plotting horizon. The function returns a ggplot object.
```r
plot_event_study(out, seperate = TRUE, horizon = NULL)
```