Timings - growing a vector
Growing a vector is one of the deadly sins in R; you should always avoid it.
The growing()
function defined below generates n
random standard normal numbers, but grows the size of the vector each time an element is added!
Note: Standard normal numbers are numbers drawn from a normal distribution with mean 0 and standard deviation 1.
n <- 30000
# Slow code
growing <- function(n) {
x <- NULL
for(i in 1:n)
x <- c(x, rnorm(1))
x
}
This exercise is part of the course
Writing Efficient R Code
Exercise instructions
The growing()
function has already been defined in your workspace.
- Using the
system.time()
function, find how long it takes to generaten = 30000
random standard normal numbers using thegrowing()
function. Use the<-
trick to store the result in a vector calledres_grow
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Use <- with system.time() to store the result as res_grow
system.time(___ <- ___)