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?
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.
"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.
vector
can create empty vector of the desired mode and length.
x <- vector(mode = "list", length = 10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With