Tuesday, December 27, 2016

S3 as.multiPhylo method for objects of class "phylo"

I just added a tiny update to phytools in which I have included a new S3 method to convert an object of class "phylo" to an object of class "multiPhylo".

This is super-simple & looks something like the following:

as.multiPhylo.phylo<-function(x,...){
    obj<-list(x)
    class(obj)<-"multiPhylo"
    obj
}

as.multiPhylo<-function(x,...){
    if (identical(class(x),"multiPhylo")) return(x)
    UseMethod("as.multiPhylo")
}

(along with appropriate S3method declaration in NAMESPACE, etc.).

The purpose of this is to allow a function to return an object of a consistent class, even if it sometimes returns only one tree. This might be for example, read.nexus (in which our input files may contain only 1 phylogeny), or pbtree, in which a variable number of phylogenies are to be simulated.

Here is a quick demo of the latter:

pbtree(n=26,tip.label=LETTERS)
## 
## Phylogenetic tree with 26 tips and 25 internal nodes.
## 
## Tip labels:
##  A, B, C, D, E, F, ...
## 
## Rooted; includes branch lengths.
pbtree(n=26,tip.label=LETTERS,nsim=10)
## 10 phylogenetic trees

vs.

as.multiPhylo(pbtree(n=26,tip.label=LETTERS))
## 1 phylogenetic trees
as.multiPhylo(pbtree(n=26,tip.label=LETTERS,nsim=10))
## 10 phylogenetic trees

The update can be obtained by installing phytools version >= 0.5-67 from GitHub.

No comments:

Post a Comment

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