1

[注意,我写了这个问题,然后找到了答案。我想也许其他人想知道它,所以我发布答案以防万一。我不确定这是否是“完成的事情”]。

假设我想要一个向量的有符号距离矩阵,即距离并不总是正数,但可以是负数。你不能使用

距离()

因为它返回绝对值。

4

2 回答 2

2

使用适用:

y<-seq(1:10)
distmat<-as.data.frame(apply(as.matrix(y),1,function(x) y-x))
distmat[upper.tri(distmat,diag=TRUE)]<-NA
于 2013-02-19T15:57:58.610 回答
2

这是另一种方法,它更快并且需要更少的内存:

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
于 2013-02-19T16:55:18.523 回答