set.seed(2) L <- 100 T <- 2 K <- 2 beta <- 1 sigma <-c(0.1, 0.1, 1)
z_lk0 <-
tidyr::expand_grid(
l = 1:L,
k = 1:K
) %>%
dplyr::mutate(
z_lk0 = runif(length(l))
)
g_kt <-
tidyr::expand_grid(
t = 1:T,
k = 1:K
) %>%
dplyr::mutate(g_kt = rnorm(t))
df <-
tidyr::expand_grid(
l = 1:L,
t = 1:T,
k = 1:K
) %>%
dplyr::left_join(
z_lk0,
by = c("l", "k")
) %>%
dplyr::left_join(
g_kt,
by = c("k", "t")
) %>%
dplyr::mutate(
z_lkt = z_lk0 + sigma[1] * runif(length(l)),
g_lkt = g_kt + sigma[2] * rnorm(length(l))
)
df <-
df %>%
dplyr::group_by(t, l) %>%
dplyr::mutate(
z_lk0 = z_lk0 / sum(z_lk0),
z_lkt = z_lkt / sum(z_lkt),
x_lt = sum(z_lkt * g_lkt)
)
df_lt <-
df %>%
dplyr::mutate(g_tilde_lkt = g_lkt - g_kt) %>%
dplyr::group_by(l, t) %>%
dplyr::summarise(
dplyr::across(
c(x_lt, g_tilde_lkt),
mean
),
.groups = "drop"
) %>%
dplyr::ungroup() %>%
dplyr::mutate(
y_lt = beta * x_lt + sigma[3] * g_tilde_lkt
)
result_ols <-
df_lt %>%
lm(
formula = y_lt ~ x_lt
)
modelsummary::modelsummary(result_ols)
| Model 1 | |
|---|---|
| (Intercept) | 0.008 |
| (0.005) | |
| x_lt | 1.017 |
| (0.008) | |
| Num.Obs. | 200 |
| R2 | 0.989 |
| R2 Adj. | 0.989 |
| AIC | -505.6 |
| BIC | -495.7 |
| Log.Lik. | 255.810 |
| F | 17887.862 |
b_lt <- df %>% dplyr::group_by(l, t) %>% dplyr::summarise(b_lt = sum(z_lk0 * g_kt)) %>% dplyr::ungroup()
## `summarise()` has grouped output by 'l'. You can override using the `.groups` argument.
result_first_stage <-
df_lt %>%
dplyr::left_join(b_lt, by = c("l", "t")) %>%
lm(
formula = x_lt ~ b_lt
)
modelsummary::modelsummary(result_first_stage)
| Model 1 | |
|---|---|
| (Intercept) | 0.016 |
| (0.006) | |
| b_lt | 1.012 |
| (0.010) | |
| Num.Obs. | 200 |
| R2 | 0.980 |
| R2 Adj. | 0.980 |
| AIC | -394.3 |
| BIC | -384.4 |
| Log.Lik. | 200.135 |
| F | 9714.889 |
result_tsls <-
df_lt %>%
dplyr::left_join(b_lt, by = c("l", "t")) %>%
estimatr::iv_robust(
formula = y_lt ~ x_lt | b_lt
)
modelsummary::modelsummary(result_tsls)
| Model 1 | |
|---|---|
| (Intercept) | 0.009 |
| (0.005) | |
| x_lt | 1.005 |
| (0.008) | |
| Num.Obs. | 200 |
| R2 | 0.989 |
| R2 Adj. | 0.989 |
| p.value.endogeneity | |
| p.value.overid | |
| p.value.weakinst | |
| se_type | HC2 |
| statistic.endogeneity | |
| statistic.overid | |
| statistic.weakinst |