[R] passing parameters to an R script

Stavros Macrakis macrakis at alum.mit.edu
Sat Jan 3 22:19:02 CET 2009


R's variable passing mechanism is not call by value, but a mixture of
unevaluated arguments (like the obsolete Lisp FEXPR) and call-by-need.
 It is like FEXPR in that the function can capture the unevaluated
argument (using 'substitute').  But it is like call-by-need in that
normal use of the argument (without 'substitute') evaluates the
expression the first time the variable is evaluated and caches the
result as the value of the variable.  If the argument's value is never
evaluated, the argument is not evaluated.

For example:

 (function(x){print(1);x;print(2);x;print(substitute(x));4})(print(3))
[1] 1   << prints 1 before evaluating argument
[1] 3   << evaluates argument
[1] 2   << after evaluating argument
             << x has already been evaluated; is not reevaluated
print(3)  << quoted argument
[1] 4   << returns 4

You will sometimes here the terms call-by-name or lazy evaluation used
to describe R's mechanism, but those mean quite different things in
other programming languages, so it's best to avoid those terms.

So it is in fact possible to 'capture' a variable and modify it:

     increment <- function(var) eval(substitute(var<-var+1),parent.frame())
     x<-23
     increment(x)
     x  ==> 24

The 'substitute' operates in the function's own frame, so 'var'
evaluates to the argument; but then the evaluation is specified to
happen in the parent frame.

That said, as a general rule, it is very poor practice to do this sort of thing.

               -s

On Sat, Jan 3, 2009 at 1:32 PM,  <mauede at alice.it> wrote:
> I knowf R functions ca be called passing some parameters.
> My first question is: how are parameters passed to R functions ?
> Browsing through R archives I found an answer confirming taht parameters can
> be passed to the  called function by value. I wonder whether passing the parameter
> address is possible somehow to allow the function to actually change its value.




More information about the R-help mailing list