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`
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.