使用整洁的评估来过滤我自己的功能
Using tidy evaluation to filter in my own function
我在编写自己的函数时很难使用 tidy evaluation。
我将使用 ToothGrowth 数据集来说明我的问题,我们要在其中过滤例如VC作为补充。
install.packages("tidyverse")
library(tidyverse)
data(ToothGrowth)
test <- function(df, condition) {
df %>% filter(supp %in% condition)
}
test(ToothGrowth, "VC")
此 returns 预期输出,其中数据帧仅包含 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)
VC
是一个值,不是变量。如果你真的想要,你可以制作你正在寻找的 UI ,但这会使你的功能在感觉上非常奇特。如果您想遵循约定,请为数据框列保留 data-masking。
我在编写自己的函数时很难使用 tidy evaluation。 我将使用 ToothGrowth 数据集来说明我的问题,我们要在其中过滤例如VC作为补充。
install.packages("tidyverse")
library(tidyverse)
data(ToothGrowth)
test <- function(df, condition) {
df %>% filter(supp %in% condition)
}
test(ToothGrowth, "VC")
此 returns 预期输出,其中数据帧仅包含 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)
VC
是一个值,不是变量。如果你真的想要,你可以制作你正在寻找的 UI ,但这会使你的功能在感觉上非常奇特。如果您想遵循约定,请为数据框列保留 data-masking。