list.files()Practice session: difference-in-differences
Applied Economics Issues, Master 2 DADEE
\[ % Wong palette \definecolor{wongBlack}{RGB}{0,0,0} \definecolor{wongGold}{RGB}{230,159,0} \definecolor{wongLightBlue}{RGB}{86,180,233} \definecolor{wongGreen}{RGB}{0,158,115} \definecolor{wongYellow}{RGB}{240,228,66} \definecolor{wongBlue}{RGB}{0,114,178} \definecolor{wongOrange}{RGB}{213,94,0} \definecolor{wongPurple}{RGB}{204,121,167} \definecolor{gris}{RGB}{148,150,152} % Light tints (= color!17 in xcolor) \definecolor{wongBlackLight}{RGB}{212,212,212} \definecolor{wongGoldLight}{RGB}{251,239,212} \definecolor{wongLightBlueLight}{RGB}{226,242,251} \definecolor{wongGreenLight}{RGB}{212,239,231} \definecolor{wongYellowLight}{RGB}{252,250,223} \definecolor{wongBlueLight}{RGB}{212,231,242} \definecolor{wongOrangeLight}{RGB}{248,228,212} \definecolor{wongPurpleLight}{RGB}{246,232,240} \definecolor{grisLight}{RGB}{237,237,237} % Coloured math \newcommand{\graswongBlackMath}[1]{{\color{wongBlack}#1}} \newcommand{\graswongGoldMath}[1]{{\color{wongGold}#1}} \newcommand{\graswongLightBlueMath}[1]{{\color{wongLightBlue}#1}} \newcommand{\graswongGreenMath}[1]{{\color{wongGreen}#1}} \newcommand{\graswongYellowMath}[1]{{\color{wongYellow}#1}} \newcommand{\graswongBlueMath}[1]{{\color{wongBlue}#1}} \newcommand{\graswongOrangeMath}[1]{{\color{wongOrange}#1}} \newcommand{\graswongPurpleMath}[1]{{\color{wongPurple}#1}} \newcommand{\grasgrisMath}[1]{{\color{gris}#1}} % Coloured math on a light background \newcommand{\highlightwongBlackMath}[1]{\colorbox{wongBlackLight}{$\color{wongBlack}#1$}} \newcommand{\highlightwongGoldMath}[1]{\colorbox{wongGoldLight}{$\color{wongGold}#1$}} \newcommand{\highlightwongLightBlueMath}[1]{\colorbox{wongLightBlueLight}{$\color{wongLightBlue}#1$}} \newcommand{\highlightwongGreenMath}[1]{\colorbox{wongGreenLight}{$\color{wongGreen}#1$}} \newcommand{\highlightwongYellowMath}[1]{\colorbox{wongYellowLight}{$\color{wongYellow}#1$}} \newcommand{\highlightwongBlueMath}[1]{\colorbox{wongBlueLight}{$\color{wongBlue}#1$}} \newcommand{\highlightwongOrangeMath}[1]{\colorbox{wongOrangeLight}{$\color{wongOrange}#1$}} \newcommand{\highlightwongPurpleMath}[1]{\colorbox{wongPurpleLight}{$\color{wongPurple}#1$}} \newcommand{\highlightgrisMath}[1]{\colorbox{grisLight}{$\color{gris}#1$}} \]
This notebook was written by Claude, an AI model made by Anthropic, under the supervision of your teacher, who reviewed and adapted it. Like any teaching document, including one written by a teacher alone, it may contain errors. If something looks wrong or unclear, please tell your teacher.
To test the exercise before class, AI agents played the role of students:
- one agent, with a strong background in econometrics, checked the econometrics, the numbers and the code;
- another agent, with a weaker background, worked through the whole notebook to see where students get stuck. Its feedback was used to write the Key concept boxes, which quickly explain the background you need. Open them when you need them.
The question investigated in this notebook is the following: how do we check, estimate and display a difference-in-differences, and how do we know when not to trust it?
In Parts 1 to 4, we simulate the data ourselves, so we know the true effect of the program for every village and every year. In Part 5, you receive data from five provinces where the same program was implemented, and you do not know the true effect.
In real life, we never know it!
Consider the following setting. From 2010, a government program installs irrigation pumps in some villages. We want to know its effect on rice yields, measured in quintals per hectare (q/ha; 1 quintal = 100 kg). We observe 200 villages every year from 2004 to 2015. Half of them enter the program in 2010 (the treated villages); the other half never do (the control villages).
Open RStudio by double-clicking the project.Rproj file, so that your current working directory is the one that contains this qmd file. You can easily check it: if you run the instruction below, you should see the data/ folder, the did-lab-functions.R script, and the current did-lab-exercise.qmd file.
In this Quarto Markdown Document, fill in the blanks (___) and answer the questions in the text below each block.
You are given a dataset where each row characterizes a village and a year. The list of variables is given in Table 1.
| Variable | Meaning |
|---|---|
village |
village identifier |
year |
year, from 2004 to 2015 |
treated |
1 if the village enters the program in 2010, 0 if it never does |
yield |
rice yield, in q/ha |
yield0_oracle |
the yield the village would have had without the program (in the simulated data only) |
effect_oracle |
the true effect of the program on the village that year (in the simulated data only) |
The last two columns exist only because we simulate the data. As in the practice session of Session 2, they are “oracle” columns (they give the truth): in real data, we never see them.
A panel follows the same units (here, villages) over several periods (here, years). Each row is one village in one year: 200 villages \(\times\) 12 years = 2,400 rows.
With a panel, we can compare each village with itself over time. This removes everything that does not change over time for that village (land quality, distance to the market, etc.), even if we do not observe it.
The content of the document is as follows:
- Simulate the data
- Plot the observations: are the trends parallel?
- Estimate the effect
- Event study: display the coefficients
- DiD detective: five provinces (group work and reports)
- Wrap-up
We will need the following packages (if fixest or broom is missing, run install.packages(c("fixest", "broom")) once):
library(tidyverse)
library(fixest) # regressions with fixed effects
library(broom) # regression results as data frames
library(here)
# Load some useful functions
source(here("did-lab-functions.R"))
group_colours <- c(Control = "#0072B2", Treated = "#E69F00")
truth_colour <- "#D55E00"
theme_set(theme_minimal() + theme(legend.position = "bottom"))fixest in five lines
feols(y ~ x | village + year, data = d) # OLS with village and year fixed effects
feols(..., cluster = ~village) # standard errors clustered by village
i(year, treated, ref = 2009) # one dummy per year, times treated; 2009 omitted
etable(m1, m2, m3) # regression table, models side by side
tidy(m, conf.int = TRUE) # coefficients in a data frame (package broom)1 Simulate the data
1.1 Drawing a Panel of Villages
The function simulate_panel() (in did-lab-functions.R) draws a panel of villages. We fix the seed so that everyone gets the same data.
d <- simulate_panel(seed = 2014)
d# A tibble: 2,400 × 6
village year treated yield yield0_oracle effect_oracle
<int> <int> <dbl> <dbl> <dbl> <dbl>
1 1 2004 1 35.0 35.0 0
2 1 2005 1 38.0 38.0 0
3 1 2006 1 39.1 39.1 0
4 1 2007 1 40.3 40.3 0
5 1 2008 1 35.1 35.1 0
6 1 2009 1 38.2 38.2 0
7 1 2010 1 38.9 37.9 1
8 1 2011 1 42.7 40.7 2
9 1 2012 1 44.9 41.9 3
10 1 2013 1 44.8 41.8 3
# ℹ 2,390 more rows
The yield of village \(i\) in year \(t\), \(Y_{it}\), is generated as \[ Y_{it} = \underbrace{40 - 3\,\text{Treated}_i + a_i}_{\text{village effect}} \;+\; \underbrace{0.5\,(t-2004) + s_t}_{\text{year effect}} \;+\; \highlightwongGoldMath{\tau_{it}} \;+\; e_{it}, \] where all the random terms are drawn independently:
- \(a_i\sim\mathcal N(0,4^2)\): some villages have better land than others;
- \(s_t\sim\mathcal N(0,1)\): good and bad years (e.g., the weather), which affect all villages; in addition, yields grow by 0.5 q/ha per year;
- \(\highlightwongGoldMath{\tau_{it}}\): the effect of the program.
- It is 0 for control villages and before 2010.
- For treated villages, it is 1, 2, 3, 3, 3 and 3 q/ha in 2010, 2011, …, 2015: in the DGP, we assumed that farmers learn to use the pumps.
- \(e_{it}=0.6\,e_{i,t-1}+u_{it}\), with \(u_{it}\sim\mathcal N(0,1.5^2)\): shocks specific to the village, which persist: they last several years (a bad year is often followed by another bad year).
The yield without the program, \(Y_{it}-\tau_{it}\), is stored in yield0_oracle, and \(\highlightwongGoldMath{\tau_{it}}\) in effect_oracle.
In \(e_{it} = 0.6\,e_{i,t-1} + u_{it}\), 60% of last year’s shock is still there this year, 36% the year after, and so on: shocks fade away slowly. A village that had a bad year is likely to have another bad year.
Why it matters: the 12 observations of one village are not independent. They carry less information than 12 different villages would. We come back to this when we choose the standard errors (Q2c).
The data generating function has other options, all switched off for now.
1.2 Average Treatment Effect on the Treated
The average effect of the program on the treated villages over 2010–2015 is the average treatment effect on the treated (ATT).
Write \(Y_{it}(1)\) and \(Y_{it}(0)\) for the potential yields of village \(i\) in year \(t\) with and without the program, so that \(\highlightwongGoldMath{\tau_{it}} = Y_{it}(1) - Y_{it}(0)\). The average treatment effect on the treated over 2010–2015 is \[
\text{ATT} = \mathbb{E}\big[\,Y_{it}(1) - Y_{it}(0) \;\big|\; \text{Treated}_i = 1,\ t \geq 2010\,\big].
\] In our simulated sample, we observe \(\highlightwongGoldMath{\tau_{it}}\) (the column effect_oracle), so we can compute it directly: \[
\text{ATT} = \frac{1}{6\,N_1} \sum_{i:\,\text{Treated}_i = 1} \;\sum_{t=2010}^{2015} \highlightwongGoldMath{\tau_{it}},
\qquad N_1 = \sum_{i} \text{Treated}_i ,
\] which is the mean of effect_oracle over treated villages from 2010. Here \(\highlightwongGoldMath{\tau_{it}}\) does not vary across villages.
Each village has two potential yields each year: \(Y_{it}(1)\) with the program and \(Y_{it}(0)\) without it. We only ever observe one of them: \(Y_{it}(1)\) for treated villages from 2010, \(Y_{it}(0)\) otherwise. So the effect \(\tau_{it} = Y_{it}(1) - Y_{it}(0)\) is never observed in real data.
The ATT is the average of this effect over the villages that were actually treated, in the years they were treated. A difference-in-differences estimates the ATT by using the control villages to guess the missing \(Y_{it}(0)\) of the treated villages.
Compute the ATT from the oracle column.
TRUE_ATT <- d |>
filter(___) |> # TODO: treated villages, from 2010
summarise(att = mean(effect_oracle)) |>
pull(att)
TRUE_ATTError in parse(text = input): <text>:2:11: unexpected input
1: TRUE_ATT <- d |>
2: filter(__
^
- How many villages, years and observations are there? How many treated villages?
- Treated villages have lower yields on average (the \(-3\,\text{Treated}_i\) term). Is this a problem for a difference-in-differences?
- What is the ATT?
Your answers go here.
2 Plot the observations
2.1 A Few Villages
Let us plot the yield (observed) of 20 villages drawn at random.
set.seed(123)
id_some_villages <- sample(unique(d$village), 20)
d |>
filter(village %in% id_some_villages) |>
mutate(group = if_else(treated == 1, "Treated", "Control")) |>
ggplot(
mapping = aes(x = year, y = yield, group = village, colour = group)
) +
geom_vline(xintercept = 2009.5, linetype = "dashed") +
geom_line(alpha = .7) +
scale_colour_manual(values = group_colours) +
scale_x_continuous(breaks = 2004:2015) +
labs(x = NULL, y = "Yield (q/ha)", colour = NULL)
What differs from one village to the next? What do all villages have in common? Which terms of the equation do these features correspond to?
- What differs:
- What do all villages have in common:
Terms to use: \(a_{i}\), \(-3\), \(0.5(t-2004)\), \(s_{t}\), \(\tau_{it}\), \(e_{it}\).
2.2 Group means
Compute the mean yield of each group (treated/untreated) in each year, with a 95% confidence interval, and plot it.
For each group \(g \in \{\graswongBlueMath{0}, \graswongGoldMath{1}\}\) (\(\graswongBlueMath{\text{control}}\), \(\graswongGoldMath{\text{treated}}\)), with \(N_g\) villages, and each year \(t\), the mean yield is \[ \bar{Y}_{gt} = \frac{1}{N_g} \sum_{i:\,\text{Treated}_i = g} Y_{it}, \] its standard error is \[ \widehat{\text{se}}\big(\bar{Y}_{gt}\big) = \frac{s_{gt}}{\sqrt{N_g}}, \qquad s_{gt}^2 = \frac{1}{N_g - 1} \sum_{i:\,\text{Treated}_i = g} \big(Y_{it} - \bar{Y}_{gt}\big)^2, \] and its 95% confidence interval is \[ \highlightwongOrangeMath{\bar{Y}_{gt} \pm 1.96 \times \widehat{\text{se}}\big(\bar{Y}_{gt}\big)}. \]
means <- d |>
mutate(group = if_else(treated == 1, "Treated", "Control")) |>
group_by(group, year) |>
summarise(
mean_yield = mean(yield),
se = sd(yield) / sqrt(n()),
.groups = "drop"
)
ggplot(
data = means,
mapping = aes(x = ___, y = ___, colour = group)
) + # TODO: x and y
geom_vline(xintercept = 2009.5, linetype = "dashed") +
geom_line() +
geom_pointrange(
mapping = aes(ymin = ___, ymax = ___) # TODO: bounds of the 95% CI
) +
scale_colour_manual(values = group_colours) +
scale_x_continuous(breaks = 2004:2015) +
labs(x = NULL, y = "Mean yield (q/ha)", colour = NULL)Error in parse(text = input): <text>:12:22: unexpected input
11: data = means,
12: mapping = aes(x = __
^
A 95% confidence interval (CI) for one mean is \(\bar Y \pm 1.96 \times \text{se}\). It tells us where this mean is likely to be.
To know whether two means are different, look at their difference \(G = \bar Y_{0t} - \bar Y_{1t}\). For two independent groups, \[ \text{se}(G) = \sqrt{\text{se}_0^2 + \text{se}_1^2}, \] and the difference is significant at 5% if \(|G| > 1.96 \times \text{se}(G)\).
With equal standard errors, \(\text{se}(G) = \sqrt{2}\,\text{se} \approx 1.4\,\text{se}\), while two intervals stop overlapping only when \(G > 2 \times 1.96\,\text{se}\). So two intervals can overlap even when the difference is significant. The column se of means gives you what you need to check.
- Before 2010, are the two lines parallel? Are they at the same level?
- What happens after 2010?
- Before 2010, the confidence intervals of the two means do not overlap; from 2011, they do. Does the overlap mean that we cannot detect a difference between the groups from 2011? Does it tell us anything about the effect of the program?
2.3 The counterfactual
Using the previous plot, let us add the mean of yield0_oracle for the treated villages: the yield they would have had without the program.
counterfactual <- d |>
filter(treated == 1) |>
group_by(year) |>
summarise(mean_yield0 = mean(yield0_oracle))
ggplot(means, aes(x = year, y = mean_yield, colour = group)) +
geom_vline(xintercept = 2009.5, linetype = "dashed") +
geom_line() +
geom_point() +
geom_line(data = counterfactual, aes(x = year, y = mean_yield0),
inherit.aes = FALSE, colour = group_colours[["Treated"]],
linetype = "dashed") +
scale_colour_manual(values = group_colours) +
scale_x_continuous(breaks = 2004:2015) +
labs(x = NULL, y = "Mean yield (q/ha)", colour = NULL,
caption = "Dashed line: treated villages without the program (oracle).")Error:
! object 'means' not found
DiD assumes that, without the program, the treated villages would have followed the same evolution as the control villages: \[ \mathbb{E}\big[Y_{it}(0) - Y_{i,2009}(0) \mid \text{Treated}_i = 1\big] = \mathbb{E}\big[Y_{it}(0) - Y_{i,2009}(0) \mid \text{Treated}_i = 0\big]. \] The levels can differ (here, treated villages are about 3 q/ha lower): only the changes must be the same. After 2010, \(Y_{it}(0)\) is not observed for the treated villages, so the assumption can never be fully checked. We can only look at the years before.
- In real data, which line would be missing?
- State the parallel trends assumption in terms of this dashed line.
- Can you check the assumption before 2010? After 2010?
- In real life,
2.4 The gap between the groups
For each year, compute the gap between the treated and control means, and how it changed since 2009.
For each year \(t\), the gap between the two groups is \[ \text{gap}_t = \graswongGoldMath{\bar{Y}_{1t}} - \graswongBlueMath{\bar{Y}_{0t}}, \] and its change since 2009 is \[ \Delta_t = \text{gap}_t - \text{gap}_{2009} = \highlightwongOrangeMath{\big(\graswongGoldMath{\bar{Y}_{1t}} - \graswongGoldMath{\bar{Y}_{1,2009}}\big) - \big(\graswongBlueMath{\bar{Y}_{0t}} - \graswongBlueMath{\bar{Y}_{0,2009}}\big)}. \] By definition, \(\Delta_{2009} = 0\). For \(t \geq 2010\), \(\Delta_t\) is a difference-in-differences: the change in the mean yield of the \(\graswongGoldMath{\text{treated}}\) villages since 2009, minus the change for the \(\graswongBlueMath{\text{control}}\) villages.
gaps <- means |>
select(group, year, mean_yield) |>
pivot_wider(names_from = group, values_from = mean_yield) |>
mutate(
gap = ___, # TODO
gap_vs_2009 = ___ # TODO: change in the gap since 2009
)
gaps
ggplot(gaps, aes(x = year, y = gap_vs_2009)) +
geom_hline(yintercept = 0) +
geom_vline(xintercept = 2009.5, linetype = "dashed") +
geom_line() +
geom_point() +
scale_x_continuous(breaks = 2004:2015) +
labs(x = NULL, y = "Gap treated - control,\nminus the gap in 2009 (q/ha)")Error in parse(text = input): <text>:5:12: unexpected input
4: mutate(
5: gap = __
^
- What should this plot look like before 2010 if the trends were parallel?
- What does it measure after 2010? Compare it with the true effect (1, 2, 3, 3, 3, 3).
3 Estimate the effect
3.1 DiD with four means
We compare the period before the program (2004–2009) with the period after (2010–2015).
For each group \(g \in \{\graswongBlueMath{0}, \graswongGoldMath{1}\}\), the mean yield before and after the start of the program is \[ \bar{Y}_{g}^{\,\text{before}} = \frac{1}{6\,N_g} \sum_{i:\,\text{Treated}_i = g} \;\sum_{t=2004}^{2009} Y_{it}, \qquad \bar{Y}_{g}^{\,\text{after}} = \frac{1}{6\,N_g} \sum_{i:\,\text{Treated}_i = g} \;\sum_{t=2010}^{2015} Y_{it}. \] The difference-in-differences estimator is the change for the \(\graswongGoldMath{\text{treated}}\) villages minus the change for the \(\graswongBlueMath{\text{control}}\) villages: \[ \widehat{\text{DiD}} = \highlightwongOrangeMath{\big(\graswongGoldMath{\bar{Y}_{1}^{\,\text{after}}} - \graswongGoldMath{\bar{Y}_{1}^{\,\text{before}}}\big) - \big(\graswongBlueMath{\bar{Y}_{0}^{\,\text{after}}} - \graswongBlueMath{\bar{Y}_{0}^{\,\text{before}}}\big)}. \]
First, we create the \(\text{Post}_t\) dummy that takes value 1 from 2010 on, and the \(D_{it}\) dummy that takes value 1 if the village is in the program that year, 0 otherwise.
d <- d |>
mutate(
post = as.integer(year >= 2010), # 1 from 2010 on
D = treated * post # 1 if the village is in the program that year
)changes <- d |>
group_by(treated) |>
summarise(
before = mean(yield[post == 0]),
after = mean(yield[post == 1]),
change = ___ # TODO
)
changes
did_hand <- ___ # TODO: use changes$change and changes$treated
did_handError in parse(text = input): <text>:6:15: unexpected input
5: after = mean(yield[post == 1]),
6: change = __
^
3.2 The same with regressions
First, the “2×2” regression \[Y_{it} = \beta_0 + \beta_1\,\text{Treated}_i + \beta_2\,\text{Post}_t + \beta_3\,(\text{Treated}_i\times\text{Post}_t) + \varepsilon_{it}.\] Then the two-way fixed effects (TWFE) regression, with one fixed effect per village (\(\gamma_i\)) and one per year (\(\delta_t\)): \[Y_{it} = \gamma_i + \delta_t + \beta\,D_{it} + \varepsilon_{it}.\]
We use the notation of the slides: \(Y_{it}\) is yield, \(\text{Treated}_i\) is treated, \(\text{Post}_t\) is post, \(D_{it}=\text{Treated}_i\times\text{Post}_t\) is D, \(\gamma_i\) and \(\delta_t\) are the village and year fixed effects.
A village fixed effect \(\gamma_i\) is one dummy per village. It captures everything about a village that does not change over time: its land quality \(a_i\), and also the \(-3\) of treated villages. Since \(\text{Treated}_i\) never changes for a given village, it is absorbed by \(\gamma_i\): this is why treated does not appear in the TWFE regression.
A year fixed effect \(\delta_t\) is one dummy per year. It captures everything that affects all villages in the same year: the trend \(0.5\,(t-2004)\), the weather \(s_t\), and also \(\text{Post}_t\).
What is left to estimate \(\beta\) is \(D_{it}\): whether a village is in the program in a given year, compared with its usual level and with the common shock of that year. With two groups, one start date and a balanced panel, this gives exactly the DiD with four means.
did_2x2 <- feols(yield ~ treated * post, data = d, vcov = "iid")
did_twfe_iid <- feols(yield ~ D | village + year, data = d, vcov = "iid")
did_twfe_cl <- feols(yield ~ D | village + year, data = d, cluster = ~village)
etable(
did_2x2, did_twfe_iid, did_twfe_cl,
headers = c("2x2, iid", "TWFE, iid", "TWFE, clustered")
) did_2x2 did_twfe_iid did_twfe_cl
2x2, iid TWFE, iid TWFE, clustered
Dependent Var.: yield yield yield
Constant 41.88*** (0.1892)
treated -3.324*** (0.2675)
post 2.971*** (0.2675)
treated x post 2.452*** (0.3783)
D 2.452*** (0.1352) 2.452*** (0.2141)
Fixed-Effects: ------------------ ----------------- -----------------
village No Yes Yes
year No Yes Yes
_______________ __________________ _________________ _________________
S.E. type IID IID by: village
Observations 2,400 2,400 2,400
R2 0.21527 0.90854 0.90854
Within R2 -- 0.13073 0.13073
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
confint(did_twfe_cl) 2.5 % 97.5 %
D 2.029512 2.873904
iid standard errors (vcov = "iid") assume that all 2,400 errors are independent of each other.
But the shocks of a village persist over time (\(e_{it} = 0.6\,e_{i,t-1} + u_{it}\)), so the errors of the same village are correlated. Twelve years of one village carry less information than twelve different villages: iid standard errors are then too small, and the CIs too narrow.
Clustered standard errors (cluster = ~village) allow any correlation between the errors of the same village, and only assume that different villages are independent. Rule of thumb: cluster at the level at which the treatment is assigned (here, the village).
- Compare
did_hand, the coefficient ontreated x postand the coefficient onD. Why are they equal? - Is the true ATT inside the 95% CI?
- The three columns give the same estimate but three different standard errors. Which one would you report, and why?
4 Event study, display the coefficients
4.1 Estimation
Instead of one coefficient for the whole post period, estimate one coefficient per year, relative to 2009 (the last year before the program): \[Y_{it} = \gamma_i + \delta_t + \sum_{k\neq 2009}\beta_k\,\mathbb 1[t=k]\times\text{Treated}_i + \varepsilon_{it}.\]
As in the slides, one year is left out as the reference. Here, it is 2009, the last year before the program (in the training example of the slides, it was year \(-2\), the last year before the dip).
\(\mathbb 1[t=k]\) is an indicator: it equals 1 if the year is \(k\), and 0 otherwise. So \(\mathbb 1[t=2012] \times \text{Treated}_i\) equals 1 only for treated villages in 2012. In fixest, i(year, treated, ref = 2009) creates all these dummies at once, except the one for 2009.
Why leave one year out? If you add up the dummies of all 12 years, you get \(\text{Treated}_i\), which the village fixed effects already capture. With all 12 dummies, the regression could not separate them (perfect collinearity, as in the “dummy variable trap” with a constant and one dummy per category). Each \(\beta_k\) is therefore measured relative to the year left out.
es <- feols(
yield ~ i(year, treated, ref = 2009) | village + year,
data = d, cluster = ~village
)
etable(es) es
Dependent Var.: yield
treated x year = 2004 -0.1471 (0.3246)
treated x year = 2005 -0.1814 (0.3566)
treated x year = 2006 -0.0282 (0.3357)
treated x year = 2007 -0.1942 (0.2770)
treated x year = 2008 -0.1467 (0.2200)
treated x year = 2010 0.6826** (0.2266)
treated x year = 2011 1.700*** (0.2853)
treated x year = 2012 2.907*** (0.3232)
treated x year = 2013 3.121*** (0.3416)
treated x year = 2014 2.816*** (0.3608)
treated x year = 2015 2.786*** (0.3757)
Fixed-Effects: -----------------
village Yes
year Yes
_____________________ _________________
S.E.: Clustered by: village
Observations 2,400
R2 0.91201
Within R2 0.16369
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
- What does \(\beta_{2012}\) measure?
- Why must one year be left out?
4.2 Comparison between estimates and the true values
First, let us put the coefficients in a data frame, add the reference year (its coefficient is 0 by definition) and the true effect.
es_tbl <- tidy(es, conf.int = TRUE) |>
mutate(
# "year::2004:treated" -> 2004
year = as.integer(str_extract(term, "\\d{4}"))
) |>
select(year, estimate, conf.low, conf.high) |>
# Reference year
add_row(
year = 2009,
estimate = 0,
conf.low = 0,
conf.high = 0
) |>
arrange(year)
# The true effect per year (not observed in real life)
true_effect <- d |>
filter(treated == 1) |>
distinct(year, true = effect_oracle)
es_tbl <- es_tbl |> left_join(true_effect, by = "year")
es_tbl# A tibble: 12 × 5
year estimate conf.low conf.high true
<dbl> <dbl> <dbl> <dbl> <dbl>
1 2004 -0.147 -0.787 0.493 0
2 2005 -0.181 -0.885 0.522 0
3 2006 -0.0282 -0.690 0.634 0
4 2007 -0.194 -0.740 0.352 0
5 2008 -0.147 -0.581 0.287 0
6 2009 0 0 0 0
7 2010 0.683 0.236 1.13 1
8 2011 1.70 1.14 2.26 2
9 2012 2.91 2.27 3.54 3
10 2013 3.12 2.45 3.79 3
11 2014 2.82 2.10 3.53 3
12 2015 2.79 2.04 3.53 3
Display the coefficients with their 95% CI, together with the true effect.
ggplot(
data = es_tbl,
mapping = aes(x = year)
) +
geom_hline(yintercept = 0) +
geom_vline(xintercept = 2009.5, linetype = "dashed") +
geom_line(
mapping = aes(y = true),
colour = truth_colour, linewidth = 1
) +
geom_pointrange(
mapping = aes(y = ___, ymin = ___, ymax = ___) # TODO
) +
scale_x_continuous(breaks = 2004:2015) +
labs(
x = NULL,
y = "Effect on yield, relative to 2009 (q/ha)",
caption = "Points and bars: estimates and 95% CI. Orange line: true effect (oracle)."
)Error in parse(text = input): <text>:12:24: unexpected input
11: geom_pointrange(
12: mapping = aes(y = __
^
Each point is \(\hat\beta_k\): how much the gap between treated and control villages changed between 2009 and year \(k\).
- Before the program: if the trends were parallel, the points should be close to 0, and their 95% CIs should contain 0.
- After the program: the points show how the effect changes over time.
- A 95% CI misses the true value in about 5% of samples. With many coefficients, one miss is not alarming.
- What do the coefficients before 2010 tell you?
- Compare the estimates with the truth. How many of the 11 CIs (2004–2015, without 2009) contain the true value? How many would you expect to miss it?
- Compare
es_tbl$estimatewithgaps$gap_vs_2009from Section 2.4. Why are they equal?
4.3 A joint test of the pre-trends
Are the five coefficients for 2004–2008 all equal to zero at the same time?
# the coefficients of 2004 to 2008
wald(es, keep = "year::200") Wald test, H0: joint nullity of year::2004:treated, year::2005:treated, year::2006:treated, year::2007:treated and year::2008:treated
stat = 0.242848, p-value = 0.942979, on 5 and 199 DoF, VCOV: Clustered (village).
Looking at five CIs one by one does not test whether the five coefficients are all zero at the same time. The Wald test does it in one step: \[ H_0:\ \beta_{2004} = \beta_{2005} = \dots = \beta_{2008} = 0. \] A small p-value (say, below 0.05) rejects \(H_0\): at least one coefficient before the program is not zero, which is a warning for parallel trends.
In wald(es, keep = "year::200"), the argument keep selects the coefficients whose name contains year::200, that is, the years 2004 to 2009 (2009 is the reference here, so it has no coefficient).
A large p-value means “no evidence against” parallel trends before 2010, not a proof: the test may lack power, and it says nothing about the years after 2010.
What is the null hypothesis? What do you conclude? Does a large p-value prove that the parallel trends assumption holds?
{fixest} can draw the same plot in one line (without the truth, which only we know):
iplot(es)
5 DiD detective, five provinces
Now, suppose that the same program also started in 2010 in five other provinces, called A to E. In each province, an evaluation team received data on 200 villages, 2004–2015, in data/province_A.csv, …, data/province_E.csv, with four variables: village, year, treated and yield.
Here, there are no oracle columns: as in real life, you do not know the true effect!
Imagine you are the evaluation team of one province (pick a group from A to E). The Ministry of Agriculture wants to know the effect of the program on yields in your province, and how much it can trust your number.
From the lecture, here are the possible problems. A province may have one of them, or none.
| Suspect | What happened | |
|---|---|---|
| (a) | Nothing | The design works |
| (b) | Diverging trends | Treated villages already had a different trend before 2010 |
| (c) | Ashenfelter dip | Villages entered the program after an unusually bad year |
| (d) | Anticipation | Villages changed their behavior before the program started |
| (e) | Something else | Another change hit the treated villages from 2010 |
- (b) Diverging trends: before 2010, the coefficients move steadily up or down (a slope).
- (c) Ashenfelter dip: the treated villages fall in the year just before the program, then come back. With 2009 as the reference, all the earlier coefficients are shifted by the same amount; with an earlier reference year, only 2009 stands out, with a negative coefficient.
- (d) Anticipation: the effect starts before 2010. With an earlier reference year, 2009 stands out with a coefficient of the same sign as the effect.
- (e) Something else: nothing unusual before 2010. The data alone cannot reveal it.
5.1 Your Toolbox
The four functions below combine the steps of Parts 2 to 4. Run the chunk.
# 1. Mean yield of each group, by year, with 95% CI
#' @param d Dataset.
plot_trends <- function(d) {
d |>
mutate(group = if_else(treated == 1, "Treated", "Control")) |>
group_by(group, year) |>
summarise(
mean_yield = mean(yield), se = sd(yield) / sqrt(n()),
.groups = "drop"
) |>
ggplot(aes(x = year, y = mean_yield, colour = group)) +
geom_vline(xintercept = 2009.5, linetype = "dashed") +
geom_line() +
geom_pointrange(
mapping = aes(
ymin = mean_yield - 1.96 * se,
ymax = mean_yield + 1.96 * se
),
size = .3
) +
scale_colour_manual(values = group_colours) +
scale_x_continuous(breaks = 2004:2015) +
labs(x = NULL, y = "Mean yield (q/ha)", colour = NULL)
}
# 2. Static DiD (TWFE), standard errors clustered by village
#' @param d Dataset.
did_twfe <- function(d) {
d <- d |> mutate(D = treated * as.integer(year >= 2010))
feols(yield ~ D | village + year, data = d, cluster = ~village) |>
tidy(conf.int = TRUE) |>
select(term, estimate, std.error, conf.low, conf.high)
}
# 3. Event study relative to the year `ref_year`
#' @param d Dataset.
#' @param ref_year Reference year.
event_study <- function(d, ref_year = 2009) {
feols(
yield ~ i(year, treated, ref = ref_year) | village + year,
data = d, cluster = ~village
)
}
# 4. Coefficient plot, with the reference year added (as in 4.2)
#' @param es Event-study regression (output of event_study()).
plot_event_study <- function(es) {
tbl <- tidy(es, conf.int = TRUE) |>
mutate(year = as.integer(str_extract(term, "\\d{4}"))) |>
select(year, estimate, conf.low, conf.high)
ref_year <- setdiff(2004:2015, tbl$year)
tbl |>
add_row(year = ref_year, estimate = 0, conf.low = 0, conf.high = 0) |>
ggplot(
mapping = aes(
x = year, y = estimate, ymin = conf.low, ymax = conf.high
)
) +
geom_hline(yintercept = 0) +
geom_vline(xintercept = 2009.5, linetype = "dashed") +
geom_pointrange() +
scale_x_continuous(breaks = 2004:2015) +
labs(x = NULL, y = str_c("Effect relative to ", ref_year, " (q/ha)"))
}5.2 Investigate your province
Run the chunk with the letter of your province. If you think that 2009 is not a good reference year, re-estimate the event study with another one, for instance event_study(dp, ref_year = 2008). To estimate the static DiD without some years, filter them out, for instance did_twfe(filter(dp, year != 2009)).
With ref_year = 2008, the year 2009 now has a coefficient, and keep = "year::200" includes it in the joint test. To test only the years before a possible dip or anticipation, select them explicitly, for instance:
es_p8 <- event_study(dp, ref_year = 2008)
wald(es_p8, keep = "year::200[4-7]") # 2004 to 2007 onlymy_province <- "___" # TODO: the letter of your province, e.g. "C"
# Import dataset
dp <- read_csv(
here("data", str_c("province_", my_province, ".csv")),
show_col_types = FALSE
)
plot_trends(dp)
did_twfe(dp)
es_p <- event_study(dp)
wald(es_p, keep = "year::200") # joint test: all coefficients before 2010 are 0
plot_event_study(es_p)- Do the trends look parallel before 2010? What do you see?
- Static DiD estimate, with its 95% CI.
- The event study before 2010: what pattern? The p-value of the joint test.
- Your suspect, (a) to (e), and your evidence.
- Your preferred estimate for the Ministry, and its main limitation.
Report (2 minutes per team): show your event-study plot, give your number and your verdict.
5.3 The reveal
Let us reveal, in class, what happened in each province after the reports.
6 Wrap-up
- Which problems could you detect with the data? Which one could you not, and what would you need to detect it?
- Angrist and Pischke (2010) ask DiD studies to show outcomes over many years, so that we can see the trends. Why? With only two years of data (2009 and 2010), which provinces would have given you a wrong answer?
- Which province looks like the training programs of Ashenfelter and Card (1985)? Which base year would you choose there?