[R] Recursive function for lists

Martin Maechler maechler at stat.math.ethz.ch
Tue Jun 11 18:34:32 CEST 2002


>>>>> "John" == John Fox <jfox at mcmaster.ca> writes:

    John> Dear Eric, At 01:23 PM 6/10/2002 +0100, Eric Lecoutre
    John> 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.

    John> I have the feeling that I'm reinventing the wheel -- I
    John> think that I recall a simple way to flatten a list but
    John> I can't find it (or I may just be having a Lisp
    John> flashback), and I don't think that anyone else has
    John> posted an answer to your question.

unlist() is probably what you can't recall.
It is a bit different than your  flatten()  though :

> lst <- list(lst1=list(a=1:3, b=4:6), lst2=list(c=7:9, d=10:12), e=13:15) 

> str(ul <- unlist(lst, recursive=FALSE))
List of 7
 $ lst1.a: int [1:3] 1 2 3
 $ lst1.b: int [1:3] 4 5 6
 $ lst2.c: int [1:3] 7 8 9
 $ lst2.d: int [1:3] 10 11 12
 $ e1    : int 13
 $ e2    : int 14
 $ e3    : int 15


    John> In any event, here's a simple-minded function that
    John> 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
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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