Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preallocate list in R

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?

like image 847
Alex Avatar asked Sep 17 '12 17:09

Alex


People also ask

What does it mean to Preallocate a vector?

If you preallocate a vector you will end up calling the default constructor for each element to make empty elements, and then copying the item over the space later. If you add elements it can just copy or construct the element in place which may be more efficient. Follow this answer to receive notifications.

What is Preallocate memory?

"Pre-allocated memory" means that a program should allocate all the required memory blocks once after startup (using the new operator, as usual), rather than allocate memory multiple times during execution and leave memory which is no longer needed for the garbage collector to free.


1 Answers

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

x <- vector(mode = "list", length = 10) 
like image 95
Luciano Selzer Avatar answered Oct 12 '22 06:10

Luciano Selzer