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!!
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.
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.
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]]
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 .
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With