# Extracting clusters in from pheatmap in different order to distance

I have created a heatmap in R using pheatmap as seen below. I would like to extract the clusters outlined in black, due to the patterns identified within. The problem I have is that the distances are not in the order I wish to extract the clusters. Is there a smart way I can do this whilst still keeping the information contained? I am using Ward D2 clustering method.

I have so far used:

df$clust <- cbind(df, cluster = cutree(pat$tree_col,  k = 4))


but of course this goes by distance. Thanks!

## 1 Answer

It is not obvious what you mean by "the distances are not in the order I wish to extract the clusters": a "distance" is a matrix with pairwise distance values, which are symmetric. It is used to induce an ordering among the samples, via some method; the way you compute or use the distance defines the groups/ clusters.

In this case, pheatmap's clusters are computed by hc(.) via some distance -- see ?pheatmap to change the parameters -- and can be accessed from the return object, along with other information.

Did you annotate the figure yourself? It is not even clear if rows are clustered as well; please provide some complete example.

In my experience, however, R package dynamicTreeCut provides you with some interesting dendrogram cutting heuristics, which seem to make sense in many cases.

• This is more like a comment where you are asking questions of the OP to better clarify the question. – Michael Chernick Jun 1 '18 at 0:12