# Event-study difference-in-differences
# https://tidyecology.com/posts/difference-in-differences-event-study/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-05-26

## ---- setup ----
library(ggplot2); library(dplyr); library(tidyr)
set.seed(404)
N <- 40; Tn <- 12; T0 <- 7; treated_ids <- 1:20
Kset <- setdiff((1 - T0):(Tn - T0), -1)            # event times, reference k = -1
tau_true <- c(`0` = 0.30, `1` = 0.60, `2` = 0.90, `3` = 1.10, `4` = 1.20, `5` = 1.30)
alph <- rnorm(N, 0, 0.8)                            # site fixed effects
gam  <- cumsum(c(0, rnorm(Tn - 1, 0.05, 0.15)))    # common year trend (parallel)
sig  <- 0.40

make_panel <- function(pretrend = 0) {
  d <- expand.grid(id = 1:N, year = 1:Tn)
  d$treated <- as.integer(d$id %in% treated_ids)
  eff <- ifelse(d$treated == 1 & d$year >= T0, tau_true[as.character(pmin(d$year - T0, 5))], 0)
  eff[is.na(eff)] <- 0
  ptr <- ifelse(d$treated == 1, pretrend * (d$year - T0), 0)   # optional differential trend
  d$y <- alph[d$id] + gam[d$year] + eff + ptr + rnorm(nrow(d), 0, sig)
  d
}
dc <- make_panel(0)

## ---- estimators ----
event_study <- function(d) {
  X <- sapply(Kset, function(k) as.integer(d$treated == 1 & (d$year - T0) == k))
  colnames(X) <- paste0("k", ifelse(Kset < 0, paste0("m", abs(Kset)), Kset))
  df <- cbind(d, as.data.frame(X)); lag <- colnames(X)[Kset >= 0]
  m  <- lm(as.formula(paste("y ~ factor(id) + factor(year) +", paste(colnames(X), collapse = " + "))), df)
  m0 <- lm(as.formula(paste("y ~ factor(id) + factor(year) +", paste(lag, collapse = " + "))), df)
  pt <- anova(m0, m); co <- summary(m)$coefficients
  est <- data.frame(k = Kset, b = co[colnames(X), 1], se = co[colnames(X), 2])
  est$lo <- est$b - 1.96 * est$se; est$hi <- est$b + 1.96 * est$se
  list(est = est, F = pt$F[2], p = pt$`Pr(>F)`[2], df1 = pt$Df[2], df2 = pt$Res.Df[2])
}
static_did <- function(d) {
  d$post <- as.integer(d$year >= T0)
  co <- summary(lm(y ~ factor(id) + factor(year) + post:treated, d))$coefficients["post:treated", ]
  c(b = unname(co[1]), se = unname(co[2]), lo = unname(co[1] - 1.96 * co[2]), hi = unname(co[1] + 1.96 * co[2]))
}
ec <- event_study(dc); sc <- static_did(dc); avg <- mean(tau_true)
postc <- ec$est[ec$est$k >= 0, ]; postc$true <- tau_true[as.character(postc$k)]
cover <- mean(with(postc, true >= lo & true <= hi))

## ---- fig-estimates ----
te <- list(ink="#16241d",body="#2c3a31",forest="#275139",label="#46604a",sage="#93a87f",
           paper="#f5f4ee",line="#dad9ca",faint="#5d6b61",grazed="#cda23f",mown="#2f8f63",aband="#b5534e")
ec$est$grp <- ifelse(ec$est$k < 0, "pre", "post")
truthdf <- data.frame(k = as.integer(names(tau_true)), true = as.numeric(tau_true))
ggplot(ec$est, aes(k, b)) +
  annotate("rect", xmin = -0.5, xmax = 5.5, ymin = -Inf, ymax = Inf, fill = te$sage, alpha = 0.12) +
  geom_hline(yintercept = 0, colour = te$faint, linewidth = 0.4) +
  geom_vline(xintercept = -0.5, colour = te$aband, linetype = "22", linewidth = 0.5) +
  geom_segment(data = data.frame(x = -0.5, xe = 5.5, y = sc[1]), aes(x = x, xend = xe, y = y, yend = y),
               inherit.aes = FALSE, colour = te$grazed, linewidth = 0.9) +
  annotate("text", x = -3.5, y = sc[1] + 0.12, label = sprintf("static DiD = %.2f (one average)", sc[1]),
           colour = te$grazed, size = 3.1, hjust = 0.5) +
  geom_line(data = truthdf, aes(k, true), inherit.aes = FALSE, colour = te$forest, linewidth = 0.7, linetype = "31") +
  geom_point(data = truthdf, aes(k, true), inherit.aes = FALSE, colour = te$forest, size = 1.4) +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.18, colour = te$ink, linewidth = 0.4) +
  geom_point(aes(fill = grp), shape = 21, colour = te$ink, size = 2.4) +
  scale_fill_manual(values = c(pre = te$paper, post = te$mown), guide = "none") +
  scale_x_continuous(breaks = Kset) +
  labs(x = "Event time (years since intervention)", y = "Effect on the index",
       title = "Event-study reveals the dynamic effect the static DiD hides",
       subtitle = "Dashed green: true path. Grey band: post-intervention. Amber line: single static-DiD coefficient.") +
  theme_minimal(base_size = 12) +
  theme(text = element_text(colour = te$body), plot.title = element_text(colour = te$ink, face = "bold"),
        plot.subtitle = element_text(colour = te$faint, size = rel(0.9)), axis.title = element_text(colour = te$label),
        axis.text = element_text(colour = te$faint), panel.grid.minor = element_blank(),
        panel.grid.major = element_line(colour = te$line, linewidth = 0.3),
        plot.background = element_rect(fill = te$paper, colour = NA), panel.background = element_rect(fill = te$paper, colour = NA))

## ---- violation ----
dv <- make_panel(0.10)
ev <- event_study(dv); sv <- static_did(dv)

## ---- fig-pretrends ----
cc <- c("k","b","se","lo","hi")
prc <- ec$est[ec$est$k < 0, cc]; prc$scenario <- "Parallel trends hold"
prv <- ev$est[ev$est$k < 0, cc]; prv$scenario <- "Differential pre-trend"
prb <- rbind(prc, prv)
prb$scenario <- factor(prb$scenario, levels = c("Parallel trends hold", "Differential pre-trend"))
labs2 <- data.frame(scenario = factor(c("Parallel trends hold", "Differential pre-trend"), levels = levels(prb$scenario)),
                    lab = c(sprintf("pre-test p = %.2f", ec$p), sprintf("pre-test p = %.3f", ev$p)), k = -6, b = 1.05)
ggplot(prb, aes(k, b)) +
  geom_hline(yintercept = 0, colour = te$faint, linewidth = 0.4) +
  geom_smooth(method = "lm", se = FALSE, colour = te$aband, linewidth = 0.5, linetype = "22", formula = y ~ x) +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.16, colour = te$ink, linewidth = 0.4) +
  geom_point(colour = te$ink, fill = te$sage, shape = 21, size = 2.3) +
  geom_text(data = labs2, aes(k, b, label = lab), hjust = 0, colour = te$label, size = 3.2) +
  facet_wrap(~scenario) + scale_x_continuous(breaks = (1 - T0):-2) +
  labs(x = "Event time before intervention", y = "Lead coefficient",
       title = "The pre-intervention leads are the parallel-trends check",
       subtitle = "Flat leads on zero are consistent with parallel trends; trending leads flag a violation.") +
  theme_minimal(base_size = 12) +
  theme(text = element_text(colour = te$body), plot.title = element_text(colour = te$ink, face = "bold"),
        plot.subtitle = element_text(colour = te$faint, size = rel(0.9)), axis.title = element_text(colour = te$label),
        axis.text = element_text(colour = te$faint), panel.grid.minor = element_blank(),
        panel.grid.major = element_line(colour = te$line, linewidth = 0.3), strip.text = element_text(colour = te$ink, face = "bold"),
        plot.background = element_rect(fill = te$paper, colour = NA), panel.background = element_rect(fill = te$paper, colour = NA))
