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:
- First, we create a
lazyfunc
function withx
andy
as the argument, but only returnx
:>lazyfunc<- function(x, y){ + x + } >lazyfunc(3) [1] 3
- On the other hand, if the function returns the summation of
x
andy
but we do not passy
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.