问题
Consider the function fun1(). Calling it does not assign the value 2 to xx in .GlobalEnv.
fun1 <- function(x) eval(expr=substitute(x))
fun1({xx <- 2; xx})
## [1] 2
xx
## Error: object 'xx' not found
The default value of the argument envir of eval() is:
formals(eval)$envir
## parent.frame()
In fun2() the argument envir is explicitly set to its default value parent.frame(). Calling fun2() does assign the value 2 to xx in .GlobalEnv.
fun2 <- function(x) eval(expr=substitute(x), envir=parent.frame())
fun2({xx <- 2; xx})
## [1] 2
xx
## [1] 2
(Tested with R version 3.5.0)
Why is that? Is that behavior intended?
回答1:
Defaults to functions are evaluated in the evaluation frame of the function. Explicit arguments are evaluated in the calling frame. (Both of these can be changed by non-standard evaluation tricks, but you're not using those.)
So in your first example, parent.frame() is the parent of the call to eval(), i.e. the evaluation frame of fun1(). In your second example, parent.frame() is the parent of the call to fun2().
来源:https://stackoverflow.com/questions/53734536/r-eval-changed-behavior-when-argument-envir-is-explicitly-set-to-default-va