[SOLVED] preallocate list in R

Issue

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?

Solution

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

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

Answered By – Luciano Selzer

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *