2014-03-26 33 views
1

標題說得很清楚。我的問題很簡單。假設我有向量x:如何獲得總和矩陣而不是距離

x <- c(13,10,9,5) 

# this function gives only distances 
dist(x) 
    1 2 3 
2 3  
3 4 1 
4 8 5 4 

Instead of distance I would like to have sums like this: 
# sum matrix 
    1 2 3 
2 23  
3 22 19 
4 18 15 14 

怎麼辦呢?dist函數中有一些參數嗎?

回答

1

使用外部函數

as.dist(outer(x,x,'+')) 
1

您可以使用outer

sums <- outer(x, x, `+`)[-1, ] 

爲了使它對稱,使用uppertri

sums[upper.tri(sums)] <- NA 
+0

如果你想要得到的矩陣作爲例子,只需使用'print(sums,na.print =「」)',+1! –

+0

偉大的點Jilber。 –