preallocate list in R
PerformanceRListMemoryPerformance Problem Overview
It is inefficient in R to expand a data structure in a loop. How do I preallocate a list
of a certain size? matrix
makes this easy via the ncol
and nrow
arguments. How does one do this in lists? For example:
x <- list()
for (i in 1:10) {
x[[i]] <- i
}
I presume this is inefficient. What is a better way to do this?
Performance Solutions
Solution 1 - Performance
vector
can create empty vector of the desired mode and length.
x <- vector(mode = "list", length = 10)
Solution 2 - Performance
To expand on what @Jilber said, lapply
is specially built for this type of operation.
instead of the for loop, you could use:
x <- lapply(1:10, function(i) i)
You can extend this to more complicated examples. Often, what is in the body of the for loop can be directly translated to a function which accepts a single row that looks like a row from each iteration of the loop.
Solution 3 - Performance
Something like this:
x <- vector('list', 10)
But using lapply is the best choice
Solution 4 - Performance
All 3 existing answers are great.
The reason the vector()
function can create a list is explained in JennyBC's purrr tutorial:
> A list is actually still a vector in R, but it’s not an atomic vector. We construct a list explicitly with list() but, like atomic vectors, most lists are created some other way in real life.
To preallocate a list
list <- vector(mode = "list", length = 10)
vector
To preallocate avec <- rep(NA, 10)