[r] Appending a list to a list of lists in R

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.

This question is related to r list matrix append extend

The answer is


By putting an assignment of list on a variable first

myVar <- list()

it opens the possibility of hiearchial assignments by

myVar[[1]] <- list()
myVar[[2]] <- list()

and so on... so now it's possible to do

myVar[[1]][[1]] <- c(...)
myVar[[1]][[2]] <- c(...)

or

myVar[[1]][['subVar']] <- c(...)

and so on

it is also possible to assign directly names (instead of $)

myVar[['nameofsubvar]] <- list()

and then

myVar[['nameofsubvar]][['nameofsubsubvar']] <- c('...')

important to remember is to always use double brackets to make the system work

then to get information is simple

myVar$nameofsubvar$nameofsubsubvar

and so on...

example:

a <-list()
a[['test']] <-list()
a[['test']][['subtest']] <- c(1,2,3)
a
$test
$test$subtest
[1] 1 2 3


a[['test']][['sub2test']] <- c(3,4,5)
a
$test
$test$subtest
[1] 1 2 3

$test$sub2test
[1] 3 4 5

a nice feature of the R language in it's hiearchial definition...

I used it for a complex implementation (with more than two levels) and it works!


This answer is similar to the accepted one, but a bit less convoluted.

L<-list()
for (i in 1:3) {
L<-c(L, list(list(sample(1:3))))
}

outlist <- list(resultsa)
outlist[2] <- list(resultsb)
outlist[3] <- list(resultsc)

append's help file says it is for vectors. But it can be used here. I thought I had tried that before but there were some strange anomalies in the OP's code that may have mislead me:

outlist <- list(resultsa)
outlist <- append(outlist,list(resultsb))
outlist <- append(outlist,list(resultsc))

Same results.


Just a note on Brian's answer below, the first assignment to outlist can also be an append statement so you could also do something like this:

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

outlist <- list()
outlist <- append(outlist,list(resultsa))
outlist <- append(outlist, list(resultsb))
outlist <- append(outlist, list(resultsc))

This is sometimes helpful if you want to build a list from scratch in a loop.


The purrr package has a lot of handy functions for working on lists. The flatten command can clean up unwanted nesting.

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

nested_outlist <- list(resultsa, resultsb, resultsc)
outlist <- purrr::flatten(nested_outlist)

There are two other solutions which involve assigning to an index one past the end of the list. Here is a solution that does use append.

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

outlist <- list(resultsa)
outlist <- append(outlist, list(resultsb))
outlist <- append(outlist, list(resultsc))

which gives your requested format

> str(outlist)
List of 3
 $ :List of 5
  ..$ : num 1
  ..$ : num 2
  ..$ : num 3
  ..$ : num 4
  ..$ : num 5
 $ :List of 5
  ..$ : num 6
  ..$ : num 7
  ..$ : num 8
  ..$ : num 9
  ..$ : num 10
 $ :List of 5
  ..$ : num 11
  ..$ : num 12
  ..$ : num 13
  ..$ : num 14
  ..$ : num 15

Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to matrix

How to get element-wise matrix multiplication (Hadamard product) in numpy? How can I plot a confusion matrix? Error: stray '\240' in program What does the error "arguments imply differing number of rows: x, y" mean? How to input matrix (2D list) in Python? Difference between numpy.array shape (R, 1) and (R,) Counting the number of non-NaN elements in a numpy ndarray in Python Inverse of a matrix using numpy How to create an empty matrix in R? numpy matrix vector multiplication

Examples related to append

List append() in for loop ValueError: all the input arrays must have same number of dimensions Append a tuple to a list - what's the difference between two ways? How merge two objects array in angularjs? How to add an element at the end of an array? Appending a list or series to a pandas DataFrame as a row? Can someone explain how to append an element to an array in C programming? How to append elements at the end of ArrayList in Java? Append value to empty vector in R? How to append new data onto a new line

Examples related to extend

Appending a list to a list of lists in R Javascript: Extend a Function What is the syntax to insert one list into another list in python? What is the difference between Python's list methods append and extend?