SolessChong
SolessChong

Reputation: 3407

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

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?

Upvotes: 28

Views: 19665

Answers (2)

JasonRDalton
JasonRDalton

Reputation: 725

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.

Upvotes: 35

geotheory
geotheory

Reputation: 23650

Is this what you need? dist(matrix(1:16, nrow=4))

Upvotes: 0

Related Questions