preallocate list in R

25,285

Solution 1

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

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

Solution 2

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

Something like this:

   x <- vector('list', 10)

But using lapply is the best choice

Share:
25,285
Alex
Author by

Alex

Updated on January 06, 2022

Comments

  • Alex
    Alex over 2 years

    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?

  • Brian Albert Monroe
    Brian Albert Monroe about 6 years
    You could also just do x <- lapply(1:10, c) to avoid the anonymous function. It's 2.5 microseconds faster on my machine.
  • stevec
    stevec about 4 years
    I find myself back at this answer approximately every 2-3 months