I have a recursive function kindly explained to me by @thothal here This allows me to recursively get dataframes based on looking up a character string in the parent dataframe.
You can put all of your data frames in an own environment and once they are found remove it from there:
get_all_dfs_rec <- function(df, my_env) {
lapply(df[, 1], function(elem) {
print(paste("Looking for element", elem))
# use mget because we can use ifnotfound despite we are requesting only one element
next_df <- mget(elem, env = my_env, ifnotfound = NA)
if (!is.na(next_df)) {
# use list, otherwise rm tries to remove elem (which does not exist in the env)
rm(list = elem, envir = my_env)
unlist(get_all_dfs_rec(next_df[[1]], my_env), FALSE)
} else {
list(setNames(df, c("col1", "col2")))
}
})
}
get_all_dfs <- function(df_start) {
## create a new environment
my_env <- new.env()
## and add all 'data.frames' from the global environment to it
walk(ls(.GlobalEnv), ~ {
elem <- get(.x, env = .GlobalEnv);
if (class(elem) == "data.frame") my_env[[.x]] <- elem})
flatten_dfr(get_all_dfs_rec(df_start, my_env)) %>% unique()
}