r - 如何将 dplyr 中的“摘要”与动态列名一起使用?
问题描述
我正在使用summarize
R 中 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页面,我尝试了一堆 , , , 等的组合quo
,enquo
但!!
我.dots=(...)
还没有找到正确的方法。
我也知道这个答案,但是,1)当我使用标准评估函数standardise_
时,R 告诉我它已被贬值,并且 2)这个答案似乎一点也不优雅。那么,有没有一种好的、简单的方法来做到这一点?
谢谢!
解决方案
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)
推荐阅读
- sql-server - 无法修复 sql 查询中的语法错误
- java - 致命异常:java.lang.OutOfMemoryError
- portal - 如何删除嵌套 for 循环中最后一个对象的逗号?
- django - 如何用列表元素索引表单集输入字段
- replace - R中的colnames和变量在两个data.frames之间进行条件替换
- android - listAll 在 Sugarrecord 中需要很长时间?
- python - 如何相互比较每个列表的每个项目?等等 ['3','3', '1', '0.05'] ['5', '2', '4', '0.05'] 如果 3 等于 5?
- php - 如何使用 Laravel 验证来自 Microsoft Azure AD 的数据并将其重定向到主页?
- hive - 有没有办法在保留另一个 Hive 表的顺序的同时插入 Hive 表
- xcode - Xcode 身份验证失败,因为将 iOS 版本更改为 14 后未提供凭据