scoping issues (was help with eval)
You intended quote() rather than expression(), I believe. If I do
show.a <- function(a) {a}
eval(quote(show.a(a)),envir=my.env)
this works. R has lexical scoping, so with
show.a <- function() {a}
'a' is looked for in the frame of the function (not defined there) and then in the environment of the function.
environment(show.a)
<environment: R_GlobalEnv>
since show.a was defined in the workspace. The envir arg of eval() is
used to find the object(s), here `show.a', not to sets its environment.
So my first version works because 'a' is part of the expression.
Perhaps you intended something like
init.env <- function() {
a <- 200
show.a <- function() {a}
environment()
}
my.env <- init.env()
eval(quote(show.a()),envir=my.env)
which works, and is a common R idiom (although via local() or new.env()).
However, you could just do
eval(quote(a), envir=my.env)
[1] 200
eval(expression(a), envir=my.env)
[1] 200 BTW, use typeof() to see the difference here.
On Fri, 13 May 2005, Whit Armstrong wrote:
I've been looking at the help page for eval for a while, but I can't
make sense of why this example does not work.
show.a <- function() {
a
}
init.env <- function() {
a <- 200
environment()
}
my.env <- init.env()
ls(envir=my.env)
# returns this:
# > ls(envir=my.env)
# [1] "a"
# but this does not work:
eval(expression(show.a()),envir=my.env)
# > eval(expression(show.a()),envir=my.env)
# Error in show.a() : Object "a" not found
# >
The help page gives the following:
'eval' evaluates the expression 'expr' argument in the environment
specified by 'envir' and returns the computed value. If 'envir' is
not specified, then 'sys.frame(sys.parent())', the environment
where the call to 'eval' was made is used.
I would be grateful for any help.
Thanks,
Whit
[[alternative HTML version deleted]]
______________________________________________ R-help at stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595