r - 使用 I 字符串来引用 dplyr 中的变量?
问题描述
假设我有以下数据:
test_df <- data.frame(a=rnorm(100), b=rnorm(100))
以下作品:
test_df %>%
summarise(y = mean(a))
现在假设a
我不想传递一个字符串
string_outcome <- "a" # I want to use this
test_df %>%
summarise(y = mean(string_outcome))
那是行不通的。我尝试使用!!string_outcome
,但这也不起作用。我怎样才能解决这个问题?
解决方案
因为它是一个字符串,所以将其转换为符号 ( sym
from rlang
) 并计算 ( !!
)
test_df %>%
summarise(y = mean(!! rlang::sym(string_outcome)))
或者使用which 可以在参数summarise_at
中接受字符串vars
test_df %>%
summarise_at(vars(string_outcome), list(y = ~ mean(.)))
或者如果我们需要一个没有任何属性的单一值,即使pull
withmean
也可以使用
test_df %>%
pull(string_outcome) %>%
mean
推荐阅读
- node.js - 处理大量记录会产生 OutOfMemoryException - Kafka REST 代理
- nativescript - 使用 NativeScript Sidekick 构建应用程序时收到“无法安装应用程序”
- html - 带有内联 CSS 的垂直时间线
- google-sheets - 与条件匹配但最后一行的所有行的 AverageIF
- d - 如何在 D 中使用 tolow
- c++ - 在 C++ 中检查特定的命令行参数
- wordpress - 具有可变产品的 Woocommerce CSV 失败
- django - 发生 VsCode 异常:VariableDoesNotExist
- ios - 如何在文本字段中添加或删除前缀为“减号”的符号?
- javascript - 如何为两人一组选择项目