Last active
November 4, 2021 10:36
-
-
Save resulumit/6c8ede945c7002ac3a33361d21d4e528 to your computer and use it in GitHub Desktop.
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
# a loop-based function in r | |
# that can be used for multiverse analysis | |
# with the feols function from the fixest package | |
feols_multiverse <- function(dep_var, indep_var, cont_var, back_end){ | |
# function to create the powerset | |
power <- function(x){ | |
sets <- lapply(1:(length(x)), function(i) combn(x, i, simplify = F)) | |
unlist(sets, recursive = F) | |
} | |
# create the powerset | |
powerset <- c(" ", as.list(paste0(" + ", lapply(power(cont_var), | |
function(x) sprintf(paste0(x, collapse = " + ")))))) | |
# create the df of calls | |
df.calls <- do.call(rbind, lapply(powerset, as.data.frame)) | |
names(df.calls)[1] <- "set.element" | |
calllist <- list() | |
for(i in 1:(length(dep_var))){ | |
df.calls$call <- paste0("feols(", dep_var[i], " ~ ", indep_var, df.calls$set.element, back_end[i]) | |
df.calls$dv <- dep_var[i] | |
calllist[[i]] <- df.calls # add it to the list | |
} | |
# bind the list together as a tibble | |
df.calls <- do.call(rbind, calllist) | |
df.calls <- subset(df.calls, select = c("call", "dv")) | |
# create a list to be filled with regression results | |
reglist = list() | |
# loop the regression runs | |
for(i in seq(df.calls$call)){ | |
skip_to_next <- FALSE | |
tryCatch( | |
expr = { | |
model <- broom::tidy(eval(rlang::parse_expr(df.calls$call[i]))) | |
model$formula <- df.calls$call[i] | |
model$dv <- df.calls$dv[i] | |
reglist[[i]] <- model # add it to the list | |
}, | |
error = function(x) {skip_to_next <<- TRUE} | |
) | |
if(skip_to_next) { next } | |
} | |
# bind the list together as a tibble | |
regresion_results <- do.call(rbind, reglist) | |
# print the results | |
regresion_results | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment