使用`dplyr计算有效汉明距离`
我需要计算(缩放)的汉明字符串距离使用`dplyr计算有效汉明距离`,r,dplyr,R,Dplyr,我需要计算(缩放)的汉明字符串距离 d(x,y)={x_i!=y_i:i=1,…,n}/n其中x和y是长度为n的字符串。我使用R和dplyr/tidyverse,并将汉明距离定义为 hamdist = function(x,y) mean(str_split(x, "")[[1]] != str_split(y, "")[[1]]) 这个很好用。但是,因为我想按列应用它,所以必须使用rowwise动词(或者使用purr包中的map2)。问题是:我的数据集包含约5000万次观测,因此计算需要几个
d(x,y)={x_i!=y_i:i=1,…,n}/n
其中x
和y
是长度为n
的字符串。我使用R和dplyr/tidyverse,并将汉明距离定义为
hamdist = function(x,y) mean(str_split(x, "")[[1]] != str_split(y, "")[[1]])
这个很好用。但是,因为我想按列应用它,所以必须使用rowwise
动词(或者使用purr包中的map2
)。问题是:我的数据集包含约5000万次观测,因此计算需要几个小时
因此,我的问题是:是否有一种更平滑/更有效的方法来实现列操作的汉明字符串距离
(最好使用dplyr解决方案)
一个例子:
n = 1000
l = 8
rstr = function(n, l = 1) replicate(n, paste0(letters[floor(runif(l, 1, 27))], collapse = ""))
hamdist = function(x,y) mean(str_split(x, "")[[1]] != str_split(y, "")[[1]])
df = tibble(a = rstr(n, l), b = rstr(n, l))
df %>% mutate(dist = hamdist(a, b)) # wrong!
df %>% rowwise() %>% mutate(dist = hamdist(a, b)) # correct! but slow for n = 50 mio
请参阅
stringdist
包。函数stringdist
接受一个方法
参数,该参数可以是“hamming”
。
stringdist
包声称:
专为速度而建,使用openMP进行并行计算
你能给我举个例子吗?我加了一个例子。谢谢。这个函数实际上运行得非常快:
>system.time(df%>%mutate(dist=stringdist(a,b,method=“hamming”)/8))用户系统运行0.002 0.000 0.001和>system.time(df%>%rowwise()%%>%mutate(dist=hamdist(a,b)))用户系统运行1.0820 0.020 1.102(对于n=10000)