使用purrr :: walk重命名数据帧列表中的列

时间:2022-03-24 10:36:01

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

我需要重命名列表中所有数据帧的第二列。我正在尝试使用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?

当我检查列名称时,所有平均列仍然被命名为'mean'。我做错了什么?

1 个解决方案

#1


4  

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.

如果你有这样的列名列表,你可以使用map2同时循环过滤变量和命名变量。这将允许您在进行操作时命名列,而不是在创建列表后重命名。

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

这确实涉及使用rlang中的一些tidyeval操作来使用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

#1


4  

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.

如果你有这样的列名列表,你可以使用map2同时循环过滤变量和命名变量。这将允许您在进行操作时命名列,而不是在创建列表后重命名。

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

这确实涉及使用rlang中的一些tidyeval操作来使用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