【问题标题】:Compare 2 strings in R比较R中的2个字符串
【发布时间】:2020-08-21 19:02:19
【问题描述】:

我的数据如下:

vec <- c("ABC|ADC|1","ABC|ADG|2")

我需要检查以下子字符串是否存在 “ADC|DFG”,它应该为此返回 false,因为我需要匹配精确的模式。 "ABC|ADC|1|5" 应该返回 True,因为这是向量中第一个元素的子元素。 我尝试使用 grepl,但如果我也只通过 ADC,它会返回 true,不胜感激。

【问题讨论】:

  • 你能显示一个匹配的示例字符串吗
  • akrun - 例如,应该给出 TRUE 的字符串是 "ABC|ADC","ABC|ADC|1|2","ABC|ADG","ABC|ADG|2|5"
  • IceCreamToucan - 对于字符串“ABC|ADC”,它应该为 TRUE,但对于“ADC|1”,它应该为 false。

标签: r


【解决方案1】:

grepl 返回 true,因为正则表达式中的管道字符 | 是一个特殊字符。 a|b 表示匹配 ab。你需要做的就是逃避它。

frtest<-c("ABC|ADC","ABC|ADC|1|2","ABC|ADG","ABC|ADG|2|5")
# making the last number and it's pipe optional
test <- gsub('(\\|\\d)$', '(\\1)?', frtest)
# escaping all pipes 
test<-gsub('\\|' ,'\\\\\\\\|',test)
# testing if any of the strings is in vec
res <- sapply(test, function(x) any(grepl(x, vec)) )
# reassigning the names so they're readable
names(res) <-frtest
#>    ABC|ADC ABC|ADC|1|2     ABC|ADG ABC|ADG|2|5 
         TRUE        TRUE        TRUE        TRUE 

【讨论】:

  • 但是? 操作符会在字面上匹配,从而破坏表达式
【解决方案2】:

对于两个向量vectest,如果test 的对应元素是vec 的元素之一的开始,或者是元素之一vectest 对应元素的开始。

vec <- c("ABC|ADC|1","ABC|ADG|2")
test <- c("ADC|DFG", "ABC|ADC|1|5", "ADC|1", "ABC|ADC")

colSums(sapply(test, startsWith, vec) | t(sapply(vec, startsWith, test))) > 0

# ADC|DFG ABC|ADC|1|5       ADC|1     ABC|ADC 
#   FALSE        TRUE       FALSE        TRUE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    相关资源
    最近更新 更多