Sunday, February 5, 2012

Printing a tree to file without branch lengths

A recent Google search string that led a user to the phytools blog was as follows:

"how to create newick tree without distances"

By this I presume they mean: how does one print a Newick tree to file (or screen) without branch lengths? In R, this is very straightforward.

Every phylo object stored in memory has three main items and a class attribute "phylo". The items are a m × 2 matrix edge (for m branches in the tree); a vector of length N containing all the tip names (tip.label); and an integer, Nnode, which indicates the number of internal nodes in the tree. Trees with branch lengths also have an m length vector edge.length containing the branch lengths for all the branches in the tree (in the same order as the rows in edge).

To print a tree without its branch lengths, it is simply necessary to set edge.length to NULL. That's it - piece of cake, right?

Let's try it.

> tr1<-rtree(10) # random tree
> write.tree(tr1) # write tree with edge lengths
[1] "(((t10:0.055,t6:0.599):0.3,(t9:0,((((t5:0.728,t1:0.624):0.142,t4:0.639):0.965,t3:0.396):0.562,(t7:0.383,t2:0.241):0.14):0.741):0.501):0.801,t8:0.138);"
> tr2<-tr1 # copy tree
> tr2$edge.length<-NULL # get rid of edge lengths
> write.tree(tr2) # write tree without edge lengths
[1] "(((t10,t6),(t9,((((t5,t1),t4),t3),(t7,t2)))),t8);"


Of course, this works just as well with write.nexus (which writes a NEXUS format tree) or write.tree(...,file=filename) and write.nexus(...,file=filename).

3 comments:

  1. Hi Liam,

    Thanks for this. I was just wondering how you would accomplish this with a mutiphylo object. I'd also love to know how you reroot a multiphylo object.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete

Note: due to the very large amount of spam, all comments are now automatically submitted for moderation.