Preallocate Memory

In R, you don’t have to explicitly allocate memory before you use it. For example, you could fill an array with numbers using the following code:

v <- c()
for (i in 1:100000) {v[i] <- i;}

This code works correctly; however, it takes a long time to finish (about 30 seconds on my computer). You can speed up this code substantially by preallocating memory to the vector. You can do this by setting the length, nrow, ncol, or dim attributes for an object. Here is an example:

v2 <- c(NA)
length(v2) <- 100000
for (i in 1:100000) {v2[i] <- i;}

This code works identically but performs much, much faster.

Get R in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.