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.