Aan de slagGa gratis aan de slag

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
}

Deze oefening maakt deel uit van de cursus

Writing Efficient R Code

Cursus bekijken

Oefeninstructies

The growing() function has already been defined in your workspace.

  • Using the system.time() function, find how long it takes to generate n = 30000 random standard normal numbers using the growing() function. Use the <- trick to store the result in a vector called res_grow.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# Use <- with system.time() to store the result as res_grow
system.time(___ <- ___)
Code bewerken en uitvoeren