使用filter()和str_detect()根据多个模式进行筛选

15

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

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(string,pattern,opts_regex = opts(pattern))中:较长的对象长度不是较短对象长度的倍数

3个回答

47

使用filter()和str_detect()实现此目的的正确语法应为

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

1
已更正,谢谢。不断学习中。我一直在使用case_when(),但有些困惑。 - user6571411
如果这是正确的语法,我觉得 str_detect() 的用途比我想象的更为有限。如果您想在长字符串列表中进行部分匹配,推荐使用哪个函数?回到 grep 吗? - dhd

0

用 "&" 而不是 "|" 可以实现这个吗?(抱歉我没有足够的声望来评论)


1
这并没有真正回答问题。如果您有不同的问题,可以通过点击提问来提出。如果您想在此问题获得新的答案时得到通知,您可以关注此问题。一旦您拥有足够的声望,您还可以添加悬赏以吸引更多关注。- 来自审核 - xilliam

0
为了进一步综合接受的答案,还可以定义一个包含感兴趣的搜索模式的向量,并使用paste函数将它们连接起来,其中搜索条件'or'被定义为'|',搜索条件'and'被定义为'&'
例如,当搜索模式在脚本的其他地方自动生成或从源读取时,这将非常有用。
#' Changing the column name of the letters column to `lttrs`
#' to avoid confusion with the built-in vector `letters`
df <- data.frame(numbers = 1:52, lttrs = letters)

search_vec <- c('a','f','o')
df %>% 
    filter(str_detect(lttrs, pattern = paste(search_vec, collapse = '|')))

#  numbers letters
#1       1       a
#2       6       f
#3      15       o
#4      27       a
#5      32       f
#6      41       o

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接