0

I am trying to create a list of lists in R but the interior list are only being stored as temp variables as I go through a loop and when I try to access one of the sub-lists inside of the larger list, I only receive the first element of the sub-list.

I found this answer R. how make list of lists in R? but it is not working for me and I think it might be due to the fact that I am not storing each list.

Here is my code:

list1 <- list(1,2,3,4,5)
allLists <- list()
for(i in 1:5){
    allLists[i] = list1
}
newlst = allLists[[3]]
newlst[2]
#[[1]]
#NULL

I wold like to be able to access all the lists within allLists but it does not let me. The value for newlst is 1 when I would like it to be the list (1,2,3,4,5)

RLave
  • 8,144
  • 3
  • 21
  • 37
CU_dev
  • 243
  • 1
  • 14
  • 1
    Do you want `allLists[[i]] <- list1` in the for-loop? – jogo May 28 '19 at 14:30
  • @jogo yes I think that is what I needed. I am new to R as of last Friday so I am not exactly sure what the double brackets really mean but your suggestion worked and I will look into what the double brackets do. Thank you. – CU_dev May 28 '19 at 14:36
  • https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el – jogo May 29 '19 at 07:55

1 Answers1

2

If we want to create a list of lists an option is replicate

replicate(5, list1, simplify = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • My actual application of this will be using different lists and adding them to one big list so I can store them. I only used l`list1` replicated 5x as a way to simplify my code for the question. But yes that would work if I needed `list1` several times in a big list. – CU_dev May 28 '19 at 14:35