【发布时间】:2018-03-08 10:35:34
【问题描述】:
我想在字符串向量中找到第一次出现的模式向量的元素,并获取这些字符串的输出向量,其中不匹配项应分配给NA。此外,我想为这个问题使用一个紧凑的矢量化解决方案(最好是一个 tidyverse 解决方案)。
library(stringr)
library(purrr)
例子:
patterns1 <- c("101", "102", "103", "101")
patterns2 <- c("101", "102", "103", "999", "101")
strings <- c("101a", "101a", "a102a", "aa103a")
对于patterns1,这是可行的,因为每个元素都存在于strings:
map_chr(patterns1, function(x) detect(strings, str_detect, x))
# [1] "101a" "a102a" "aa103a" "101a"
但是patterns2 map_chr 会报错:
map_chr(patterns2, function(x) detect(strings, str_detect, x))
# Error: Result 4 is not a length 1 atomic vector
因为如果检测失败,detect 将返回 NULL。或者您是否建议使用map 而不是map_chr 的解决方法并将NULL 元素转换为NA?
map(patterns2, function(x) detect(strings, str_detect, x))
# [[1]]
# [1] "101a"
#
# [[2]]
# [1] "a102a"
#
# [[3]]
# [1] "aa103a"
#
# [[4]]
# NULL
#
# [[5]]
# [1] "101a"
【问题讨论】: