[R] Understanding eval

From: Charilaos Skiadas <cskiadas_at_gmail.com>
Date: Sat, 22 Dec 2007 15:30:34 -0500


After many hours of debugging code, I came to the conclusion that I have a fundamental misunderstanding regarding eval, and hope that someone here can explain to me, why the following code acts as it does:

foo <- function(expr) {

   eval(substitute(expr), envir=list(a=5), enclos=parent.frame()) }
bar <- function(er) {

   foo(er)
}

> foo(a)

[1] 5
> bar(a)

Error in eval(expr, envir, enclos) : object "a" not found

Now, regarding the "bar(a)" call, this is my understanding of what happens, hoping someone will correct me where I'm wrong.

  1. bar is called. Its evaluation frame contains the association "er=a".
  2. bar calls foo. So foo is called, and its evaluation frame contains the association "expr=er", with enclosing environment the local environment of bar.
  3. foo calls eval.
  4. eval starts by evaluating "substitute(expr)" in foo's environment. "substitute" then locates expr in foo's environment, and replaces it with er. So the result of this process is the symbol er, which is what will now be evaluated by eval.
  5. eval then creates the environment where this evaluation will take place. It does that by creating an environment containing the frame "a=5", and with enclosing environment the parent frame of foo, which is bar's environment.
  6. So, as I understand it, the symbol "er" is going to now be evaluated in an environment where a is set to 5 and er is set to a, along with whatever is in the user's workspace.
  7. So the first step now is looking up a definition for er. Nothing is found in the current frame, so the evaluation proceeds to bar's environment, where the association "er=a" is found, so er is replaced by a.
  8. Now, and perhaps this is where I misunderstand things, the lookup for a will take place. My thinking was that the lookup would start from the evaluation environment that eval created, and hence would locate the a=5 value. But this is clearly not what happens.

Anyway, hope someone will correct me where I'm wrong, and explain to me what I am doing wrong, and ideally how to diagnose such things.

Thanks,
Haris Skiadas
Department of Mathematics and Computer Science Hanover College



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sat 22 Dec 2007 - 20:34:42 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sun 23 Dec 2007 - 03:30:21 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.