5

I am using str_detect within the stringr package and I am having trouble searching a string with more than one pattern.

Here is the code I am using, however it is not returning anything even though my vector ("Notes-Title") contains these patterns.

filter(str_detect(`Notes-Title`, c("quantity","single")))

The logic I want to code is:

Search each row and filter it if it contains the string "quantity" or "single".

SteveM
  • 213
  • 3
  • 13

1 Answers1

9

You need to use the | separator in your search, all within one set of "".

> words <- c("quantity", "single", "double", "triple", "awful")
> set.seed(1234)
> df = tibble(col = sample(words,10, replace = TRUE))
> df
# A tibble: 10 x 1
   col     
   <chr>   
 1 triple  
 2 single  
 3 awful   
 4 triple  
 5 quantity
 6 awful   
 7 triple  
 8 single  
 9 single  
10 triple 

> df %>% filter(str_detect(col, "quantity|single"))
# A tibble: 4 x 1
  col     
  <chr>   
1 single  
2 quantity
3 single  
4 single  
Taylor
  • 171
  • 2
  • Taylor - thanks but this doesn't work for me. It only seems to work for individual character searches. If I write "q|s" it matches, but matches everything that has a q or an s in it. If it write "quanitity|single" it matches with nothing. – SteveM Nov 16 '19 at 02:02
  • @SteveM Sorry I wasn't clear in my toy example. I've changed the dataset so that you can see how the | operator works with `str_detect` – Taylor Nov 16 '19 at 02:18
  • this worked. Thanks. One other question though...how do I make it case insensitive? I tried using fixed("quantity|multiple", ignore_case = TRUE) but that does not seem to work – SteveM Nov 16 '19 at 04:39
  • i don't know if there's an easy way to do that unfortunately. you can either add in additional query, e.g., "(quantity|Quantity|single|Single)" or you can mutate the column ahead of the filter `mutate(col = tolower(col))` in order to drop capitalization – Taylor Nov 16 '19 at 20:10