51

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
  • 18,593
  • 36
  • 118
  • 187

4 Answers4

83

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

x <- vector(mode = "list", length = 10)
Luciano Selzer
  • 9,466
  • 3
  • 41
  • 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
  • 41,121
  • 9
  • 89
  • 109
6

Something like this:

   x <- vector('list', 10)

But using lapply is the best choice

Jilber Urbina
  • 53,125
  • 10
  • 108
  • 134
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
  • 27,285
  • 13
  • 133
  • 181