Reputation: 19803
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?
Upvotes: 59
Views: 29211
Reputation: 52238
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.
list <- vector(mode = "list", length = 10)
vec <- rep(NA, 10)
Upvotes: 1
Reputation: 43255
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.
Upvotes: 25
Reputation: 61154
Something like this:
x <- vector('list', 10)
But using lapply is the best choice
Upvotes: 6
Reputation: 10016
vector
can create empty vector of the desired mode and length.
x <- vector(mode = "list", length = 10)
Upvotes: 98