R eval():当参数"envir"显式设置为默认值时更改了行为 [英] R eval(): changed behavior when argument 'envir' is explicitly set to default value

查看:39
本文介绍了R eval():当参数"envir"显式设置为默认值时更改了行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑函数 fun1().称为不会将值 2 分配给 .GlobalEnv 中的 xx .

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

eval()的参数 envir 的默认值为:

formals(eval)$envir
## parent.frame()

fun2()中,参数 envir 被显式设置为其默认值 parent.frame().调用 fun2() 确实 2 的值分配给 .GlobalEnv 中的 xx .

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

(已通过R版本3.5.0测试)

(Tested with R version 3.5.0)

为什么?这种行为是故意的吗?

推荐答案

在函数的评估框架中评估函数的默认值.显式参数在调用框架中求值.(这两种方法都可以通过非标准的评估技巧来更改,但是您并没有使用它们.)

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.)

因此,在您的第一个示例中, parent.frame()是对 eval()的调用的父级,即 fun1()的评估框架.在第二个示例中, parent.frame()是对 fun2()的调用的父代.

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().

这篇关于R eval():当参数"envir"显式设置为默认值时更改了行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆