R:子串匹配
问题描述:
我有一个包含字符names
的一列中的以下内容:R:子串匹配
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中部分匹配的值?
答
#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
}
答
我会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
}
答
一些文件和搜索字符串一个简单的例子:
# 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
其实我去了stringi,发现这非常有帮助!非常感谢Marta。 – grievy
不客气,@格里维。 – Marta