问题
[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