As you can see, R does not use lazy bounds in the general sense. But R provides this functionality, if you need it, with the delayedAssign()
function, as shown below:
> system.time(y <- sample(1E8)) user system elapsed 7.636 0.128 7.766 > system.time(length(y)) user system elapsed 0 0 0 system.time(delayedAssign("x", sample(1E8))) user system elapsed 0.000 0.000 0.001 > system.time(length(x)) user system elapsed 7.680 0.096 7.777
As you can see, y
is evaluated immediately, so no time is needed to determine the length of y
. x
, on the other hand, is not evaluated when it is created, only the promise to evaluate x
returned by delayedAssign()
, and only when we really need the value of x
, in this case, to determine its length, x
.
It doesn’t matter if the expression is placed in the function or executed in the global environment, therefore, encapsulating the expression inside the function that you did in your example actually does not add anything, so I excluded it, But if you want to be sure, try:
af <- function(z) { delayedAssign("x", sample(1E8)); return(z+1) } system.time(af(0)) user system elapsed 0 0 0
source share