gpt4 book ai didi

r - 将管道运算符 %>% 与 colnames()<- 等替换函数一起使用

转载 作者:行者123 更新时间:2023-12-03 05:59:13 26 4
gpt4 key购买 nike

如何使用管道运算符通过管道连接到替换函数,如 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

但理想情况下它会是这样的:

averages_df <- 
group_by(mtcars, cyl) %>%
summarise(mean(disp), mean(hp)) %>%
add_colnames(c("cyl", "disp_mean", "hp_mean"))

有没有一种方法可以做到这一点,而无需每次都编写特殊函数?

这里的答案是一个开始,但不完全是我的问题:Chaining arithmetic operators in dplyr

最佳答案

您可以使用colnames<-setNames (感谢@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

或者选择 Alias ( set_colnames ) 来自 magrittr :

library(magrittr)
group_by(mtcars, cyl) %>%
summarise(mean(disp), mean(hp)) %>%
set_colnames(c("cyl", "disp_mean", "hp_mean"))

dplyr::rename如果您仅(重新)命名许多列中的一些列,可能会更方便(它需要同时写入旧名称和新名称;请参阅@Richard Scriven 的答案)

关于r - 将管道运算符 %>% 与 colnames()<- 等替换函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28100780/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com