[R] Recursive function for lists

Thomas Lumley tlumley at u.washington.edu
Tue Jun 11 18:17:44 CEST 2002


On Tue, 11 Jun 2002, John Fox wrote:

> Dear Eric,
>
> At 01:23 PM 6/10/2002 +0100, Eric Lecoutre wrote:
>
> >Does it exist a function to recursively run through a list and apply a
> >function only to terminal nodes?
> >I tried to sapply my HTML.list function to a list and expected that it
> >recursively worked but it's not the case.
>
> I have the feeling that I'm reinventing the wheel -- I think that I recall
> a simple way to flatten a list but I can't find it (or I may just be having
> a Lisp flashback), and I don't think that anyone else has posted an answer
> to your question.
>

If you don't want to flatten the list you need something like

treeapply<-function (x, FUN)
{
    if (is.atomic(x))
        FUN(x)
    else lapply(x, function(n) treeapply(n, FUN))
}

This is less general and much slower than lapply, but could easily be
improved. For a start it won't work for very deep trees as it has multiple
nested function calls per level.

The XML package has an internal function for doing this to XML structures,
and I think there might be one somewhere in bioconductor.

	-thomas

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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