将 str_detect 映射到字符串列表以检测第二个字符串列表

Gre*_*reg 2 r stringr purrr

获取字符串列表:

strings <- c("ABC_XZY", "qwe_xyz", "XYZ")
Run Code Online (Sandbox Code Playgroud)

我想获取其中strings不包含特定子字符串的所有元素

avoid <- c("ABC")
Run Code Online (Sandbox Code Playgroud)

我可以做这个

library(stringr)
library(dplyr)
library(purrr)

strings %>% 
   .[!map_lgl(., str_detect, avoid)]
[1] "qwe_xyz" "XYZ"
Run Code Online (Sandbox Code Playgroud)

我想做的是指定几个子字符串

avoid_2 <- c("ABC", "qwe")
Run Code Online (Sandbox Code Playgroud)

然后像以前一样映射列表(不起作用)

strings %>% 
   .[!map_lgl(., str_detect, avoid_2)]
Error: Result 1 must be a single logical, not a logical vector of length 2
Run Code Online (Sandbox Code Playgroud)

我想要的是

[1] "XYZ"
Run Code Online (Sandbox Code Playgroud)

错误很明显 - 的每个元素都string为 的每个元素生成一个逻辑avoid_2,总共 2 个逻辑/元素,并且map_lgl只能处理一个/元素。

我当然可以单独处理每个子字符串,但我不想 - 我想制作一个子字符串列表

不想要,但确实有效

strings %>%
  .[!map_lgl(., str_detect, "ABC")] %>% 
  .[!map_lgl(., str_detect, "qwe")]
Run Code Online (Sandbox Code Playgroud)

tmf*_*mnk 5

一种选择可能是:

strings[map_lgl(strings, ~ !any(str_detect(., avoid_2)))]

[1] "XYZ"
Run Code Online (Sandbox Code Playgroud)

或者直接执行:

strings[!str_detect(strings, paste(avoid_2, collapse = "|"))]
Run Code Online (Sandbox Code Playgroud)