使用%>%替换函数,例如colnames()< -

时间:2015-01-22 23:51:55

标签: r dplyr magrittr

如何使用管道运算符来管道替换函数,如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

3 个答案:

答案 0 :(得分:62)

您可以使用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_colnamesmagrittr):

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

dplyr::rename如果你只是(重新)命名很多列中的一些(它需要写下新旧名称,请参阅@Richard Scriven的回答)可能会更方便。

答案 1 :(得分:17)

dplyr中,有两种方法可以重命名列。

一种是使用rename()功能。在此示例中,您需要回溯由summarise()创建的名称,因为它们是表达式。

group_by(mtcars, cyl) %>%
    summarise(mean(disp), mean(hp)) %>%
    rename(disp_mean = `mean(disp)`, hp_mean = `mean(hp)`)
#   cyl disp_mean   hp_mean
# 1   4  105.1364  82.63636
# 2   6  183.3143 122.28571
# 3   8  353.1000 209.21429

您也可以使用select()。这样做有点容易,因为我们可以使用列号,从而无需使用反向标记。

group_by(mtcars, cyl) %>%
    summarise(mean(disp), mean(hp)) %>%
    select(1, disp_mean = 2, hp_mean = 3)

但是对于这个例子,最好的方法是做@thelatemail在评论中提到的内容,那就是返回一步并命名summarise()中的列。

group_by(mtcars, cyl) %>%
    summarise(disp_mean = mean(disp), hp_mean = mean(hp))

答案 2 :(得分:5)

我们可以使用.funs summarise_at参数和dplyr作为以下代码,为汇总变量添加后缀。

library(dplyr)

# summarise_at with dplyr
mtcars %>% 
  group_by(cyl) %>%
  summarise_at(
    .cols = c("disp", "hp"),
    .funs = c(mean="mean")
  )
# A tibble: 3 × 3
# cyl disp_mean   hp_mean
# <dbl>     <dbl>     <dbl>
# 1     4  105.1364  82.63636
# 2     6  183.3143 122.28571
# 3     8  353.1000 209.21429

另外,我们可以通过多种方式设置列名。

# set_names with magrittr
mtcars %>% 
  group_by(cyl) %>%
  summarise(mean(disp), mean(hp)) %>%
  magrittr::set_names(c("cyl", "disp_mean", "hp_mean"))

# set_names with purrr
mtcars %>% 
  group_by(cyl) %>%
  summarise(mean(disp), mean(hp)) %>%
  purrr::set_names(c("cyl", "disp_mean", "hp_mean"))

# setNames with stats
mtcars %>%
  group_by(cyl) %>%
  summarise(mean(disp), mean(hp)) %>%
  stats::setNames(c("cyl", "disp_mean", "hp_mean"))

# A tibble: 3 × 3
# cyl disp_mean   hp_mean
# <dbl>     <dbl>     <dbl>
# 1     4  105.1364  82.63636
# 2     6  183.3143 122.28571
# 3     8  353.1000 209.21429