Common R Portfolio

Vectorization As a general rule of thumb, we want to avoid writing for-loops as much as possible, and instead vectorize operations to speed up our calculations. For example suppose that we want to calculate \[\sum_{i=1}^n\cos(i) \times \sin(i) \times \tan(i) - \cos(i)^2-\sin(i)^3\] At first one could write a function similar to this: myfunc <- function(n){ total = 0 for (i in 1:n){ total = total + cos(i)*sin(i)*tan(i) - cos(i)^2 - sin(i)^3 } return(total) } We can see see how long a function takes to run in R by using the system.

Continue reading

Author's picture

Mauro Camara Escudero

PhD student in Computational Statistics and Data Science at the University of Bristol

COMPASS PhD Student

Bristol, United Kingdom