Add elements to a deeply nested list

Viewed 70

I am trying to populate a deeply nested list - a 4 level list like this :-

mylist <- vector(5, mode = "list")
for (i in 1:5)
    {for (j in 1:2)
        {for (k in 1:3)
            {for (m in 1:4)
                {mylist[[i]][[j]][[k]][[m]] <- m
                }
            }
        }
    }

Obviously I am doing something wrong but don't know what. I have a list called 'mylist' - a vector of model 'list'

At the highest level, this is a 5 item list as shown by 5 values of 'i'. Now each of these 5 items are list of 2 items as shown by value of 'j'. Again, each of these 2 items are list of 3 items as shown by value of 'k'. Finally, this item is a list of 4 items shown by value of 'm'.

The idea is to populate 'mylist' variable with a certain value - I have made that value equal to 'm' for simplicity but its going to be different value - in fact its going to be the output from a regression. But that doesn't matter - obviously, but what does is how to do it and I can't get it going.

It seems to work with values of all of the variables have a value of 1. It also works when 'i' = 1, 'j' = 1, 'k' = 1 and for all values of 'm' (that is 'm' going from 1:4. However, got the 'subscript out of bounds error' when 'j' goes beyond 1. Not sure if that would be the case with values of 'k' also being greater than 1 (in my real case, k went from 1:1) - so, couldn't test it.

Any suggestions, where am I going wrong?

Best regards

Deepak

1 Answers

You need to initiate the items ie l[[i]]<-vector(2, mode = "list") and so on

mylist <- vector(5, mode = "list")
for (i in 1:5){
    mylist[[i]] <- vector(2, mode = "list")
    for (j in 1:2){   
        mylist[[i]][[j]] <- vector(2, mode = "list") 
        for (k in 1:3){   
            mylist[[i]][[j]][[k]] <- vector(3, mode = "list")
            for (m in 1:4){   
                mylist[[i]][[j]][[k]][[m]] <- m
            }
        }
    }
}

Also the older code works with j=k=1 because variables by default are treated as one element vectors in R.

Related