问题
I have build my own distance (let's call it d1
). Now, I have a matrix for which I need to compute the distance. Considering x
as the matrix with the content for each sample, the code written to get the distance matrix is the following:
# Build the matrix
wDM <- matrix(0, nrow=nrow(x), ncol=nrow(x))
# Fill the matrix
for (i in 1:(nrow(wDM)-1)){
for (j in (i+1):nrow(wDM)){
wDM[i,j] <- wDM[j,i] <- d1(x[i,], x[j,])
}
}
I have to implement this process several times. So, I was wondering if there is a faster way to fill the distance matrix wDM
rather than using two for loops.
Thank you so much,
回答1:
You can use dist()
from proxy package
. It lets you specify user-defined distance function by setting the parameter method = #yourDistance
default would be euclidean
. Check the documentation here: https://cran.r-project.org/web/packages/proxy/proxy.pdf
来源:https://stackoverflow.com/questions/45231861/improving-distance-calculation