tricks
# Generate a sample matrix
y <- matrix(rnorm(50), 10, 5, dimnames=list(paste("g", 1:10, sep=""),
paste("t", 1:5, sep="")))
# Cluster rows and columns by correlation distance
hr <- hclust(as.dist(1-cor(t(y), method="pearson")))
hc <- hclust(as.dist(1-cor(y, method="spearman")))
# Obtain discrete clusters with cutree
mycl <- cutree(hr, h=max(hr$height)/1.5)
# Prints the row labels in the order they appear in the tree.
hr$labels[hr$order] .
# Prints the row labels and cluster assignments
sort(mycl)
# Some color selection steps
mycolhc <- sample(rainbow(256))
mycolhc <- mycolhc[as.vector(mycl)]
# Plot the data matrix as heatmap and the cluster results as dendrograms
with heatmap or heatmap.2
# and show the cutree() results in color bar.
heatmap(y, Rowv=as.dendrogram(hr), Colv=as.dendrogram(hc), scale="row",
RowSideColors=mycolhc)
library("gplots")
heatmap.2(y, Rowv=as.dendrogram(hr), Colv=as.dendrogram(hc),
col=redgreen(75), scale="row",
ColSideColors=heat.colors(length(hc$labels)), RowSideColors=mycolhc,
trace="none", key=T, cellnote=round(t(scale(t(y))),1))
# 2
data <- data.matrix(data)
data <- y
distance <- dist(data)
cluster <- hclust(distance, method="ward")
dendrogram <- as.dendrogram(cluster)
Rowv <- rowMeans(data, na.rm = T)
dendrogram <- reorder(dendrogram, Rowv)
## Produce the heatmap from the calculated dendrogram.
## Don't allow it to re-order rows because we have already re-ordered them above.
reorderfun = function(d,w) { d }
png("heatmap.png", res=150, height=22,width=17,units="in")
heatmap(data,col=colors,breaks=breaks,scale="none",Colv=NA,Rowv=dendrogram,labRow=NA, reorderfun=reorderfun)
dev.off()
## Re-order the original data using the computed dendrogram
rowInd = rev(order.dendrogram(dendrogram))
di = dim(data)
nc = di[2L]
nr = di[1L]
colInd = 1L:nc
data_ordered <- data[rowInd, colInd]
write.table(data_ordered, "rows.txt",quote=F, sep="\t",row.names=T, col.names=T)