【问题标题】:R: Substring MatchingR:子串匹配
【发布时间】:2016-01-22 07:41:20
【问题描述】:

我有一列字符 names,其中包含以下内容:

Raymond K
Raymond K-S
Raymond KS
Bill D
Raymond Kerry
Blanche D
Blanche Diamond
Bill Dates

我还有一个字符向量 m_names 包含以下内容:

Raymond K
Blanche D

我想创建一个列outcome,如果有匹配的子字符串则返回一个非零整数,如果没有匹配则返回0。例如,对于上面的文本列,我理想情况下希望看到结果

[1] 1 1 1 0 1 2 2 0

目前,我已经尝试了以下代码:

outcome <- pmatch(as.character(names), m_names, nomatch = 0)

但这只会返回以下outcome

[1] 1 0 0 0 1 2 0 0

如何确保即使没有完全匹配,代码仍会返回一个标识 R 中部分匹配的值?

【问题讨论】:

    标签: r match


    【解决方案1】:

    一个包含一些文档和搜索字符串的简单示例:

    # Some documents
    docs <- c("aab", "aba", "bbaa", "b")
    
    # Some search strings (regular expressions)
    searchstr <- c("aa", "ab")
    

    1) 结果向量中的个数计算匹配搜索字符串的个数(1表示“aa”或“ab”匹配,2表示都匹配)

    Reduce('+', lapply(searchstr, grepl, x = docs))
    # Returns: [1] 2 1 1 0
    

    2) 结果的编号应指示搜索字符串 1 匹配还是搜索字符串 2 匹配。如果两者都匹配,则返回最大的数字。 (我想,这就是你想要的)

    n <- length(searchstr)
    Reduce(pmax, lapply(1:n, function(x) x * grepl(searchstr[x], docs)))
    # Returns: [1] 2 2 1 0
    

    现在我们终于考虑你的例子了:

    docs <- c("Raymond K", "Raymond K", "Raymond KS", "Bill D", 
              "Raymond Kerry", "Blanche D", "Blanche Diamond", 
              "Bill Dates")
    searchstr <- c("Raymond K", "Blanche D")
    Reduce(pmax, lapply(1:n, function(x) x * grepl(searchstr[x], docs)))
    # Returns: [1] 1 1 1 0 1 2 2 0
    

    【讨论】:

      【解决方案2】:
      #create an empty outcome vector
      
      outcome<-vector(mode="integer",length=length(names))
      
      # loop for the length of compare vector (m_names)
      for(i in 1:length(m_names)) {
        outcome[grep(m_names[i],names)]<-i
      }
      

      【讨论】:

        【解决方案3】:

        我会用stringi

        library("stringi")    
        
        # data example:
        
        a <- read.table(text="
                        Raymond K
                        Raymond K-S
                        Raymond KS
                        Bill D
                        Raymond Kerry
                        Blanche D
                        Blanche Diamond
                        Bill Dates", 
                        stringsAsFactors=FALSE, sep="\t")
        
        wek <- c("Raymond K", "Blanche D")
        
        # solution
        
        klasa <- numeric(length(a[, 1]))
        for(i in 1:length(wek)){
            klasa[stri_detect_fixed(a[, 1], wek[i])] <- i
        }
        

        【讨论】:

        • 我实际上选择了 stringi,发现这非常有用!非常感谢玛塔。
        猜你喜欢
        • 2016-10-18
        • 2015-10-28
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多