R eval(): changed behavior when argument 'envir' is explicitly set to default value

送分小仙女□ 提交于 2020-02-05 04:57:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!