[R] Scope and assignment: baffling

Peter Dalgaard pdalgd at gmail.com
Thu Apr 1 09:48:09 CEST 2010


Jeff Brown wrote:
> Hi,
> 
> The code below creates a value, x$a, which depending on how you access it
> evaluates to its initial value, or to what it's been changed to.  The last
> two lines should, I would have thought, evaluate to the same value, but they
> don't.
> 
> f <- function () {
> 	x <- NULL;
> 	x$a <- 0;
> 	x$get.a <- function () {
> 		x$a;
> 	};
> 	x$increment.a <- function () {
> 		x$a <<- x$a + 5;
> 	};
> 	x
> };
> x <- f();
> x$increment.a();
> x$get.a();
> x$a;
> 
> This can be repeated; each time you call x$increment.a(), the value
> displayed by x$get.a() changes, but x$a continues to be zero.
> 
> Is that totally weird, or what?

In a word, no. It's not the same x. (And R is not Java or C++). It
should be enlightening to try

evalq(x,environment(x$get.a))




-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list