Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested lists: how to define the size before entering data

Tags:

r

nested-forms

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!!

like image 437
Vero Avatar asked Jul 10 '13 09:07

Vero


People also ask

How do I find the size of a nested list?

To find the shape (or dimensions) of a nested list or tuple in Python, iterate over each element in the list or tuple and identify its length with the built-in len() function.

How do you define a nested list?

A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if you want to create a matrix or need to store a sublist along with other data types.

How do you implement a nested list?

We can add an element to a nested list with the append() function. In our example, we create a list and append it to one of our existing lists from above. This should result in this list: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2], [8, 7, 6]]

How do you check if an element is in a nested list Python?

Using index() method First, iterate through the sublist in the nested list, then check if that particular element exists in that sub_list . If it exists, find the index of the sub_list and the index of the element in that sub_list .


1 Answers

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"
like image 137
Backlin Avatar answered Oct 03 '22 02:10

Backlin