问题描述
我如何使用管道操作符将替换函数输入到替换函数中,例如 colnames() ?
How can I use the pipe operator to pipe into replacement function like colnames()<-
?
这是我想要做的:
library(dplyr)
averages_df <-
group_by(mtcars, cyl) %>%
summarise(mean(disp), mean(hp))
colnames(averages_df) <- c("cyl", "disp_mean", "hp_mean")
averages_df
# Source: local data frame [3 x 3]
#
# cyl disp_mean hp_mean
# 1 4 105.1364 82.63636
# 2 6 183.3143 122.28571
# 3 8 353.1000 209.21429
但理想情况下应该是这样的:
But ideally it would be something like:
averages_df <-
group_by(mtcars, cyl) %>%
summarise(mean(disp), mean(hp)) %>%
add_colnames(c("cyl", "disp_mean", "hp_mean"))
有没有办法不用每次都写一个专门的函数?
Is there a way to do this without writing a specialty function each time?
这里的答案是一个开始,但不完全是我的问题:在 dplyr 中链接算术运算符
The answers here are a start, but not exactly my question: Chaining arithmetic operators in dplyr
推荐答案
您可以使用 colnames<-
或 setNames
(感谢@David Arenburg)
You could use colnames<-
or setNames
(thanks to @David Arenburg)
group_by(mtcars, cyl) %>%
summarise(mean(disp), mean(hp)) %>%
`colnames<-`(c("cyl", "disp_mean", "hp_mean"))
# or
# `names<-`(c("cyl", "disp_mean", "hp_mean"))
# setNames(., c("cyl", "disp_mean", "hp_mean"))
# cyl disp_mean hp_mean
# 1 4 105.1364 82.63636
# 2 6 183.3143 122.28571
# 3 8 353.1000 209.21429
或者从 magrittr
中选择一个 Alias
(set_colnames
):
Or pick an Alias
(set_colnames
) from magrittr
:
library(magrittr)
group_by(mtcars, cyl) %>%
summarise(mean(disp), mean(hp)) %>%
set_colnames(c("cyl", "disp_mean", "hp_mean"))
dplyr::rename
如果您只是(重新)命名许多列中的一些列可能会更方便(它需要同时编写旧名称和新名称;请参阅@Richard Scriven 的回答)
dplyr::rename
may be more convenient if you are only (re)naming a few out of many columns (it requires writing both the old and the new name; see @Richard Scriven's answer)
这篇关于将 %>% 与 colnames()<- 等替换函数一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!