输入 dplyr::filter() 作为函数的参数

Input dplyr::filter() as argument to function

输入dplyr::filter函数

如何创建一个函数,它接受任何 dplyr::filter 作为输入,returns 满足过滤器的行数?

我试过这样的方法,但不起作用:

library(tidyverse)

filter_function <- function(dataset, filter_text) {
    dataset %>% filter_text %>% nrow() -> n_rows_satisfy_filter

    paste0( "Number of rows satisfying the filter: ", n_rows_satisfy_filter)
}

这里我尝试将过滤器作为字符串输入:

filter_function(iris, "filter( Sepal.Length > 5 & Species == 'setosa' )" )

给出错误:

Error in quote(., filter_text) : 
  2 arguments passed to 'quote' which requires 1 

问题与 相似但不是重复问题,因为当前问题试图改变整个过滤器,而不仅仅是静态过滤器的输入。

试试这个代码,evalenvir 指定的环境中计算 expr 参数,returns 计算值。

library(tidyverse)

filter_function <- function(dataset, filter_text) {
  n_rows_satisfy_filter <- eval(parse(text = filter_text), envir = dataset) %>% nrow()
  paste0( "Number of rows satisfying the filter: ", n_rows_satisfy_filter)
}

filter_function(iris, "filter(dataset, Sepal.Length > 5 & Species == 'setosa' )" )

tidyverse 一起,另一个选项是 parse_expr 来自 rlang

library(dplyr)
filter_function <- function(dataset, filter_text) {
  eval(rlang::parse_expr(filter_text)) %>% 
         nrow() %>%
         paste0( "Number of rows satisfying the filter: ", .)
}

filter_function(iris, "filter(dataset, Sepal.Length > 5 & Species == 'setosa' )" )
#[1] "Number of rows satisfying the filter: 22"