【问题标题】:Determine which elements of a vector partially match a second vector, and which elements don't (in R)确定向量的哪些元素部分匹配第二个向量,哪些元素不匹配(在 R 中)
【发布时间】:2021-11-18 03:47:20
【问题描述】:

我有一个向量A,其中包含一个属列表,我想用它来子集第二个向量B。我已成功使用 grepl 从B 中提取与A 中的属部分匹配的任何内容。下面是我所做的一个可重现的示例。

但现在我想获得A 中的哪个属与B 中的某些内容匹配的列表,以及哪个属不匹配的列表。 IE。 “匹配”列表将包含 Cortinarius 和 Russula,而“不匹配”列表将包含 Laccaria 和 Inocybe。关于如何做到这一点的任何想法?实际上,我的向量很长,B 中的属名在其他信息中并不完全相同。

# create some dummy vectors
A <- c("Cortinarius","Laccaria","Inocybe","Russula")
B <- c("fafsdf_Cortinarius_sdfsdf","sdfsdf_Russula_sdfsdf_fdf","Tomentella_sdfsdf","sdfas_Sebacina","sdfsf_Clavulina_sdfdsf")

# extract the elements of B that have a partial match to anything in A.
new.B <- B[grepl(paste(A,collapse="|"), B)]

# But now how do I tell which elements of A were present in B, and which ones were not?

【问题讨论】:

    标签: r grepl


    【解决方案1】:

    您可以使用sapplygrepl 来检查A 的每个值是否与B 的值匹配。

    sapply(A, grepl, B)
    
    #     Cortinarius Laccaria Inocybe Russula
    #[1,]        TRUE    FALSE   FALSE   FALSE
    #[2,]       FALSE    FALSE   FALSE    TRUE
    #[3,]       FALSE    FALSE   FALSE   FALSE
    #[4,]       FALSE    FALSE   FALSE   FALSE
    #[5,]       FALSE    FALSE   FALSE   FALSE
    

    您可以按列对这些值求和以获取匹配数。

    result <- colSums(sapply(A, grepl, B))
    result
    
    #Cortinarius    Laccaria     Inocybe     Russula 
    #          1           0           0           1 
    
    #values with at least one match
    names(Filter(function(x) x > 0, result))
    #[1] "Cortinarius" "Russula" 
    
    #values with no match
    names(Filter(function(x) x == 0, result))
    #[1] "Laccaria" "Inocybe" 
    

    【讨论】:

      【解决方案2】:

      我们可以使用lapplysapply 循环遍历这些模式,然后得到一个命名输出

      out <- setNames(lapply(A, function(x) grep(x, B, value = TRUE)), A)
      

      那么,更容易检查返回空元素的那些

      > out[lengths(out) > 0]
      $Cortinarius
      [1] "fafsdf_Cortinarius_sdfsdf"
      
      $Russula
      [1] "sdfsdf_Russula_sdfsdf_fdf"
      
      > out[lengths(out) == 0]
      $Laccaria
      character(0)
      
      $Inocybe
      character(0)
      

      并获取其中的names

      > names(out[lengths(out) > 0])
      [1] "Cortinarius" "Russula"    
      > names(out[lengths(out) == 0])
      [1] "Laccaria" "Inocybe" 
      

      【讨论】:

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