Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set names of dataframes inside lists

I've got a rather large list that contains many dataframes of the same length. I'd like to rename all the column names in the list. I've tried to use purrr::map, but have hit various issues. Is there a better way to do this?

Here is a reprex of the approach and issues I'm having with it. Thanks.

library(tidyverse)


org_names <- names(
    starwars %>% 
        select_if(
        Negate(is.list))
                   )

df <- starwars %>% 
    select_if(Negate(is.list))

names(df) <- sample(LETTERS, length(df), replace = F)



df_ls <- list(df, list(df, df), list(df, df, df), df, list(df, df))


map(df_ls, function(x){
    x %>% 
        set_names(org_names)
})
#> `nm` must be `NULL` or a character vector the same length as `x`
like image 288
elliot Avatar asked Oct 27 '25 21:10

elliot


1 Answers

As some of the elements are nested list, can use a condition to check if it is a list, then do the set_names by looping inside the list

library(tidyverse)
map(df_ls, ~ if(is.data.frame(.x))  .x %>% 
                                      set_names(org_names) else 
                   map(.x,  ~ .x %>%
                               set_names(org_names)))

Or it can be made more compact with map_if

out <- map_if(df_ls, is.data.frame, set_names, org_names, 
             .else = ~ map(.x, set_names, org_names))
like image 147
akrun Avatar answered Oct 30 '25 10:10

akrun