Wednesday, July 10, 2013

Rotating all the nodes in a tree (or a set of nodes)

I just wrote a utility function that wraps around rotate in the ape package to rotate a set of nodes in a tree (including nodes="all"). It also addresses this weird problem that I discovered that results when a bunch of rotations are applied to a tree the "phylo" can become non-compliant with certain ape & phytools functions because the order of the tip numbers in tree$edge is not 1:n for n tips.

Here's the function:

rotateNodes<-function(tree,nodes,polytom=c(1,2),...){
  n<-length(tree$tip.label)
  if(nodes[1]=="all") nodes<-1:tree$Nnode+n
  for(i in 1:length(nodes))
    tree<-rotate(tree,nodes[i],polytom)
  if(hasArg(reversible)) reversible<-list(...)$reversible
  else reversible<-TRUE
  if(reversible){
    ii<-which(tree$edge[,2]<=n)
    jj<-tree$edge[ii,2]
    tree$edge[ii,2]<-1:n
    tree$tip.label<-tree$tip.label[jj]
  }
  return(tree)
}

Let's try it:

> tree<-pbtree(n=26)
> tree$tip.label<-LETTERS
> plotTree(tree)
> tree<-rotateNodes(tree,"all")
> plotTree(tree)

1 comment:

  1. This function is in a new build of phytools (phytools 0.2-94), and will be in the next CRAN release.

    ReplyDelete