Skip to content
Prev 44514 / 398502 Next

pass by reference -- how to do it

[sorry if this appears twice. I had an email problem and am
sending it out again]
 
As you and Andy correctly point out, <<- searches through
its environments and it may find a match prior to the Global
Environment.

On the other hand, while its possible to get into trouble,
I believe its actually not that likely since avoiding
nested functions is all you have to do.

For example, we can modify the previous example to make it
NOT work like this. With g nested in f, g's x refers to f's x,
not the global x:

f <- function(x) { g <- function() x[1] <<- x[1]+1; g() } # g nested 
x <- 1:5
f(x)
x # x unchanged since x in g matches x in f, not the global x

However, by simply defining g at the top level rather than
nesting it in f2, the code does work to modify the global x
despite the fact that f2 defines its own x:

g <- function() x[1] <<- x[1]+1 # g at not level, i.e. not nested
f2 <- function(x) g()
x <- 1:5
f2(x)
x # c(2,2,3,4,5)

The fact that its this easy to guarantee that it works seems to
be one of the advantages of R's lexical scoping.

---
Date: Thu, 19 Feb 2004 10:11:50 -0000 
From: Simon Fear <Simon.Fear at synequanon.com>
To: <ggrothendieck at myway.com>, <robert_dodier at yahoo.com>, <r-help at stat.math.ethz.ch> 
Subject: RE: [R] pass by reference -- how to do it 


For the record, be careful: <<- does not necessarily assign to 
the global environment. In R ` x <<- value` assigns `value` to 
the first instance of `x` it can find using lexical scoping. Only if it 
doesn't find any such variable, it will indeed create an `x` 
in .GlobalEnv.

Tricky for those brought up on S-Plus, where assignment <<- 
is guaranteed to assign to frame 1. 

HTH