pdubois
pdubois

Reputation: 7790

Write table with row name ordered after clustering in R's heatmap.2

With the following code:

mydata <- mtcars
hclustfunc <- function(x) hclust(x, method="complete")
distfunc <- function(x) dist(x,method="euclidean")
heatmap.2(as.matrix(mydata),dendrogram="row",trace="none", margin=c(8,9), hclust=hclustfunc,distfun=distfunc);

I get the following heatmap:enter image description here

What I want to do is to save the result of the clustering in to a text file but the row names are ordered as clustered result:

mpg cyl disp hp drat wt qsec vs am gear carb
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.9 1 1 4 1
Porsche 914-2 26 4 120.3 91 4.43 2.14 16.7 0 1 5 2
Datsun 710 22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
....
Maserati Bora 15 8 301 335 3.54 3.57 14.6 0 1 5 8

What's the way to do it ? I tried this after heatmap.2 line in the code above, but doesn't give the result as I desired.

write.table(mydata, "~/Desktop/tmp.txt",row.names = TRUE, quote=FALSE)

Upvotes: 1

Views: 3225

Answers (1)

MrFlick
MrFlick

Reputation: 206197

The heatmap.2 function won't do anything to your original data. If you save the results from the call to heatmap.2 function, it will return the rowDendrogram that you can use to re-sort your data. For example

hh<-heatmap.2(as.matrix(mydata),dendrogram="row",
    trace="none", margin=c(8,9), 
    hclust=hclustfunc,distfun=distfunc);

sorted <- mydata[match(rev(labels(hh$rowDendrogram)), rownames(mydata)), ]

#view result
head(sorted)
#               mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Toyota Corona 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
# Porsche 914-2 26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
# Datsun 710    22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
# Volvo 142E    21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
# Merc 230      22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
# Lotus Europa  30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

then you can write the sorted version of the data.frame to disk with write.table

Upvotes: 4

Related Questions