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 read.nexus is just a list of trees with the class attribute set to "multiPhylo". To pick one at random we can just do:

random.tree<-sample(trees,size=1)[[1]]
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:

random.trees<-sample(trees,size=100)

That's it.

6 comments:

  1. Very useful and so simple! Thank you, Liam!
    Few weeks ago, I found another approach, which takes into account burn-in.
    http://coleoguy.blogspot.ru/2012/09/randomly-sampling-trees.html





    ReplyDelete
    Replies
    1. Yes - that basically works the same way.

      Thanks!

      Delete
  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 ?

    ReplyDelete
  3. Hey Liam! Thank you so much! I couldn't find this info anywhere!

    ReplyDelete
  4. That's awesome Liam, would it be possible to select n random trees that have the same topology?

    ReplyDelete

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