Marius Hofert
2011-May-19 10:53 UTC
[R] foreach: how to create array (of lists) as result?
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"))
okay, I should have remembered... Gabor suggested a pretty nice solution, see: http://r.789695.n4.nabble.com/How-to-create-an-array-of-lists-of-multiple-components-td3167576.html -- View this message in context: http://r.789695.n4.nabble.com/foreach-how-to-create-array-of-lists-as-result-tp3535393p3537776.html Sent from the R help mailing list archive at Nabble.com.
Animesh Saxena
2011-May-20 06:51 UTC
[R] foreach: how to create array (of lists) as result?
Thanks a lot! It worked perfectly.... I just tried a simple modification... > dc<-array(sapply(sapply(modelprices[2], c), c)) On 5/20/11 12:11 PM, mhofert wrote:> okay, I should have remembered... Gabor suggested a pretty nice solution, > see: > > http://r.789695.n4.nabble.com/How-to-create-an-array-of-lists-of-multiple-components-td3167576.html > > -- > View this message in context: http://r.789695.n4.nabble.com/foreach-how-to-create-array-of-lists-as-result-tp3535393p3537776.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.-- Regards, Animesh Saxena (www.quantanalysis.in)