Writing Efficient R Code
Colin Gillespie
Jumping Rivers & Newcastle University

// C code: request memory for a number
x = (double *) malloc(sizeof(double));
// Free the memory
free(x);
$$ 1, 2, \ldots, n $$
## Method 1
x <- 1:n
## Method 2
x <- vector("numeric", n) # length n
for(i in 1:n)
x[i] <- i
## Method 3
x <- NULL # Length zero
for(i in 1:n)
x <- c(x, i)
1:nn |
1 | 2 | 3 |
|---|---|---|---|
| $10^5$ | 0.00 | 0.02 | 0.2 |
| $10^6$ | 0.00 | 0.2 | 30 |
| $10^7$ | 0.00 | 2 | 3800 |

The first rule of R club: never, ever grow a vector.
Writing Efficient R Code