简体   繁体   English

通过 R 中的多个条件进行复杂过滤

[英]complex filter by multiple conditions in R

I am trying to filter a df based on multiple conditions:我正在尝试根据多个条件过滤 df:

This is part of my df:这是我的 df 的一部分:

     cym    isop   macr    pin   mvk    euc  t_2m  hour   day month  BVOC  AVOC isop_ox monoterpenes
   <dbl>   <dbl>  <dbl>  <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>   <dbl>        <dbl>
 1 1.56  NA      0.570  0.0482 7.27  NA      28.7    14     6     2  9.45 5.21    7.84         1.61 
 2 1.05  NA      0.320  0.0225 6.77  NA      27.3    16     6     2  8.16 2.93    7.09         1.07 
 3 0.560  0.559  0.122  0.0144 1.48   2.01   26.4    17     6     2  4.74 1.87    2.16         2.58 
 4 0.402  0.276  0.0795 0.0113 0.431  0.87   25.4    18     6     2  2.07 1.29    0.787        1.28 
 5 0.325  0.0624 0.0416 0.0148 0.360  0.853  24.8    19     6     2  1.66 1.05    0.464        1.19 
 6 0.297  0.699  0.131  0.0197 3.92   0.995  25.6     8     7     2  6.06 1.59    4.75         1.31 
 7 0.218  0.565  0.213  0.012  5.67   0.593  26.5     9     7     2  7.27 1.17    6.45         0.823
 8 0.144  0.666  0.174  0.006  6.57   0.458  29.1    11     7     2  8.02 0.687   7.41         0.608
 9 0.274  1.58   0.255  0.0098 6.73   0.664  29.7    13     7     2  9.51 1.12    8.56         0.948
10 0.187  0.952  0.156  0.0062 3.22   0.355  28.7    14     7     2  4.88 0.797   4.33         0.549

I want to use different conditions based on the month column like this:我想根据月份列使用不同的条件,如下所示:

day_data_f <- wd_filter_data%>%
   select(cym, isop, macr,pin,mvk,euc,t_2m,hour,day,month,
         BVOC, AVOC,isop_ox,monoterpenes,Month)%>%
   filter(month==2, between(hour,6,21)) 

The problem is that I want to apply multiple conditions depending on the month column value.问题是我想根据月份列值应用多个条件。 eg:例如:

filter(month==3, between(hour,6,20))
filter(month==5, between(hour,6,17))
filter(month==6, between(hour,7,17))

Is there a way to apply all this filters at once?有没有办法一次应用所有这些过滤器?

You can combine the conditions using OR ( | ) operator.您可以使用 OR ( | ) 运算符组合条件。

library(dplyr)

wd_filter_data %>%
  filter(month == 2 & between(hour,6,21) | 
         month == 3 & between(hour,6,20) | 
         month == 5 & between(hour,6,17) | 
         month == 6 & between(hour,7,17)) 

We could create the logical vector with pmap我们可以用pmap创建逻辑向量

library(purrr)
library(dplyr)
pmap(list(c(2:3, 5:6), rep(c(6, 7), c(3, 1)), c(21, 20, 17, 17)), 
           ~  (data$month == ..1) & between(data$hour, ..2, ..3)) %>%
 reduce(`|`) %>%
 filter(wd_filter_data, .)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM