3

This script below runs nicely to get the cluster with a huge data set, but I need to get the cluster into a newick file or a text file so I can export it from R to other editing programs but I can't find a way to get the hclust into a newick format, how can I do it? I feel the new2phylo function may do the job but we did not manage to make it work.

I would really appreciate your help as we have searched everywhere and can't find a solution =(

datos <- read.table("morphclustersred.csv",header=T,sep="\t")
head(datos)
distfunc <- function(x) daisy(x,metric="gower")
d <- distfunc(datos)
hclustfunc <- function(x) hclust(x, method="complete")
fit <- hclustfunc(d)
plot(fit)
plot(fit, labels=datos$Species,main='Morphological Clustering')
rect.hclust(fit, k=5, border="red")
user3301513
  • 31
  • 1
  • 2

2 Answers2

7

You can do it by using write.tree function from ape package. Try this:

library(ape)
class(fit) # must be hclust class
my_tree <- as.phylo(fit) 
write.tree(phy=my_tree, file="exported_tree.newick") # look for the file in your working directory

Hope this helps.

Newbie_R
  • 655
  • 7
  • 22
4

I've only ever managed to extract the .nwk formats from heatmaps by the following conversion steps:

  • dendro --> hcclust --> phylo --> nwk

I know it's a bit of a hack, but here's the code:

# Heatmap of data frame 'data' saved as 'heat'
heat <- heatmap.2(as.matrix(data))

# Extract dendrograms for rows and columns from 'heat'
row.dendro <- heat$rowDendrogram
col.dendro <- heat$colDendrogram

# Convert dendrograms to nwk (via .hcclust and .phylo formats!)
as.hclust (row.dendro)  ->row.hcclust
as.phylo  (row.hcclust) ->row.phylo
write.tree(row.phylo)   ->row.nwk

as.hclust (col.dendro)  ->col.hcclust
as.phylo  (col.hcclust) ->col.phylo
write.tree(col.phylo)   ->col.nwk
T.Shafee
  • 41
  • 1