Monday, April 1, 2013

Picking a tree or set of trees at random from a "multiPhylo" object

A friend recently asked:

"Does anybody know how to, in R, select a single tree at random from a posterior distribution of trees (e.g., generated via MrBayes)?"

This is not too hard. A set of trees read into memory using read.tree or is just a list of trees with the class attribute set to "multiPhylo". To pick one at random we can just do:

We include the index [[1]] to (non-recursively) unlist the object returned by sample.

If we want to sample more than one, say 100 random trees from a posterior sample of 1,000, the procedure is the same. So we can just do:


That's it.


  1. Very useful and so simple! Thank you, Liam!
    Few weeks ago, I found another approach, which takes into account burn-in.

    1. Yes - that basically works the same way.


  2. Dear Revell,

    I'm trying to use the function ace to calculate ancestral states with a sample of 500 hundred trees to take into account phylogenetic uncertainty. My tree file is thus an object of class "multiPhylo", and it seems the ace function does not not work with more than one phylogeny. Am i right ? Is there a way in phytools to infere internal nodes taking into account phylogenetic uncertainty ?