我想在字符串向量中找到第一个出现的模式向量元素,并获得这些字符串的输出向量,其中非匹配应分配给NA
。另外,我想为这个问题使用紧凑的矢量化解决方案(最好是一个整体解决方案)。
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"
答案 0 :(得分:1)
我们可以创建一个条件
map_chr(patterns2, ~ detect(strings, str_detect, .x) %>%
if(length(.) > 0) . else NA)
#[1] "101a" "a102a" "aa103a" NA "101a"
或与NA
连接并获取first
值
map_chr(patterns2, ~ c(detect(strings, str_detect, .x), NA)[1])
#[1] "101a" "a102a" "aa103a" NA "101a"