r - 使用整洁的评估过滤我自己的功能
问题描述
在编写自己的函数时,我很难使用整洁的评估。我将使用 ToothGrowth 数据集来说明我的问题,我们希望在其中过滤例如 VC 作为补充。
install.packages("tidyverse")
library(tidyverse)
data(ToothGrowth)
test <- function(df, condition) {
df %>% filter(supp %in% condition)
}
test(ToothGrowth, "VC")
这将返回预期的输出,其中数据帧仅包含 VC 作为supp
.
但是,我不想引用函数中的所有参数,这有点复杂,并且需要更多参数。这只是为了证明问题。我被卡住的地方是,这dplyr::filter()
需要引用的论点。我的解决方案是使用ensym()
,所以我可以使用VC
而不是"VC"
。
test <- function(df, condition) {
condition <- ensym(condition)
df %>% filter(supp %in% condition)
}
test(ToothGrowth, VC)
Fehler: Problem with `filter()` input `..1`.
x 'match' benötigt Vektoren als Argumente
ℹ Input `..1` is `supp %in% condition`.
到目前为止,我已经尝试过quo()
,但无法使其正常工作..enquo()
sym()
ensym()
有没有办法为我的函数提供一个不带引号的参数并在函数中引用它,所以dplyr::filter()
可以使用它吗?
帮助表示赞赏。
解决方案
您可以使用deparse
+substitute
将未引用的参数更改为引用的参数。
library(dplyr)
test <- function(df, condition) {
val <- deparse(substitute(condition))
df %>% filter(supp %in% val)
}
test(ToothGrowth, VC)
推荐阅读
- jquery - jQuery:window.timer 对多个元素使用 setTimeout 和 setInterval 时出现问题
- r - R 中的 revoScaleR::rxGlm() 问题 - GLM 残差
- python - 我怎样才能使我的信号工作并解决这个问题?
- qt - 在 QML 文本元素中启用“elide”属性,但在从右到左的用户界面中
- c++ - 为什么分配动态内存时虚拟内存没有减少
- c - 即使我输入了一个数字,为什么我的代码仍然返回 1 和错误消息?
- react-native - 获取参数问题反应原生
- c# - 在不同的 efpt.renaming.json 文件中重命名 .net 核心应用程序
- python - 图例有时具有重复值
- c++ - 如何返回指针函数?