Skip to content

Instantly share code, notes, and snippets.

@resulumit
Last active November 4, 2021 10:36
Show Gist options
  • Save resulumit/6c8ede945c7002ac3a33361d21d4e528 to your computer and use it in GitHub Desktop.
Save resulumit/6c8ede945c7002ac3a33361d21d4e528 to your computer and use it in GitHub Desktop.
# 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