[R] A question regarding R scoping

William Dunlap wdunlap at tibco.com
Fri Aug 7 19:29:43 CEST 2009

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Ivo Shterev
> Sent: Friday, August 07, 2009 9:36 AM
> To: murdoch at stats.uwo.ca; markleeds at verizon.net
> Cc: r-help at r-project.org
> Subject: Re: [R] A question regarding R scoping
> Dear All,
> Sorry for the introduced confusion. My question is to have a 
> function (in my case f1) that just takes an argument and 
> modifies it (no copies, no returns). This can be done by:
> f1 = function(i){i <<- 1}
> Then this function is called by another function (in my case 
> f2) that just initializes the above mentioned argument and 
> calls f1, like this
> f2 = function(n){
> ##whatever initialization on i
> f1(i)
> print(i)
> }
> Obviously in my code example f1 "loses" its ability to modify 
> its argument, so the question is how to modify f2 so that it 
> prints out 1. 

In general, S functions do not modify their arguments.
However functions defined in the form
     `f`1<-` <- function(x, ..., value) { # last argument must be called
          newx <- someFunctionOf(x, ..., value)
and called as
     f1(x) <- myValue
will alter x, giving it the value of someFunctionOf(x,myValue).
(Do not call `f1<-` directly, as new<-`f1<-`(x,value=value).) 

In any case, only things on the left side of the
assignment operator will be assigned to.

If you write such a 'replacement function' it is good form to write
an extraction function to do the inverse, as then you can nest
the replacement function calls, as in f1(x)[1:2] <- myValue.

In your case you could write such a function that ignored the
value argument and just returned 1
     `f1<-` <- function(x, value)   1
but you would have to call it in the required form
     f1(x) <- "ignoredValue"
    > `f1<-` <- function(x, value) 1
    > x<-c(pi, 1i, exp(1))
    > k
    [1] 3.141593+0i 0.000000+1i 2.718282+0i
    > f1(k) <- "ignored"
    > k
    [1] 1

You might make use of the value argument so that, e.g., 'initial' meant
to give a suitable starting value and 'terminal' would give it whatever
value meant the procedure was over.  The extraction function could
then return 'initial' or 'terminal' or 'in progress'.

Bill Dunlap
TIBCO Software Inc - Spotfire Division
wdunlap tibco.com  

> -ivo
> ... 

More information about the R-help mailing list