[R] `eval' and environment question

Joerg van den Hoff j.van_den_hoff at fzd.de
Tue Nov 13 14:39:28 CET 2007


my   understanding   of   `eval'   behaviour   is  obviously
incomplete.

my    question:   usually   `eval(expr)'   and   `eval(expr,
envir=parent.frame())' should be identical.   why  does  the
last  `eval'  (yielding `r3') in this code _not_ evaluate in
the local environment of function  `f'  but  rather  in  the
global environment (if `f' is called from there)?

#----------------------------------------------------------
f <- function () {

   a <- 1
   x <- 1

   model        <- y ~ a * x
   fitfunc      <- deriv(model[[3]], c("a"), c("a", "x"))
   call.fitfunc <- c(list(fitfunc), as.name("a"), as.name("x"))
   call.fitfunc <- as.call(call.fitfunc)

   curenv <- environment()

   cat(" eval(call.fitfunc)\n")
   r1 = eval(call.fitfunc)
   str(r1)

   cat(" eval(call.fitfunc, envir = curenv)\n")
   r2 = eval(call.fitfunc, envir = curenv)
   str(r2)

   cat(" eval(call.fitfunc, envir = parent.frame())\n")
   r3 = eval(call.fitfunc, envir = parent.frame())
   str(r3)

}
#----------------------------------------------------------


`args(eval)' yields:

"function (expr, envir = parent.frame(), enclos = if (is.list(envir) || 
    is.pairlist(envir)) parent.frame() else baseenv())"


and  the manpage says the same: the default value of `envir'
is `parent.frame()'. so I  would  expect  (lazy  evaluation)
that  providing  the  default argument explicitely should'nt
alter the behaviour. where is my error?

regards,

joerg



More information about the R-help mailing list