如何显式构建稀疏 stringdistmatrix 以避免 运行 内存不足?

How to explicitly build sparse stringdistmatrix to avoid running out of memory?

将 "data" 向量中大量略有不同的餐厅名称匹配到适当的 "match" 向量:

stringdist 包中的 stringdistmatrix 函数很棒,但是内存不足几个 10k x 10k 并且我的数据更大。

已尝试 as(stringdistmatrix(data, match),'sparseMatrix') 会给出希望的结果,但内存不足。因此,我想使用 sparseMatrix(i,j,x,dims,dimnames) 和由 adist() 计算的 x 或类似的字符串距离明确索引对,希望它适合内存。

R

data <- c("McDonalds", "MacDonalds", "Mc Donald's", "Wendy's", "Wendys", "Wendy", 
          "Chipotle", "Chipotle's")

match <- c("McDonalds", "Wendys", "Chipotle")

正在尝试:

library(Matrix)
library(stringdist)

idx <- expand.grid(a=data,b=match)
idx$row <- match(idx$a,idx$b)
idx$col <- match(idx$b,idx$a)

library(Matrix)
sparseMatrix(i=idx$row, 
             j=idx$col,
             x=ifthen(adist(data,match)<2,1,0),
             dims=c(7,3),
             dimnames = list(data, match))

希望输出匹配:

library(stringdist)
as(ifelse(stringdistmatrix(data,match)<2,1,0),'sparseMatrix')

如果我没有正确理解你的问题,你的任务是将脏字符串与干净字符串进行匹配。你不需要整个矩阵(它确实不会稀疏)。相反,您可以使用 amatch.

library(stringdist)
data <- c("McDonalds", "MacDonalds", "Mc Donald's", "Wendy's", "Wendys", "Wendy", 
          "Chipotle", "Chipotle's")
match <- c("McDonalds", "Wendys", "Chipotle")
i <- amatch(data, match, method="osa",maxDist=2)
data.frame(data=data, matched_data = match[i], stringsAsFactors = FALSE)

         data matched_data
1   McDonalds    McDonalds
2  MacDonalds    McDonalds
3 Mc Donald's    McDonalds
4     Wendy's       Wendys
5      Wendys       Wendys
6       Wendy       Wendys
7    Chipotle     Chipotle
8  Chipotle's     Chipotle