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

问题描述 投票:0回答:1

获取字符串列表:

strings <- c("ABC_XZY", "qwe_xyz", "XYZ")

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

avoid <- c("ABC")

我可以这样做

strings %>% 
   .[!map_lgl(., str_detect, avoid)]
[1] "qwe_xyz" "XYZ"

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

avoid_2 <- c("ABC", "qwe")

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

strings %>% 
   .[!map_lgl(., str_detect, avoid_2)]
Error: Result 1 must be a single logical, not a logical vector of length 2 #actually do get

我想要的是

[1] "XYZ"

我理解错误(string的每个元素正在为avoid_2的每个元素生成一个逻辑,总共2个逻辑/元素,map_lgl只能处理一个/元素。

我当然可以分别处理每个子字符串,但我不想-我想列出一个子字符串列表

不需要,但是可以工作

strings %>%
  .[!map_lgl(., str_detect, "ABC")] %>% 
  .[!map_lgl(., str_detect, "qwe")]
r purrr stringr
1个回答
0
投票

一个选项可能是:

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

[1] "XYZ"
© www.soinside.com 2019 - 2024. All rights reserved.