通过 R 中的相似字符/字符串匹配两个向量

问题描述

我有两个向量,比如

v1<-c("yellow","red","orange","blue","green")
v2<-c("blues","redx","grean")

并且我想匹配它们,即将v1的每个元素与v2上最相似的元素“链接”,以便结果是

> df
      v1    v2
1 yellow  <NA>
2    red  redx
3 orange  <NA>
4   blue blues
5  green grean

下面的代码给出了预期的结果,但只是因为它已经手动“格式化”了

df<-data.frame(v1,v2=rep(NA,5))

for (i in 1:nrow(df)) {
  
  ag<-agrep(df[i,1],v2,ignore.case = T,value = T)
  
  if (length(ag)==0) {df[i,2]<-NA}
  else if (length(ag)==1) {df[i,2]<-ag}
  else {df[i,2]<-ag[1]}
  
}

碰巧 agrep(df[2,max.distance = 0.00001,value = T) 的结果是 "redx" "grean",即使我设置了 max.distance = 0.00001

这就是为什么我有 if 条件,但它不能保证选择最相似的答案。

我该如何克服这个问题?

提前致谢

解决方法

也许以下内容可以解决您的问题。它在包 stringdistmatrix 中使用 stringdist,如果向量 v1v2 较大,这可能会成为内存问题。

d <- stringdist::stringdistmatrix(v1,v2,method = "osa")
i <- which(colSums(d == 1) > 0)
j <- which(rowSums(d == 1) > 0)
df$v2[j] <- v2[i]

df
#      v1    v2
#1 yellow  <NA>
#2    red blues
#3 orange  <NA>
#4   blue  redx
#5  green grean
,

你可以试试:

s <- which(adist(v1,v2) <= 1,TRUE) # 1 is the maximum allowed change
data.frame(v1,v2=replace(NA,s[,1],v2[s[,2]]))
      v1    v2
1 yellow  <NA>
2    red  redx
3 orange  <NA>
4   blue blues
5  green grean