具有多个条件和或

时间:2019-05-23 14:16:06

标签: filter dplyr tidyverse

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

我的过滤条件类似于

  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

对于一个更通用的解决方案,我会更加满意,例如将过滤器值放入单独的小节中并在行中进行迭代,但这超出了我的R知识。

1 个答案:

答案 0 :(得分:0)

您可以使用[22-May-2019 14:53:19 UTC] PHP Fatal error: Uncaught Error: Class 'App\Cactus' not found in /home/bradleyi/public_html/wp-content/themes/unidash/header.php:20 Stack trace: #0 /home/bradleyi/public_html/wp-includes/template.php(704): require_once() #1 /home/bradleyi/public_html/wp-includes/template.php(653): load_template('/home/bradleyi/...', true) #2 /home/bradleyi/public_html/wp-includes/general-template.php(41): locate_template(Array, true) #3 /home/bradleyi/public_html/wp-content/plugins/modern-events-calendar/templates/taxonomy-mec-category.php(12): get_header('mec') #4 /home/bradleyi/public_html/wp-includes/template-loader.php(140): include('/home/bradleyi/...') #5 /home/bradleyi/public_html/wp-blog-header.php(19): require_once('/home/bradleyi/...') #6 /home/bradleyi/public_html/index.php(17): require('/home/bradleyi/...') #7 {main} thrown in /home/bradleyi/public_html/wp-content/themes/unidash/header.php on line 20 将其放在括号中,然后使用管道&来表示“或”

|