首页 > 解决方案 > R中非常快速的字符串模糊匹配

问题描述

我有一组 40.000 行 x 4 列,我需要将每一列与其自身进行比较,以找到最接近的结果或最小的 levenshtein 距离。这个想法是为每一行获得一个“几乎重复的”。我用“adist”计算过,但似乎太慢了。例如,与所有列数据集 40.000 行相比,仅一列 5.000 行需要将近 2 个小时。这对于 4 列来说是 8 小时,对于整个数据集来说是 32 小时。有没有更快的方法来实现同样的目标?如果可能的话,我需要它在 1 或 2 小时内完成。这是我到目前为止所做的一个例子:


    #vector example
    a<-as.character(c("hello","allo","hola"))
    b<-as.character(c("hello","allo","hola"))
    
    #execution time
    start_time <- Sys.time()
    
    #Matrix with distance
    dist.name<-adist(a,b, partial = TRUE, ignore.case = TRUE)
    
    #time elapsed
    end_time <- Sys.time()
    end_time - start_time
    
    Output:
    Time difference of 5.873202 secs
    
    #result
    dist.name
          [,1] [,2] [,3]
    [1,]    0    4    5
    [2,]    2    0    2
    [3,]    5    4    0

所需的输出(每行的最小距离,但同一行没有),但我需要它更快。

[1,] 4
[2,] 2
[3,] 4

标签: rmatchingfuzzy

解决方案


你可以试试stringsdist-package。

它是用 C 编写的,使用并行处理并提供各种距离度量,包括 levenshtein-distance。

library(stringdist)

a<-as.character(c("hello","allo","hola"))
b<-as.character(c("hello","allo","hola"))

start_time <- Sys.time()
res <- stringdistmatrix(a,b, method = "lv")
end_time <- Sys.time()

> end_time - start_time
Time difference of 0.006981134 secs
> res
     [,1] [,2] [,3]
[1,]    0    2    3
[2,]    2    0    3
[3,]    3    3    0


diag(res) <- NA
apply(res, 1, FUN = min, na.rm = T)
[1] 2 2 3

推荐阅读