【问题标题】:map pattern vector with string vector带字符串向量的地图模式向量
【发布时间】: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"

【问题讨论】:

    标签: r tidyverse stringr purrr


    【解决方案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"  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多