[R] Recursive function for lists

John Fox jfox at mcmaster.ca
Tue Jun 11 17:32:52 CEST 2002


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.

In any event, here's a simple-minded function that flattens a list, along 
with an example of its use.

     > flatten <- function(x){
     +     result <- NULL
     +     for(i in seq(along=x)) {
     +         if (any(sapply(x[[i]], is.list))) Recall(x[[i]])
     +         else result <- c(result, if (is.list(x[[i]])) x[[i]] else 
list(x[[i]]))
     +         }
     +     return(result)
     +     }
     >
     > lst <- list(lst1=list(a=1:3, b=4:6), lst2=list(c=7:9, d=10:12), e=13:15)
     > flat <- flatten(lst)
     > flat
     $a
     [1] 1 2 3

     $b
     [1] 4 5 6

     $c
     [1] 7 8 9

     $d
     [1] 10 11 12

     [[5]]
     [1] 13 14 15

     > sapply(flat, sum)
     a  b  c  d
     6 15 24 33 42

Maybe this will help.
  John
-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------

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