【问题标题】:dplyr filter with multiple conditions and OR具有多个条件和 OR 的 dplyr 过滤器
【发布时间】:2025-12-18 14:30:01
【问题描述】:

我有一个大的 tibble,我需要通过过滤来减少它。具体来说,我需要过滤多个条件的不同组合(但都来自同一列)。

我的过滤条件类似于

  filter(str_detect(id, "^M.+(KIT|FLEECE)"), between(f1, 300, 400),  between(f2, 1300, 1400))
 filter(str_detect(id, "^M.+(GOOSE)"), between(f1, 200, 350),  between(f2, 1200, 1400))

当然有效的方法类似于

filtered1<- df %>%
  filter(str_detect(id, "^M.+(KIT|FLEECE)"), between(f1, 300, 400),  between(f2, 1300, 1400))
filtered2<- df %>%
  filter(str_detect(id, "^M.+(GOOSE)"), between(f1, 200, 350),  between(f2, 1200, 1400))
filtered<-bind_rows(filtered1, filtered2)     

我想知道如何将这些与某种 OR 语句结合起来,例如

  filtered<- df %>%
    filter(str_detect(id, "^M.+(KIT|FLEECE)"), between(f1, 300, 400),  between(f2, 1300, 1400)) OR
    filter(str_detect(id, "^M.+(GOOSE)"), between(f1, 200, 350),  between(f2, 1200, 1400))

这是一些样本数据的 MWE

id<-rep(c("M1_1_KIT_1", "M3_2_FLEECE_2", "M2_4_GOOSE_3", "M6_4_KIT_5"), 3)
f1<-sample(200:500, 12)
f2<-sample(1200:1500, 12)
df<-data.frame(id, f1, f2)
df

          id  f1   f2
1     M1_KIT 268 1238
2  M3_FLEECE 270 1459
3   M2_GOOSE 409 1471
4     M4_KIT 344 1337
5     M1_KIT 400 1419
6  M3_FLEECE 210 1379
7   M2_GOOSE 321 1356
8     M4_KIT 478 1284
9     M1_KIT 391 1439
10 M3_FLEECE 382 1317
11  M2_GOOSE 468 1273
12    M4_KIT 306 1270

如果我有一个更通用的解决方案,我会更高兴,比如我将过滤器值放入一个单独的 tibble 并遍历行,但这超出了我的 R 知识范围。

【问题讨论】:

    标签: r filter dplyr tidyverse


    【解决方案1】:

    您可以使用&amp; 将它们放在括号中,然后使用管道| 表示“或”

    df %>%
      filter(
        (str_detect(id, "^M.+(KIT|FLEECE)") & between(f1, 300, 400) & between(f2, 1300, 1400)) |
        (str_detect(id, "^M.+(GOOSE)") & between(f1, 200, 350) & between(f2, 1200, 1400))
      )
    
    

    【讨论】: