如何以编程方式提供要通过 dplyr 和 filter_ 应用的过滤器列表

How to programmatically provide a list of filters to apply via dplyr and filter_

我想创建一个过滤器列表以应用于数据框。类似于:

filters = list(cyl=4, am=1)

然后将其应用于 'mtcars' 数据框,以获取 cyl=4 和 am=1 的记录。我可以这样做:

filter_(mtcars, 
        lazyeval::interp(~ val == var, val = as.name(names(filters[1])), 
                                       var = filters[[1]]))

但这只会选取过滤器列表中的第一个条目。

应用所有过滤器的惯用方法是什么?

(我正在尝试创建一个有点通用的函数,它可以接受一个数据框和一个标准集,并将输出转换。现在,平等对于标准来说很好,但更通用的习语会更好)

将过滤器定义为

filter1 <- ~(cyl==4 & am==1)

filter1 <- "cyl==4 & am==1"

library(lazyeval)
filter1 <- lazy(cyl==4 & am==1)

并用作

mtcars %>% filter_(filter1)

函数示例:

get_cars_with_filter <- function(my_filter) {
  mtcars %>% filter_(lazy(my_filter))
}

get_cars_with_filter(cyl==4 & am == 1)
    data <- mtcars
    attach(data)

    ##function to create data subset applying necessary filters
     myfunction <- function(myfilter){
     newdata <- data[myfilter,]
     print(newdata)
     }

     ##calling function
     myfunction(cyl==4 & am==1)
     myfunction(mpg >20 & gear > 1)


     Output
    > myfunction(cyl==4 & am==1)

                   mpg    cyl  disp   hp drat wt    qsec  vs am gear carb
    Datsun 710     22.8   4    108.0  93 3.85 2.320 18.61  1  1    4    1
    Fiat 128       32.4   4    78.7   66 4.08 2.200 19.47  1  1    4    1
    Honda Civic    30.4   4    75.7   52 4.93 1.615 18.52  1  1    4    2
    Toyota Corolla 33.9   4    71.1   65 4.22 1.835 19.90  1  1    4    1
    Fiat X1-9      27.3   4    79.0   66 4.08 1.935 18.90  1  1    4    1
    Porsche 914-2  26.0   4    120.3  91 4.43 2.140 16.70  0  1    5    2
    Lotus Europa   30.4   4    95.1   113 3.77 1.513 16.90 1  1    5    2
    Volvo 142E     21.4   4    121.0  109 4.11 2.780 18.60 1  1    4    2 

这里的所有答案都很好,但是如果您严格地想保留您定义过滤器的原始方式(通过列表),您可以简单地将它转换为字符串并将其传递给 filter_,例如 [=12] =]

filter_(mtcars, paste(names(filters), filters, sep = "==", collapse = "&"))

(额外的好处是,这允许在您使用的逻辑运算符方面具有灵活性,例如,可以将折叠更改为“|”等)