R中的有符号距离矩阵 [英] Signed distance matrix in R
本文介绍了R中的有符号距离矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[注意,我写下了这个问题,然后找到了答案.我以为也许其他人想知道这一点,所以我发布答案是为了以防万一.我不确定这是否是完成的事情"].
[Note, I wrote out this question, then found an answer. I thought maybe someone else would like to know it, so I'm posting the answer just in case. I'm not sure if this is the "done thing"].
假设我想要向量的有符号距离矩阵,即距离并不总是正的,而是可以是负的.您不能使用
Suppose I want the signed distance matrix of a vector, i.e. the distance's aren't always positive, but can be negative. You can't use
dist()
因为它返回绝对值.
推荐答案
这是另一种方法,它更快并且需要更少的内存:
Here's another approach, which is much faster and needs less memory:
y <- sample (1 : 4)
distmat <- outer (y, y, `-`)
产量:
> distmat
[,1] [,2] [,3] [,4]
[1,] 0 1 3 2
[2,] -1 0 2 1
[3,] -3 -2 0 -1
[4,] -2 -1 1 0
## not sure why you want the upper triangular NA
distmat[upper.tri(distmat,diag=TRUE)]<-NA
但您可能想要:
> as.dist (distmat)
1 2 3
2 -1
3 -3 -2
4 -2 -1 1
这篇关于R中的有符号距离矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文