How to do it…

Write a function using a for loop to execute the targeted operation. Also, write another function without using a loop. Let's take a look at the following steps and see how we can do the preceding two tasks:

  1. Execute the following code snippet that depicts a function using a loop:
        loopOperation <- function(mat){
out<-matrix(NA, nrow = ncol(mat), ncol = ncol(mat))
for(i in 1:ncol(mat)){
for(j in 1:ncol(mat)){
colI <- mat[,i]
colJ <- mat[,j]
out[i,j] <- t(colI) %*% colJ
}
}
return(out)
}
  1. Execute another function without using the loop, but use only the matrix operation as shown in the following code snippet:
        vectorizedOp <- function(mat){
return(t(mat) %*% mat)
}

library(microbenchmark) # To compare performance of the functions
microbenchmark(loopOperation(mat = binMat), vectorizedOp(mat = binMat))
Unit: milliseconds
expr min lq mean
vectorized(mat=binMat) 7.009144 9.30052 10.67089
loopOperation(mat=binMat) 6826.260664 7476.98113 7766.50789


median uq max neval cld
9.89367 11.8099 21.3325 100 a
7650.74206 8115.6440 9333.9608 100 b
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset