首页 > 解决方案 > 如何将 dplyr 中的“摘要”与动态列名一起使用?

问题描述

我正在使用summarizeR 中 dplyr 包中的函数从表中总结组均值。我想动态地执行此操作,使用存储在另一个变量中的列名字符串。

以下是“正常”的方式,它当然有效:

myTibble <- group_by( iris, Species)
summarise( myTibble, avg = mean( Sepal.Length))

# A tibble: 3 x 2
  Species     avg
  <fct>      <dbl>
1 setosa      5.01
2 versicolor  5.94
3 virginica   6.59

但是,我想做这样的事情:

myTibble <- group_by( iris, Species)
colOfInterest <- "Sepal.Length"
summarise( myTibble, avg = mean( colOfInterest))

我已经阅读了Programming with dplyr页面,我尝试了一堆 , , , 等的组合quoenquo!!.dots=(...)还没有找到正确的方法。

我也知道这个答案,但是,1)当我使用标准评估函数standardise_时,R 告诉我它已被贬值,并且 2)这个答案似乎一点也不优雅。那么,有没有一种好的、简单的方法来做到这一点?

谢谢!

标签: rdplyrsummarize

解决方案


1)像这样使用!!sym(...)

colOfInterest <- "Sepal.Length"
iris %>% 
  group_by(Species) %>%
  summarize(avg = mean(!!sym(colOfInterest))) %>%
  ungroup

给予:

# A tibble: 3 x 2
  Species      avg
  <fct>      <dbl>
1 setosa      5.01
2 versicolor  5.94
3 virginica   6.59

2)第二种方法是:

colOfInterest <- "Sepal.Length"
iris %>% 
  group_by(Species) %>%
  summarize(avg = mean(.data[[colOfInterest]])) %>%
  ungroup

当然,这在基础 R 中是直截了当的:

aggregate(list(avg = iris[[colOfInterest]]), iris["Species"], mean)

推荐阅读