Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

matrix

distance

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?

like image 597
SolessChong Avatar asked Jul 26 '13 07:07

SolessChong


1 Answers

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.

like image 93
JasonRDalton Avatar answered Nov 10 '22 03:11

JasonRDalton