使用filter()和str_detect()按多种模式过滤 [英] Filter by multiple patterns with filter() and str_detect()

查看:996
本文介绍了使用filter()和str_detect()按多种模式过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用filter()和str_detect()匹配多个模式来过滤数据帧,而无需多次str_detect()函数调用.在下面的示例中,我想过滤数据框df以仅显示包含字母a fo的行.

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

我尝试了以下

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

并收到以下错误

警告消息:在stri_detect_regex(字符串,模式,opts_regex = opts(pattern)):较长的对象长度不是较短的对象的倍数 物体长度

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

推荐答案

使用filter()和str_detect()完成此操作的正确语法是

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

这篇关于使用filter()和str_detect()按多种模式过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆