r - 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
解决方案
你可以试试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
推荐阅读
- linux - 硬盘虚拟机Ubuntu放大
- usb - 脚本在连接后随机播放 USB 记忆棒上的文件
- windows - Jenkins共享库,使用Java 11时的外部jar
- c - 具有用户选择的 10x10 矩阵生成:获取矩阵的每行和每列的总和和平均值
- python-3.x - 相机与 y 轴的角度水平旋转
- android - Kotlin:尝试在 WebView 上添加 onReceivedError 时出现“修改器‘覆盖’不适用于‘本地函数’”错误
- angular - 以角度将ID传递给子组件
- scala - 仅当新值不是 Null 或空时,如何替换 Spark Streaming 中的列值?
- java - 订阅后收到订单。安卓工作室-Java
- r - r 比较组中的描述性统计