57

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?

Alex
  • 19,533
  • 37
  • 126
  • 195

4 Answers4

93

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

x <- vector(mode = "list", length = 10)
Luciano Selzer
  • 9,806
  • 3
  • 42
  • 40
25

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.

Justin
  • 42,475
  • 9
  • 93
  • 111
6

Something like this:

   x <- vector('list', 10)

But using lapply is the best choice

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
0

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)

To preallocate a vector

vec <- rep(NA, 10)
stevec
  • 41,291
  • 27
  • 223
  • 311