[R] Recursive function for lists

Thomas Lumley tlumley at u.washington.edu
Tue Jun 11 22:09:22 CEST 2002

On Tue, 11 Jun 2002, John Fox wrote:
> I rather like Thomas Lumley's solution, which is simpler than mine, though
> I think that it will be necessary to unlist the result returned by his
> treeapply.

Here's an extended version that optionally flattens the result, and has
two ways to control the depth of recursion, using a function IS.LEAF and a
maximum recursion DEPTH.

treeapply<-function (x, FUN,...,IS.LEAF=is.atomic,DEPTH=Inf,FLATTEN=FALSE)
    if (DEPTH<=0)
    else if (IS.LEAF(x))
    else if (FLATTEN)
        do.call("c",lapply(x, function(n) treeapply(n, FUN,...,IS.LEAF=IS.LEAF,DEPTH=DEPTH-1,FLATTEN=TRUE)))
        lapply(x, function(n) treeapply(n, FUN,...,IS.LEAF=IS.LEAF,DEPTH=DEPTH-1))


r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list