本文介绍了将%>%与colnames()<-的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用管道运算符将管道函数插入诸如 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?

这是一个开始,但不完全是我的问题tion:

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 别名 set_colnames ) / code>:

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)

这篇关于将%&gt;%与colnames()&lt;-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 23:17