代码之家  ›  专栏  ›  技术社区  ›  Dambo

如何测试向量中的每个值是否与字符串向量中的任何值匹配?

  •  0
  • Dambo  · 技术社区  · 8 年前

    我想用 str_detect 测试每个值 fruit 向量是否匹配 strings .

    fruit <- c("apple", "banana", "pear", "pinapple")
      strings <- c("apple", "app", "pear", "apple", "app", "pear", "apple", "app", "pear")
    

    这样做的目的是:

    > map_chr(fruit, ~any(str_detect(.x, strings)))
    [1] "TRUE"  "FALSE" "TRUE"  "TRUE" 
    

    但是我想知道是否有一种方法可以用矢量化的更简洁的形式来写它。 str_检测 .比如:

      str_detect(fruit, strings)  
    
    [1]  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE FALSE
    Warning message:
    In stri_detect_regex(string, pattern, opts_regex = opts(pattern)) :
      longer object length is not a multiple of shorter object length
    

    但是我在找长度的输出 length(fruit) 而不是9。

    2 回复  |  直到 8 年前
        1
  •  2
  •   MKR    8 年前

    您有许多选择来实现适当的解决方案。

    选项1: 使用 %in% 操作人员

    fruit %in% strings
    
    #[1]  TRUE FALSE  TRUE FALSE
    

    选项2: 使用 str_detect

    library(stringr)
    
    # Make sure to use \b around each word to avoid partial matching.
    str_detect(fruit, pattern = paste("\\b",strings,"\\b", sep="", collapse = "|"))
    #[1]  TRUE FALSE  TRUE FALSE
    
        2
  •  1
  •   Onyambu    8 年前

    香蕉和菠萝应该是假的,因为它们不在弦中:

    str_detect(fruit,str_c("\\b(",strings,")\\b",collapse = "|"))
    
    [1]  TRUE FALSE  TRUE FALSE