R 用字符串向量映射模式向量

R 用字符串向量映射模式向量,r,tidyverse,stringr,purrr,R,Tidyverse,Stringr,Purrr,我希望在字符串向量中找到模式向量元素的第一个匹配项,并获得这些字符串的输出向量,其中非匹配项应分配给NA。此外,我想使用一个紧凑的矢量化解决方案来解决这个问题(最好是tidyverse解决方案) 例如: patterns1 <- c("101", "102", "103", "101") patterns2 <- c("101", "102", "103", "999", "101") strings <- c("101a", "101a", "a102a", "aa103a"

我希望在字符串向量中找到模式向量元素的第一个匹配项,并获得这些字符串的输出向量,其中非匹配项应分配给
NA
。此外,我想使用一个紧凑的矢量化解决方案来解决这个问题(最好是tidyverse解决方案)

例如:

patterns1 <- c("101", "102", "103", "101")
patterns2 <- c("101", "102", "103", "999", "101")
strings <- c("101a", "101a", "a102a", "aa103a")
但是使用
patterns 2
map\u 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\u 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"

我们可以创造一个条件

map_chr(patterns2, ~ detect(strings, str_detect, .x) %>% 
                               if(length(.) > 0) . else NA)
#[1] "101a"   "a102a"  "aa103a" NA       "101a"  

或者与
NA
连接,并取
第一个

map_chr(patterns2, ~ c(detect(strings, str_detect, .x), NA)[1])
#[1] "101a"   "a102a"  "aa103a" NA       "101a"  
map_chr(patterns2, ~ detect(strings, str_detect, .x) %>% 
                               if(length(.) > 0) . else NA)
#[1] "101a"   "a102a"  "aa103a" NA       "101a"  
map_chr(patterns2, ~ c(detect(strings, str_detect, .x), NA)[1])
#[1] "101a"   "a102a"  "aa103a" NA       "101a"