preallocate list in R preallocate list in R r r

preallocate list in R


vector can create empty vector of the desired mode and length.

x <- vector(mode = "list", length = 10)


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.


Something like this:

   x <- vector('list', 10)

But using lapply is the best choice