I'm having issues appending data to a list which is already in a list format. I have a program which will export results objects during a simulation loop. The data itself is stored as a list of matrices. My idea is to store those lists in a list, and then save this list of lists as an R object for later analysis, however I'm having some issues achieving this correctly. I'll show what I've done with small abstract example just using values instead of the matrix data from my simulation:
Say I've run the simulation loop for 3 times. During the iterations, the results lists need to be collected into the one list of lists that I will save as an R object:
List to contain the other lists and be saved:
outlist1 <- list()
First iteration:
resultsa <- list(1,2,3,4,5)
outlist <- append(outlist1,resultsa)
Second Iteration:
resultsb <- list(6,7,8,9,10)
outlist <- append(outlist1,b)
Third Iteration:
resultsc <- list(11,12,13,14,15)
outlist <- list(outlist2,c)
However, this solution does not work with growing a list containing lists this way, the desired result is:
>outlist
[[1]]
[[1]][[1]]
[1] 1
[[1]][[2]]
[1] 2
[[1]][[3]]
[1] 3
[[1]][[4]]
[1] 4
[[1]][[5]]
[1] 5
[[2]]
[[2]][[1]]
[1] 6
[[2]][[2]]
[1] 7
[[2]][[3]]
[1] 8
[[2]][[4]]
[1] 9
[[2]][[5]]
[1] 10
[[3]]
[[3]][[1]]
[1] 11
[[3]][[2]]
[1] 12
[[3]][[3]]
[1] 13
[[3]][[4]]
[1] 14
[[3]][[5]]
[1] 15
However, instead what I get is:
> outlist3
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] 1
[[1]][[1]][[2]]
[1] 2
[[1]][[1]][[3]]
[1] 3
[[1]][[1]][[4]]
[1] 4
[[1]][[1]][[5]]
[1] 5
[[1]][[2]]
[[1]][[2]][[1]]
[1] 6
[[1]][[2]][[2]]
[1] 7
[[1]][[2]][[3]]
[1] 8
[[1]][[2]][[4]]
[1] 9
[[1]][[2]][[5]]
[1] 10
How do I grow a list, such that the resulting list formatted is like the desired result? If I do further analysis on these list I need to be able to easily access the elements.
Could it be this, what you want to have:
# Initial list:
myList <- list()
# Now the new experiments
for(i in 1:3){
myList[[length(myList)+1]] <- list(sample(1:3))
}
myList