2013-02-19 124 views
0

[注意,我写出了这个问题,然后找到了答案。我想也许有人想知道它,所以我发布的答案以防万一。我不确定这是否是“做过的事情”]。R中的有符号距离矩阵

假设我想要一个向量的符号距离矩阵,即距离不总是正数,但可以是负数。因为它返回的绝对值不能使用

DIST()

回答

1

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

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 
1

使用适用于:

y<-seq(1:10) 
distmat<-as.data.frame(apply(as.matrix(y),1,function(x) y-x)) 
distmat[upper.tri(distmat,diag=TRUE)]<-NA 
+0

您也可以将'distmat'作为'replicate(length(y),y) - t(replicate(length(y),y))'。 – Arun 2013-02-19 16:03:08

+1

此外,您在这里制作的结果可以通过'dist(1:10,method =“manhattan”)' – Arun 2013-02-19 16:05:59

+0

获得。希望您打算使用http://en.wikipedia中的带符号距离定义.org/wiki/Signed_distance,在这种情况下,你的内部/外部是不是很清楚。让我们来清楚一点:“距离”是严格定义非负的。你在寻找什么是基本上的矢量位置(例如,在距离原点的欧几里得距离sqrt(3^2 + 2^2)的(-3,-2)处)? – 2013-02-19 16:25:02