Hi Dave,

I believe that this does what you want ('d'apply for Dave).

dapply <- function(obj, FUN, class="phylo", default=NULL) {
  ret <- lapply(obj, function(x)
                if (inherits(x, class)) FUN(x)
                else if (is.atomic(x)) default
                else dapply(x, FUN, class))
  names(ret) <- names(obj)
  ret
}

library(ape)
tree<-rtree(10)
## Named lists to check that things are where they should be.
list1<-list(a=tree,b=tree,c=tree)
list2<-list(e=list1,f=tree,g=list1)
dapply(list2, Ntip)

Basically this recursively applies maps itself over lists until it hits an 
object of class 'class' ("phylo" by default).  If it never finds an element of 
that class by the time it reaches an atomic class (e.g., numeric) it will 
return default (by default NULL):

list3<-list(e=list1,f=tree,g=list1,h=NA)
dapply(list3,Ntip)

The above function won't be a good idea in all cases, and isn't much tested, 
etc, etc.  This also doesn't preserve class attributes, of the component lists, 
but that could be done in the same way as names() is.

Cheers,
Rich

On 2012-03-14, at 2:39 PM, David Bapst wrote:

> Hello all,
> I am dealing with simulation results that produce nested lists of trees
> (with unbalanced depths; i.e. the first list might have five lists of three
> trees, the second element might have three lists of five trees, the third
> element might just be a single tree). I want to do some analyses on each of
> these trees, so one option would be flattening the list and recording their
> original position in the list. Alternatively, I'd prefer to retain the
> structure of the nested list. I recently discovered rapply() and thought
> this was a perfect fix, only to discover that it appears to look at the
> type() and not the class() of objects passed to it, so it ignores the phylo
> objects as a whole and passes right on to their constituent elements.
> 
> For example:
> 
> library(ape)
> tree<-rtree(10)
> list1<-list(tree,tree,tree)
> list2<-list(list1,tree,list1)
> rapply(list2,Ntip)
> 
> Playing with arguments in rapply doesn't stop this behavior; indeed, it
> seems nothing will stop rapply from ignoring the type 'list' of the phylo
> objects themselves. Does anyone know of an alternative to rapply that
> considers the class of the nested objects instead?
> 
> Thanks,
> -Dave B.
> 
> -- 
> David Bapst
> Dept of Geophysical Sciences
> University of Chicago
> 5734 S. Ellis
> Chicago, IL 60637
> http://home.uchicago.edu/~dwbapst/
> http://cran.r-project.org/web/packages/paleotree/index.html
> 
> <http://home.uchicago.edu/%7Edwbapst/>
> 
>       [[alternative HTML version deleted]]
> 
> _______________________________________________
> R-sig-phylo mailing list
> R-sig-phylo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-phylo

_______________________________________________
R-sig-phylo mailing list
R-sig-phylo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-phylo

Reply via email to