Search code examples
rlistrename

How to unlist a list of multiple tibbles into different data frames and rename them?


I need to unlist a list of multiple tibbles into different data frames. In addition I want to add "_new" to the name of each unlisted data frame. I tried the following but renaming doesn't go as I wish (i.e., two separate data frames called (a_new and b_new). Besides, I prefer to avoid using a loop but not sure how to use apply function for that. Could you please help me with that?

old_list <- list( a = tibble(AAA = rep("HEN", 16), 
                             BBB = rep(1, 16), 
                             CCC = rep(14, 16)),
                  b = tibble(GGG = rep("DOG", 16), 
                             DDD = rep(5, 16), 
                             FFF = rep(9, 16)))

new <- list()
for (name in names(old_list)){
  rename_tables <- paste0(name,"_new")
  new[[rename_tables]] <- list2env(old_list, envir = .GlobalEnv)
}

Solution

  • one approach:

    new_list <- setNames(old_list, paste0(names(old_list), '_new'))
    

    to spawn the dfs into your workplace if need be ;-)

    new_list |> list2env(envir = .GlobalEnv)
    

    or short:

    setNames(old_list, paste0(names(old_list), '_new')) |>
        list2env(envir = .GlobalEnv)