[R] return value of {....}

Leonard Mada |eo@m@d@ @end|ng |rom @yon|c@eu
Thu Jan 12 21:14:45 CET 2023


Dear Akshay,

The best response was given by Andrew. "{...}" is not a closure.

This is unusual for someone used to C-type languages. But I will try to 
explain some of the rationale.

In the case that "{...}" was a closure, then external variables would 
need to be explicitly declared before the closure (in order to reuse 
those values):
intermediate = c()
{
     intermediate = ...;
     result = someFUN(intermediate);
}

1.) Interactive Sessions
This is cumbersome in interactive sessions. For example: you often 
compute the mean or the variance as intermediary results, and will need 
them later on as well. They could have been computed outside the 
"closure", but writing code in interactive sessions may not always be 
straightforward.

2.) Missing arguments
f = function(x, y) {
     if(missing(y)) {
         # assuming x = matrix
         y = x[,2]; x = x[,1];
     }
}
It would be much more cumbersome to define/use a temporary tempY.

I hope this gives a better perspective why this is indeed a useful 
feature - even if it is counterintuitive.

Sincerely,

Leonard



More information about the R-help mailing list