如何使用管道运算符将管道传递给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/

10-12 17:45