改进距离计算 [英] Improving distance calculation
问题描述
我已经建立了自己的距离(我们称其为 d1
).现在,我有了一个矩阵,需要为其计算距离.将 x
视为具有每个样本内容的矩阵,为获得距离矩阵而编写的代码如下:
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,])
}
}
我必须多次执行此过程.因此,我想知道是否有一种更快的方法来填充距离矩阵 wDM
,而不是使用两个for循环.
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.
非常感谢您,
推荐答案
您可以使用 proxy包
中的 dist()
.它允许您通过设置参数 method = #yourDistance
来指定用户定义的距离函数,默认值为 euclidean
.在此处查看文档: https://cran.r-project.org/web/packages/proxy/proxy.pdf
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
这篇关于改进距离计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!