How to convert a symmetric matrix into "dist" object?

SolessChong picture SolessChong · Jul 26, 2013 · Viewed 15.4k times · Source

I want to use hclust to cluster a data. But I don't want to use "dist()" to generate the dist object. Then I found out that I cannot pass a symmetric matrix as distance matrix into hclust.

How to convert a symetric matrix into "dist" object?

Answer

JasonRDalton picture JasonRDalton · Jul 26, 2013

It sounds like you already have a matrix calculated, and want to use that in hclust. Like @shadow said, you can use as.dist(yourMatrix) to convert to the dist format.

Given a symmetric table of distances:

> yourMatrix<-matrix(c(1,2,3,4,2,1,2,1,3,2,1,3,4,1,3,1), nrow=4)
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    2    1    2    1
[3,]    3    2    1    3
[4,]    4    1    3    1
>
>as.dist(yourMatrix)
  1 2 3
2 2    
3 3 2  
4 4 1 3

Make sure that the values in your matrix are dissimilarity, or distance metrics rather than similarity scores.