R中非常快速的字符串模糊匹配

时间:2019-05-10 06:44:54

标签: r matching fuzzy

我有一组40.000行x 4列,我需要将每一列与其自身进行比较,以找到最接近的结果或最小的勒维施泰因距离。这个想法是为每一行获取一个“几乎重复的”。我已经计算过“专家”,但似乎太慢了。例如,对于仅一列,与所有列数据集(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

1 个答案:

答案 0 :(得分:3)

您可以尝试使用stringsdist软件包。

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

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
相关问题