Skip to content

Instantly share code, notes, and snippets.

@wmay
Created April 13, 2025 22:20
Show Gist options
  • Save wmay/b5c0b06b2aca2d2225ba8155a1191b62 to your computer and use it in GitHub Desktop.
Save wmay/b5c0b06b2aca2d2225ba8155a1191b62 to your computer and use it in GitHub Desktop.
Two-way fixed effects demo
unit_effect = rnorm(5)
time_effect = rnorm(5)
unit = rep(1:5, each = 20)
time = rep(1:5, times = 20)
x = rnorm(100)
y = unit_effect[unit] + time_effect[time] + .5 * x + rnorm(100)
df = data.frame(y = y, unit = factor(unit), time = factor(time), x = x)
fit1 = lm(y ~ unit + time, data = df)
fit2 = lm(y ~ unit + time + x, data = df)
# The two regressions return different fixed effect coefficients-- the fixed
# effect coefficients are no longer means if there are additional predictors.
# Also note the estimate of x's coefficient is accurate.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment