Section 12 Optimisation of R code
12.1 Vectorised code
Identify the part of code that can take advantage of logical test, subsetting and element-wise execution. That part of code certainly can be vectorised.
Many pre-existing R fucntions are already vectorised and optimised to perform efficiently. Many of these functions are actually written in C and Fortran lanugages.
If a combination of
ifandforloop is required, it is more likely that the code could be vectorised.Explore if you can use the
applyfunctions which are optimised to run faster.Identify the operations that could be done outside the
forloop.Define the storage size of the vector before executing the
forloop.
12.2 Example 1
abs_loop <- function(x){
for(i in 1:length(x)){
if(x[i] < 0){
x[i] <- x[i]*(-1)
}
}
return(x)
}
abs_vec <- function(x){
x[x < 0] * (-1)
return(x)
}
a <- rep(c(-1,1), length=5000000)
system.time(abs_loop(a))
system.time(abs_vec(a))
system.time(abs(a))- Note: R built-in function
absis optimised to execute the operation of calculating absolute values more efficiently.