【问题标题】:Using tidy evaluation to filter in my own function使用整洁的评估过滤我自己的功能
【发布时间】:2020-10-13 22:54:57
【问题描述】:

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

【问题讨论】:

    标签: r dplyr filtering tidyeval


    【解决方案1】:

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

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

    【讨论】:

    • 您好 Ronak,我能够将您的解决方案实施到我的脚本中。它就像一个魅力。
    【解决方案2】:

    VC 是一个值,而不是一个变量。如果您真的想要,您可以制作您正在寻找的 UI,但这会使您的功能在感觉上非常奇特。如果您想遵循约定,请保留数据框列的数据屏蔽。

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 1970-01-01
      • 2021-01-08
      • 2016-01-28
      • 2018-06-10
      • 2020-04-28
      • 2018-07-18
      • 1970-01-01
      • 2017-11-16
      相关资源
      最近更新 更多