Vero - 4 months ago 31

R Question

I'm rather new to using lists in R. Now I would like to create several nested lists. I already know the number of elements the lists shall contain and now would like to define the size of the lists before entering data into them.

For the list on the highest level which is to contain 2 elements I used

`list_example <- vector(mode="list", 2)`

Now each of the two elements shall contain 3 elements: again lists which again contain lists and so on ...altogether I have 7 levels, that is a tree of 2*3*3*4*2*3*3 combinations. Is there a compact way to define the sizes of such a deeply nested list structure?

Thank you very much in advance!!

Answer

You can do that using a recursive function.

```
rec.list <- function(len){
if(length(len) == 1){
vector("list", len)
} else {
lapply(1:len[1], function(...) rec.list(len[-1]))
}
}
l <- rec.list(c(2, 3, 3, 4, 2, 3, 3))
```

Or perhaps with a 7-d list array? It might look bizarre at first, but it is a perfectly valid data structure.

```
l <- vector("list", 2*3*3*4*2*3*3)
dim(l) <- c(2, 3, 3, 4, 2, 3, 3)
l[[1,1,1,1,1,1,1]] <- "content"
```