获取字符串列表:
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")]
一个选项可能是:
strings[map_lgl(strings, ~ !any(str_detect(., avoid_2)))]
[1] "XYZ"