Performing lazy evaluation

R functions evaluate arguments lazily; the arguments are evaluated as they are needed. Thus, lazy evaluation reduces the time needed for computation. In the following recipe, we will demonstrate how lazy evaluation works.

Getting ready

Ensure that you completed the previous recipes by installing R on your operating system.

How to do it...

Perform the following steps to see how lazy evaluation works:

  1. First, we create a lazyfunc function with x and y as the argument, but only return x:
    >lazyfunc<- function(x, y){
    + x
    + }
    >lazyfunc(3)
    [1] 3
    
  2. On the other hand, if the function returns the summation of x and y but we do not pass y into the function, an error occurs:
    >lazyfunc2<- function(x, y){
    + x + y
    + }
    >lazyfunc2(3)
    Error in ...

Get R for Data Science Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.