I am looking for a more efficient way to get the distance matrix in terms of Hamming distance.
Backgrounds
I know there is a function hamming.distance()
from package e1071
to compute the distance matrix, but I suspect it might be very slow when involving a large matrix with many rows, since it applied nested for
loops for computation.
So far I have a faster way (see methodB
) in the code below. However, it is only suitable for in the binary domain, i.e., {0,1}^n
. However, it is unavailable when encountering domains consisting of more than 2 elements, i.e., {0,1,2,...,K-1}^n
. In this sense, methodB
is not for generic hamming distance.
Objective
My objective is to find a approach having the following features:
Rcpp
to rewrite function for speeding up)methodB()
for the special case k=2
k
hamming.distance()
from package e1071
My code
library(e1071)
# vector length, i.e., number of matrix
n <- 7
# number of elements to consist of domain {0,1,...,k-1}^n
k <- 2
# matrix for computing hamming distances by rows
m <- as.matrix(do.call(expand.grid,replicate(n,list(0:k-1))))
# applying `hamming.distance()` from package "e1071", which is generic so it is available for any positive integer `k`
methodA <- function(M) hamming.distance(M)
# my customized method from base R function `dist()`, which is not available for cases `k >= 2`
methodB <- function(M) as.matrix(round(dist(M,upper = T,diag = T)**2))
and the benchmark gives
microbenchmark::microbenchmark(
methodA(m),
methodB(m),
unit = "relative",
check = "equivalent",
times = 50
)
Unit: relative
expr min lq mean median uq max neval
methodA(m) 33.45844 33.81716 33.963 34.30313 34.92493 14.92111 50
methodB(m) 1.00000 1.00000 1.000 1.00000 1.00000 1.00000 50
Appreciated in advance!
methodM <- function(x) {
xt <- t(x)
sapply(1:nrow(x), function(y) colSums(xt != xt[, y]))
}
microbenchmark::microbenchmark(
methodB(m), methodM(m),
unit = "relative", check = "equivalent", times = 50
)
# Unit: relative
# expr min lq mean median uq max neval cld
# methodB(m) 1.00 1.000000 1.000000 1.000000 1.000000 1.000000 50 a
# methodM(m) 1.25 1.224827 1.359573 1.219507 1.292463 4.550159 50 b