Filter by multiple patterns with filter() and str_detect()

隐身守侯 提交于 2019-11-30 17:25:21

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/44759180/filter-by-multiple-patterns-with-filter-and-str-detect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!