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

查找字符串向量是否包含来自其他向量的任何字符串

  •  1
  • AAAA  · 技术社区  · 7 年前

    有没有一种简单的方法可以确定一个字符串向量是否包含来自其他向量的特定字符串?

    Mail <- c("xxx1@xxx.xx", "xxx2@xxx.xx", "xxx3@yyy.xx", "xxx4@zzz.xx")
    InterestingPublishers <- c("zzz.xx", "xxx.xx")
    

    我曾尝试使用%的百分比,但这适用于整个Faze:

    Mail  %in% InterestingPublishers 
    FALSE FALSE FALSE FALSE
    

    此外,grepl和grep也没有帮助,因为我无法将向量作为输入:

    grepl(InterestingPublishers, Mail)
    Warning message:
    In grepl(InterestingPublishers, Mail) :
      argument 'pattern' has length > 1 and only the first element will be used
    

    有什么简单的方法可以做到这一点吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Sotos    7 年前

    看起来你对这个领域很感兴趣。在这种情况下,我建议删除除域和顶级域之外的所有内容,只需使用 %in% ,即。

    sub('.*@', '', Mail) %in% InterestingPublishers
    
        2
  •  1
  •   s_baldur    7 年前

    d.b 的答案(目前在评论中)完全合理,这是另一个基础- R 使用循环的解决方案(通常速度较慢,但对初学者来说更透明):

    containsi <- integer()
    for (i in InterestingPublishers) {
      containsi <- c(containsi, grep(i, Mail))
    }
    Mail[containsi]
    
    [1] "xxx4@zzz.xx" "xxx1@xxx.xx" "xxx2@xxx.xx"
    

    附:你可能会 a slight speed improvement lapply sapply 的解决方案。

    Mail[unlist(lapply(InterestingPublishers, function(x) grep(x, Mail)))]