[R] foreach: how to create array (of lists) as result?

Marius Hofert m_hofert at web.de
Thu May 19 12:53:54 CEST 2011


Dear expeRts,

I have several nested foreach loops. In the end one obtains a list of lists of lists...
Since it is much more natural to work with arrays, I would like to know if it is 
possible to obtain an array of lists? 
There are two options I guess:
1) can foreach return an array instead of a list? 
2) can I easily (not by hand for each nesting level!) convert the resulting list in 
an array of lists?
Below is a minimal example. Any help is appreciated. 

Cheers,

Marius


library(foreach)

a <- c("a1","a2")
b <- c("b1","b2")
c <- c("c1","c2")
d <- 1:3

fun <- function(w,x,y,z) list(w=w, x=x, y=y, z=z) # just a dummy function

res <- foreach(i=1:length(a)) %:%
    foreach(j=1:length(b)) %:%
    foreach(k=1:length(c)) %:%
    foreach(l=d) %dopar% {

        res. <- lapply(1:4, function(x){
            res.. <- fun(a[i],b[j],c[k],d[l]+x)
            res..
        })
        res.

    }

res[[1]][[2]][[1]][[3]][[4]] # case i=1, j=2, k=1, l=3, x=4

## goal: to have an array A of lists with A[1,2,1,3,4] being equal to 
##       res[[1]][[2]][[1]][[3]][[4]] for example
## note: unlist(res) does not work in my original problem, since the list which 
##       is returned from fun has random length :-(
## If fun only returns a numeric value, the problem is of course trivial to solve, 
## it would simply be s.th. like:
## array(unlist(res), dim=c(4,3,2,2,2), dimnames=c("x","d","c","b","a"))
	


More information about the R-help mailing list