R-alpha: Environment strangeness

Robert Gentleman rgentlem@stat.auckland.ac.nz
Wed, 30 Jul 1997 13:29:54 +1200 (NZST)


Peter Dalgaard asked about environments,

----- Begin Included Message -----

 
Maybe I'm just not understanding things well enough (actually, that's
why I was fooling around with this in the first place), but:

> g
function()
{
	e<-sys.frame(sys.parent())
	print(ls(envir=e))
	eval(print(b), e)
}
> f
function () 
{
        b <- 7913
        g()
}
> f()
[1] "b"
Error: Object "b" not found

Er? Is "b" in environment "e" or not?

 
----- End Included Message -----

Ross and I have been back and forth on this one a few times already;
it's probably a faq (Kurt);
  eval evaluates an expression in an environment; 
 consider the two cases below

1)
  a<-expression(x+y)
  eval(a,e1)

2)
  eval(x+y,e1)

 Now, there is no way these can both work. It seems like the first option
is to be preferred because the second can easily be achieved by wrapping
an expression around the x+y (with the first option as the default). Used in
this manner expression is a quoting mechanism.
 eval(expression(x+y),e1) does what you want.
 If 2) is the default mechanism then there is no easy way to get 1) to work
since what we want there is the value bound to a in the environment that
eval is called from not the value of a in e1.
  So Peter's example with a small change,
g<-function() {
	e<-sys.frame(sys.parent())
	print(ls(envir=e))
	eval(expression(print(b),e)
}

will work as desired.

robert
   
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-