[英]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.
我正在尝试使用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'. 当我检查列名称时,所有均值列仍被命名为“ 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. 如果您具有这样的列名列表,则可以使用
map2
同时循环遍历filter
变量和命名变量。 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 . 这不涉及到使用一些
tidyeval
从rlang运营与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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.