首页 > 解决方案 > 使用整洁的评估过滤我自己的功能

问题描述

在编写自己的函数时,我很难使用整洁的评估。我将使用 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()可以使用它吗?
帮助表示赞赏。

标签: rdplyrfilteringtidyeval

解决方案


您可以使用deparse+substitute将未引用的参数更改为引用的参数。

library(dplyr)

test <- function(df, condition) {
  val <- deparse(substitute(condition))
  df %>% filter(supp %in% val)
}

test(ToothGrowth, VC)

推荐阅读