Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_detect for multiple patterns

Tags:

stringr

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".

like image 756
SteveM Avatar asked Jul 21 '26 13:07

SteveM


1 Answers

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  
like image 74
Taylor Avatar answered Jul 28 '26 16:07

Taylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!