在R中使用多个条件过滤条件

时间:2020-10-22 21:33:44

标签: r filter dplyr

我试图在一个数据帧上使用多个条件过滤器,但是当同时使用过滤器(来自下拉选择框)时,实际上只应用其中一个过滤器,而忽略第二个过滤器。我看不到有什么问题,并尝试了ifelse,它给出了相同的结果

# seed values 
item_levels <-c("alpha","beta","omega","omega","beta","alpha","omega")
prod_types <- c("production","development","test","example","test","test","test")
sample <-data.frame(item_levels,prod_types) 

# simulate inputs
selected_item = "omega"
selected_type = "test"


sample   %>%  
  filter(if(selected_item != "all"){
    item_levels == selected_item
  }else{1==1} & 
    if(selected_type != "all"){
      prod_types == selected_type
    }else{1==1}
  ) 
# Further calculations would be done after this filter - groupings , sum etc 


这给出了一个结果集 item_levels产品类型 1欧米茄测试 2欧米茄的例子 3欧米茄测试

我知道SQL中的等效语言是

WHERE IF(@selected_item != "all" , item_levels  =  @selected_item , 1 = 1  ) AND 
IF(@selected_type != "all" , prod_types =  @selected_item , 1 = 1  )

在这里我是否缺少明显的东西?我知道我可以应用几个过滤器并将它们通过管道连接在一起,但是当有多个过滤器时,这加起来了,我想尽可能避免

1 个答案:

答案 0 :(得分:0)

一种解决方案可能是使用一个辅助函数来为您进行base+((result/100)*base) 比较:

all

这不仅解决了您的问题,而且扩展到更多过滤器也更加简洁,因为您只需向compare_all = function(selected, to_compare) { if(selected != "all") { to_compare == selected } else { # Get a vector of only `TRUE` with the same length as `to_compare` rep_along(to_compare, TRUE) } } sample %>% filter(compare_all(selected_item, item_levels) & compare_all(selected_type, prod_types)) 添加更多调用即可。