[R] Summary: recursion over list

John Fox jfox at mcmaster.ca
Thu Jun 13 20:19:52 CEST 2002


Dear Eric,

At 02:00 PM 6/13/2002 +0100, Eric Lecoutre wrote:


>- John Fox send a function of his that allows to flatten a list, ie to 
>change a generic any-depth list to a one-depth list:
>
>         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)
>         }
>
>This function might be usefull for some purpose, but again not mine. (as 
>the result is a concatenation, it can't deal matrices or functions).

Here's an example of flattening a list that includes a matrix and a function:

     > lst <- list(a=list(b=matrix(1:12, 3,4), c=4:6), d=list(e=7:9, 
f=function(x) x), g=15:18)
     > lst
     $a
     $a$b
         [,1] [,2] [,3] [,4]
     [1,]    1    4    7   10
     [2,]    2    5    8   11
     [3,]    3    6    9   12

     $a$c
     [1] 4 5 6


     $d
     $d$e
     [1] 7 8 9

     $d$f
     function(x) x


     $g
     [1] 15 16 17 18

     > flatten(lst)
     $b
         [,1] [,2] [,3] [,4]
     [1,]    1    4    7   10
     [2,]    2    5    8   11
     [3,]    3    6    9   12

     $c
     [1] 4 5 6

     $e
     [1] 7 8 9

     $f
     function(x) x

     [[5]]
     [1] 15 16 17 18

Obviously, I misunderstand the problem.

Regards,
  John
____________________________
John Fox
Department of Sociology
McMaster University
email: jfox at mcmaster.ca
web: http://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