Last active
March 2, 2019 04:52
-
-
Save vikjam/111cf5bff7a710be27c9367d9264a045 to your computer and use it in GitHub Desktop.
Looping regressions in the tidy verse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(gapminder) | |
library(tidyverse) | |
library(broom) | |
library(huxtable) | |
library(lfe) | |
# Example dataset (via gapminder package) | |
glimpse(gapminder) | |
# Create a function to make looping easier | |
lagged_felm <- function(yvar, tlags, fe) { | |
lags_formula <- paste("lag(gdpPercap, ", 1:tlags, ")", sep = "", collapse = " + ") | |
lags_formula <- paste("gdpPercap +", lags_formula) | |
felm_formula <- paste(yvar, " ~ ", lags_formula, " | ", fe) | |
felm_est <- felm(as.formula(felm_formula), data = gapminder) | |
return_df <- tidy(felm_est) %>% mutate(yvar = yvar) | |
return(felm_est) | |
} | |
yvars <- c("lifeExp", "pop") | |
lags <- seq(1, 2) | |
fes <- c("country", "year", "continent", "continent + year") | |
cross_args <- cross_df(list(yvar = yvars, | |
tlags = lags, | |
fe = fes)) | |
results <- cross_args %>% pmap(lagged_felm) | |
lifeExpTable <- results[which(cross_args$yvar == "lifeExp")] | |
popTable <- results[which(cross_args$yvar == "pop")] | |
do.call(stargazer, lifeExpTable) | |
do.call(stargazer, popTable) | |
# End of script |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment