R Econometrics
Purpose
This skill helps economists run rigorous econometric analyses in R, including Instrumental Variables (IV), Difference-in-Differences (DiD), and Regression Discontinuity Design (RDD). It generates publication-ready code with proper diagnostics and robust standard errors.
When to Use
- Running causal inference analyses
- Estimating treatment effects with panel data
- Creating publication-ready regression tables
- Implementing modern econometric methods (two-way fixed effects, event studies)
Instructions
Step 1: Understand the Research Design
Before generating code, ask the user:
- What is your identification strategy? (IV, DiD, RDD, or simple regression)
- What is the unit of observation? (individual, firm, country-year, etc.)
- What fixed effects do you need? (entity, time, two-way)
- How should standard errors be clustered?
Step 2: Generate Analysis Code
Based on the research design, generate R code that:
- Uses the
fixest package - Modern, fast, and feature-rich for panel data
- Includes proper diagnostics:
- For IV: First-stage F-statistics, weak instrument tests
- For DiD: Parallel trends visualization, event study plots
- For RDD: Bandwidth selection, density tests
- Uses robust/clustered standard errors appropriate for the data structure
- Creates publication-ready output using
modelsummary or etable
Step 3: Structure the Output
Always include:
# 1. Setup and packages
# 2. Data loading and preparation
# 3. Descriptive statistics
# 4. Main specification
# 5. Robustness checks
# 6. Visualization
# 7. Export results
Step 4: Add Documentation
Include comments explaining:
- Why each specification choice was made
- Interpretation of key coefficients
- Limitations and assumptions
Example Prompts
- "Run a DiD analysis with state and year fixed effects, clustering at the state level"
- "Estimate the effect of X on Y using Z as an instrument"
- "Create an event study plot showing treatment effects by year"
- "Run a sharp RDD with optimal bandwidth selection"
Example Output
# ============================================
# Difference-in-Differences Analysis
# ============================================
# Setup
library(tidyverse)
library(fixest)
library(modelsummary)
# Load data
df <- read_csv("data.csv")
# Prepare treatment variable
df <- df %>%
mutate(
post = year >= treatment_year,
treated = state %in% treatment_states,
treat_post = treated * post
)
# ----------------------------------------
# Main DiD Specification
# ----------------------------------------
# Two-way fixed effects
did_model <- feols(
outcome ~ treat_post | state + year,
data = df,
cluster = ~state
)
# View results
summary(did_model)
# ----------------------------------------
# Event Study
# ----------------------------------------
# Create relative time variable
df <- df %>%
mutate(rel_time = year - treatment_year)
# Event study regression
event_study <- feols(
outcome ~ i(rel_time, treated, ref = -1) | state + year,
data = df,
cluster = ~state
)
# Plot coefficients
iplot(event_study,
main = "Event Study: Effect on Outcome",
xlab = "Years Relative to Treatment")
# ----------------------------------------
# Robustness: Alternative Specifications
# ----------------------------------------
# Different clustering
did_robust <- feols(
outcome ~ treat_post | state + year,
data = df,
cluster = ~state + year # Two-way clustering
)
# ----------------------------------------
# Export Results
# ----------------------------------------
modelsummary(
list("Main" = did_model, "Two-way Cluster" = did_robust),
stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01),
output = "results/did_table.tex"
)
Requirements
Software
Packages
fixest - Fast fixed effects estimation
modelsummary - Publication-ready tables
tidyverse - Data manipulation
ggplot2 - Visualization
Install with:
install.packages(c("fixest", "modelsummary", "tidyverse"))
Best Practices
- Always cluster standard errors at the level of treatment assignment
- Run pre-trend tests for DiD designs
- Report first-stage F-statistics for IV (should be > 10)
- Use
feols over lm for panel data (faster and more features)
- Document all specification choices in your code comments
Common Pitfalls
- ❌ Not clustering standard errors at the right level
- ❌ Ignoring weak instruments in IV estimation
- ❌ Using TWFE with staggered treatment timing (use
did or sunab() instead)
- ❌ Not reporting robustness checks
References
Changelog
v1.0.0
- Initial release with IV, DiD, RDD support
1---2name: causal-inference-r3description: Run IV, DiD, and RDD analyses in R with proper diagnostics. Use when implementing causal inference methods, event studies, or treatment effect estimation.4---5
6# R Econometrics
7
8## Purpose
9
10This skill helps economists run rigorous econometric analyses in R, including Instrumental Variables (IV), Difference-in-Differences (DiD), and Regression Discontinuity Design (RDD). It generates publication-ready code with proper diagnostics and robust standard errors.
11
12## When to Use
13
14- Running causal inference analyses
15- Estimating treatment effects with panel data
16- Creating publication-ready regression tables
17- Implementing modern econometric methods (two-way fixed effects, event studies)
18
19## Instructions
20
21### Step 1: Understand the Research Design
22
23Before generating code, ask the user:
241. What is your identification strategy? (IV, DiD, RDD, or simple regression)
252. What is the unit of observation? (individual, firm, country-year, etc.)
263. What fixed effects do you need? (entity, time, two-way)
274. How should standard errors be clustered?
28
29### Step 2: Generate Analysis Code
30
31Based on the research design, generate R code that:
32
331. **Uses the `fixest` package** - Modern, fast, and feature-rich for panel data
342. **Includes proper diagnostics:**
35 - For IV: First-stage F-statistics, weak instrument tests
36 - For DiD: Parallel trends visualization, event study plots
37 - For RDD: Bandwidth selection, density tests
383. **Uses robust/clustered standard errors** appropriate for the data structure
394. **Creates publication-ready output** using `modelsummary` or `etable`
40
41### Step 3: Structure the Output
42
43Always include:
44```r
45# 1. Setup and packages
46# 2. Data loading and preparation
47# 3. Descriptive statistics
48# 4. Main specification
49# 5. Robustness checks
50# 6. Visualization
51# 7. Export results
52```
53
54### Step 4: Add Documentation
55
56Include comments explaining:
57- Why each specification choice was made
58- Interpretation of key coefficients
59- Limitations and assumptions
60
61## Example Prompts
62
63- "Run a DiD analysis with state and year fixed effects, clustering at the state level"
64- "Estimate the effect of X on Y using Z as an instrument"
65- "Create an event study plot showing treatment effects by year"
66- "Run a sharp RDD with optimal bandwidth selection"
67
68## Example Output
69
70```r
71# ============================================
72# Difference-in-Differences Analysis
73# ============================================
74
75# Setup
76library(tidyverse)
77library(fixest)
78library(modelsummary)
79
80# Load data
81df <- read_csv("data.csv")
82
83# Prepare treatment variable
84df <- df %>%
85 mutate(
86 post = year >= treatment_year,
87 treated = state %in% treatment_states,
88 treat_post = treated * post
89 )
90
91# ----------------------------------------
92# Main DiD Specification
93# ----------------------------------------
94
95# Two-way fixed effects
96did_model <- feols(
97 outcome ~ treat_post | state + year,
98 data = df,
99 cluster = ~state
100)
101
102# View results
103summary(did_model)
104
105# ----------------------------------------
106# Event Study
107# ----------------------------------------
108
109# Create relative time variable
110df <- df %>%
111 mutate(rel_time = year - treatment_year)
112
113# Event study regression
114event_study <- feols(
115 outcome ~ i(rel_time, treated, ref = -1) | state + year,
116 data = df,
117 cluster = ~state
118)
119
120# Plot coefficients
121iplot(event_study,
122 main = "Event Study: Effect on Outcome",
123 xlab = "Years Relative to Treatment")
124
125# ----------------------------------------
126# Robustness: Alternative Specifications
127# ----------------------------------------
128
129# Different clustering
130did_robust <- feols(
131 outcome ~ treat_post | state + year,
132 data = df,
133 cluster = ~state + year # Two-way clustering
134)
135
136# ----------------------------------------
137# Export Results
138# ----------------------------------------
139
140modelsummary(
141 list("Main" = did_model, "Two-way Cluster" = did_robust),
142 stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01),
143 output = "results/did_table.tex"
144)
145```
146
147## Requirements
148
149### Software
150- R 4.0+
151
152### Packages
153- `fixest` - Fast fixed effects estimation
154- `modelsummary` - Publication-ready tables
155- `tidyverse` - Data manipulation
156- `ggplot2` - Visualization
157
158Install with:
159```r
160install.packages(c("fixest", "modelsummary", "tidyverse"))
161```
162
163## Best Practices
164
1651. **Always cluster standard errors** at the level of treatment assignment
1662. **Run pre-trend tests** for DiD designs
1673. **Report first-stage F-statistics** for IV (should be > 10)
1684. **Use `feols` over `lm`** for panel data (faster and more features)
1695. **Document all specification choices** in your code comments
170
171## Common Pitfalls
172
173- ❌ Not clustering standard errors at the right level
174- ❌ Ignoring weak instruments in IV estimation
175- ❌ Using TWFE with staggered treatment timing (use `did` or `sunab()` instead)
176- ❌ Not reporting robustness checks
177
178## References
179
180- [fixest documentation](https://lrberge.github.io/fixest/)
181- [Cunningham (2021) Causal Inference: The Mixtape](https://mixtape.scunning.com/)
182- [Angrist & Pischke (2009) Mostly Harmless Econometrics](https://www.mostlyharmlesseconometrics.com/)
183
184## Changelog
185
186### v1.0.0
187- Initial release with IV, DiD, RDD support