简体   繁体   中英

rename a column in a list of dataframes in using purrr::walk

I need to rename the second columns for all the dataframes in a list. I'm trying to use purrr::walk.

Here is the code:

cyl.name<- c('4-cyl', '6-cyl', '8-cyl')
cyl<- c(4,6,8)    
car <- map(cyl, ~mtcars %>% filter(cyl==.x) %>%
                     group_by(gear) %>% 
                     summarise(mean=mean(hp)) )
walk (seq_along(cyl.name), function (x) names(car[[x]])[2]<- cyl.name[x])

When I check the columns names, all the mean column are still named 'mean'. What did I do wrong?

If you have the list of the column names like this, you could use map2 to simultaneously loop through the filter variable and the naming variable. This would allow you to name the columns as you go rather than renaming after making the list.

This does involve using some tidyeval operations from rlang for programming with dplyr .

map2(cyl, cyl.name, ~mtcars %>% 
         filter(cyl==.x) %>%
         group_by(gear) %>%
         summarise( !!.y := mean(hp)) )

[[1]]
# A tibble: 3 x 2
   gear `4-cyl`
  <dbl>   <dbl>
1     3      97
2     4      76
3     5     102

[[2]]
# A tibble: 3 x 2
   gear `6-cyl`
  <dbl>   <dbl>
1     3   107.5
2     4   116.5
3     5   175.0

[[3]]
# A tibble: 2 x 2
   gear  `8-cyl`
  <dbl>    <dbl>
1     3 194.1667
2     5 299.5000

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM