How to prevent infinite loop in dataframe lookup where elements are bi-directional

后端 未结 1 1741

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.

1条回答
  •  萌比男神i
    2021-01-27 12:45

    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()
    }
    

    0 讨论(0)
提交回复
热议问题