【发布时间】:2020-03-16 19:51:55
【问题描述】:
获取字符串列表:
strings <- c("ABC_XZY", "qwe_xyz", "XYZ")
我想获取strings 中不包含特定子字符串的所有元素
avoid <- c("ABC")
我能做到
library(stringr)
library(dplyr)
library(purrr)
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
我想要的是
[1] "XYZ"
错误很明显 - string 的每个元素正在为 avoid_2 的每个元素生成一个逻辑,总共 2 个逻辑/元素,map_lgl 只能处理一个/元素。
我当然可以单独处理每个子字符串,但我不想 - 我想制作一个子字符串列表
不想要,但确实有效
strings %>%
.[!map_lgl(., str_detect, "ABC")] %>%
.[!map_lgl(., str_detect, "qwe")]
【问题讨论】: