4

我有 9k 行的data.table dt(请参见下面的示例)。我需要将dt的每个rname与参考dt.ref的每个cname进行比较。通过比较,我的意思是计算 Levenshtein 比率。data.table

然后,我取最大值并得到我的输出(见下文)。

dt

nid | rname  | maxr
n1  | apple  |  0.5
n2  | pear   |  0.8
n3  | banana |  0.7
n4  | kiwi   |  0.6
... (9k)

dt.ref

cid | cname
c1  | apple
c2  | maple
c3  | peer
c4  | dear
c5  | bonobo
c6  | kiwis
... (75k)

输出

nid | rname  | maxr | maxLr | cid
n1  | apple  |  0.5 | 1     | c1
n2  | pear   |  0.8 | 0.75  | c3
n2  | pear   |  0.8 | 0.75  | c4
n3  | banana |  0.7 | 0.33  | c5
n4  | kiwi   |  0.6 | 0.8   | c6
...

为了计算这个输出,我stringdistmatrix在以这种方式编码的函数中使用函数(请参阅Computing the Levenshtein ratio of each element of a data.table with each value of a reference table and merge with maximum ratio):

f1 <- function(x, y) {
  require(stringdist)
  require(matrixStats)
  dis  <- stringdistmatrix(x, y, method = "lv")
  mat <- sapply(nchar(y), function(i) pmax(i, nchar(x)))
  r <- 1 - dis / mat
  w <- apply(r, 1, function(x) which(x==max(x)))
  m <- rowMaxs(r)
  list(m = m, w = w)
}

r <- f1(dt[[2]], dt.ref[[2]])
dt[, maxLr := r$m ]
dtnew <- dt[rep(1:.N, lengths(r$w)),]
dtnew[, cid := dt.ref[unlist(r$w), 1]]

但是,对于 9k x 75k 矩阵,我遇到了导致 R 会话中止的内存问题。除了拆分 9k 表之外,它是否是一种方法:

  1. data.table仅使用而不使用矩阵进行不同的编码?
  2. 排序和拆分参考表以仅在 75k 字符串的子集上计算 Levenshtein 比率?
4

0 回答 0