Skip to Content
Modern R Programming Cookbook
book

Modern R Programming Cookbook

by Jaynal Abedin
October 2017
Beginner to intermediate
236 pages
7h 38m
English
Packt Publishing
Content preview from Modern R Programming Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

R Cookbook, 2nd Edition

R Cookbook, 2nd Edition

JD Long, Paul Teetor

Publisher Resources

ISBN: 9781787129054Supplemental Content