[R] How to create an array of lists of multiple components?

Marius Hofert m_hofert at web.de
Thu Dec 30 12:10:58 CET 2010


Dear Gabor,

*perfect*, precisely what I was looking for.

Many thanks,

Marius

On 2010-12-29, at 23:19 , Gabor Grothendieck wrote:

> On Wed, Dec 29, 2010 at 4:58 PM, Marius Hofert <m_hofert at web.de> wrote:
>> Dear Jim,
>> 
>> thanks for your quick response. Here is what I try to achieve:
>> 
>> ## list containing some data
>> l <- list(
>>          list(
>>               list(
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2)
>>                    ),
>>               list(
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2)
>>                    ),
>>               list(
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2)
>>                    )
>>               ),
>>          list(
>>               list(
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2)
>>                    ),
>>               list(
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2)
>>                    ),
>>               list(
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2),
>>                    list(a = 1, b = "b", c = 2)
>>                    )
>>               )
>>          )
>> 
>> ## now (try to) build an array of lists of the form list(a = 1, b = "b", c = 2)
>> n1 <- 2
>> n2 <- 3
>> n3 <- 4
>> res <- array(rep(list(NULL,NULL,NULL), n1*n2*n3), dim = c(n1,n2,n3))
>> for(i in 1:n1){
>>    for(j in 1:n2){
>>        for(k in 1:n3){
>>            res[i,j,k] <- l[[i]][[j]][[k]]
>>        }
>>    }
>> }
>> 
> 
> 
> Try this:
> 
> array(sapply(sapply(l, c), c), c(4, 3, 2))
> 
> 
> 
> -- 
> Statistics & Software Consulting
> GKX Group, GKX Associates Inc.
> tel: 1-877-GKX-GROUP
> email: ggrothendieck at gmail.com



More information about the R-help mailing list