0

The following code simulate a number of phylogenetic trees(here 100). But due to chance event of extinction some trees are NULL. I need to verify those NULL trees, drop them from the output object and select x out of N trees from the remaining trees.

library(phytools)
Trees<- pbtree(b=0.6, d=0.2, n=200, t=NULL, scale=NULL, nsim=100,      type="continuous", extant.only=TRUE)

Suppose above code returns 3 NULLs and I need to (let's say) choose 50 out of 100-3=97 trees. It can be the first 50 trees or whatever. I'm not sure if a loop can do that for me.

Thanks for your help!

SlowLoris
  • 995
  • 6
  • 28
Jack
  • 165
  • 2
  • 12

2 Answers2

1

Because R stores objects as vectors, loops are not usually particularly efficient: the 'apply' family of functions often work much more quickly.

Here you could try:

null.trees <- sapply(Trees, is.null)
valid.trees <- Trees[!null.trees]
if (length(valid.trees) < 50) {  
  warning('Not enough trees!'!
} else {
   valid.trees[1:50]
}
Martin Smith
  • 3,687
  • 1
  • 24
  • 51
0

Yes a loop can help you. I would do it this way, to avoid generating a bunch of excess trees that you never use:

 ntrees <- 50
 trees <- list()
 for (i in 1:ntrees) {
    tree <- NULL
    while (is.null(tree)) {
        tree <- pbtree(b=0.6, d=0.2, n=200, t=NULL, scale=NULL, 
                nsim=1, type="continuous", extant.only=TRUE)
    }
    trees[i] <- tree
 }

That works for me.

SlowLoris
  • 995
  • 6
  • 28