使用filter()和str_detect()过滤多个模式

r6l8ljro  于 2023-11-14  发布在  其他
关注(0)|答案(3)|浏览(181)

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

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

字符串
我尝试了以下做法

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


并收到以下错误
警告消息:在stri_detect_regex(string,pattern,opts_regex = opts(pattern))中:较长的对象长度不是较短对象长度的倍数

slwdgvem

slwdgvem1#

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

  1. df %>%
  2. filter(
  3. str_detect(letters, "a|f|o")
  4. )
  5. # numbers letters
  6. #1 1 a
  7. #2 6 f
  8. #3 15 o
  9. #4 27 a
  10. #5 32 f
  11. #6 41 o

字符串

cuxqih21

cuxqih212#

这可能用“&”而不是“|“(对不起,没有足够的代表发表评论)

5lhxktic

5lhxktic3#

为了更进一步地综合接受的答案,还可以定义一个具有感兴趣的搜索模式的向量,并使用其collapse参数将这些向量与paste连接起来,其中搜索标准“”或“”定义为'|',搜索标准“”和“”定义为'&'
例如,当搜索模式在脚本中的其他地方自动生成或从源读取时,这可能很有用。

  1. #' Changing the column name of the letters column to `lttrs`
  2. #' to avoid confusion with the built-in vector `letters`
  3. df <- data.frame(numbers = 1:52, lttrs = letters)
  4. search_vec <- c('a','f','o')
  5. df %>%
  6. filter(str_detect(lttrs, pattern = paste(search_vec, collapse = '|')))
  7. # numbers letters
  8. #1 1 a
  9. #2 6 f
  10. #3 15 o
  11. #4 27 a
  12. #5 32 f
  13. #6 41 o

字符串

展开查看全部

相关问题