Signed distance matrix in R

江枫思渺然 提交于 2019-12-24 10:50:01

问题


[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()

because it returns absolute values.


回答1:


Here's another approach, which is much faster and needs less memory:

y <- sample (1 : 4)
distmat <- outer (y, y, `-`) 

yields:

> 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

but you possibly want:

> as.dist (distmat)
   1  2  3
2 -1      
3 -3 -2   
4 -2 -1  1



回答2:


Use apply:

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


来源:https://stackoverflow.com/questions/14961747/signed-distance-matrix-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!