【问题标题】:grepl() - Partial string matching after a symbolgrepl() - 符号后的部分字符串匹配
【发布时间】:2017-02-01 21:08:33
【问题描述】:

我有 2 个字符向量:

Long <- c("d4@NHL1", "d7@NHL2", "d4@NHL3", "d7@NHL4", "d7@NHL5", "d9@NHL6")
Short <- c("NHL1", "NHL3", "NHL6", "NHL5")

我需要检查 Long 向量中的哪些字符串部分匹配 Short 向量中的字符串,从 @ 符号开始。结果我需要得到一个逻辑向量。

我想我需要使用grepl() 函数,像这样:

sapply(Long, function(x) grepl(x, paste(Short, collapse = "")))

我不知道在grepl() 函数中使用什么作为模式,或者在符号之后是否有任何参数开始匹配。

【问题讨论】:

  • grepl(paste(Short, collapse = '|'), Long) 应该这样做 imo
  • 另一种选择:gsub('.*@','',Long) %in% Short

标签: r string-matching


【解决方案1】:

借鉴another stackoverflow response的方法:

Long <- c("d4@NHL1", "d7@NHL2", "d4@NHL3","d7@NHL4", "d7@NHL5", "d9@NHL6")
Short <- c("NHL1", "NHL3", "NHL6", "NHL5")
matches <- grep(paste0("*@",Short,collapse="|"), 
                Long, value=TRUE)

* 匹配@ 之前的任意数量的字符

【讨论】:

    猜你喜欢
    • 2012-06-15
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多