15

I would like to filter a dataframe using filter() and str_detect() matching for multiple patterns without multiple str_detect() function calls. In the example below I would like to filter the dataframe df to show only rows containing the letters a f and o.

df <- data.frame(numbers = 1:52, letters = letters)
df %>%
    filter(
        str_detect(.$letters, "a")|
        str_detect(.$letters, "f")| 
        str_detect(.$letters, "o")
    )
#  numbers letters
#1       1       a
#2       6       f
#3      15       o
#4      27       a
#5      32       f
#6      41       o

I have attempted the following

df %>%
    filter(
        str_detect(.$letters, c("a", "f", "o"))
     )
#  numbers letters
#1       1       a
#2      15       o
#3      32       f

and receive the following error

Warning message: In stri_detect_regex(string, pattern, opts_regex = opts(pattern)) : longer object length is not a multiple of shorter object length

user6571411
  • 2,749
  • 4
  • 16
  • 29

2 Answers2

47

The correct syntax to accomplish this with filter() and str_detect() would be

df %>%
  filter(
      str_detect(letters, "a|f|o")
  )
#  numbers letters
#1       1       a
#2       6       f
#3      15       o
#4      27       a
#5      32       f
#6      41       o
user6571411
  • 2,749
  • 4
  • 16
  • 29
  • 1
    Corrected, thank you. Always learning. I have been using case_when() and became confused – user6571411 Jun 26 '17 at 12:00
  • If this is the correct syntax, it strikes me that `str_detect()` is intended for more limited situations than I had supposed. What function would be recommended if you were looking for partial matching against a longer list of longer strings? Back to `grep`? – dhd Aug 30 '22 at 01:21
0

Is this possible with an "&" rather an "|" (sorry dont have enough rep for comment)

Nana
  • 13
  • 2
  • 1
    This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/33089656) – xilliam Nov 03 '22 at 07:54