簡體   English   中英

如何通過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_ like

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

(附加的好處是,這允許您使用的邏輯運算符具有靈活性,例如可以將折疊更改為“|”等)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM