哈德利高级R书中的非标准评估 [英] Non standard evaluation in Hadley's advanced R book
问题描述
在Hadley的高级R书中,有一段代码可以我无法理解输出.
In Hadley's Advanced R book, there is a piece of code that I cannot understand the output.
f <- function(x) substitute(x)
g <- function(x) deparse(f(x))
g(1:10)
g(x)
g(x + y ^ 2 / z + exp(a * sin(b)))
为什么它们都返回"x"
?尤其是当
Why do they all return "x"
? Especially when
g <- function(x) deparse(substitute(x))
按预期返回"1:10"
,"x"
和"x + y ^ 2 / z + exp(a * sin(b))"
.
推荐答案
首先,一些背景信息:promise是未经评估的参数.一个promise由两部分组成:1)导致这种延迟计算的代码/表达式(此代码可以由substitute
或pryr::promise_info
查看),以及2)创建该代码/表达式的环境并且应该进行评估(pryr::promise_info
可以查看此环境).
First, some background information: A promise is an unevaluated argument. A promises comprises of two parts: 1) the code / expression that gives rise to this delayed computation (this code can be viewed by substitute
or pryr::promise_info
), and 2) the environment where this code / expression is created and should be evaluated in (this environment can be viewed by pryr::promise_info
).
如果将g()
函数更改为
g <- function(x) deparse(f(whatever))
您将永远得到无论如何".这是因为g()
调用f(whatever)
时,它将一个promise对象传递给f()
-该对象具有代码whatever
和g()
的执行环境.然后,f()
中的substitute
查看此promise对象并返回该promise的代码/表达式,在这种情况下为whatever
.
you would always get "whatever". This is because when g()
calls f(whatever)
, it passes a promise object to f()
--this object has the code whatever
and the environment of g()
's execution environment. Then, the substitute
within f()
looks at this promise object and returns the code / expression of that promise, which is whatever
in this case.
可以通过运行以下代码来确认promise对象的代码和环境:
The code and the environment of the promise object can be confirmed by running the following code:
library(pryr) # need to install it
f <- function(x) {
print(promise_info(x))
substitute(x)
}
g <- function(x) {
print(environment())
f(whatever)
}
g(1:10)
最重要的是,您将获得传递给f(whatever)
的所有信息.这就是为什么分离这些功能不是一个好主意的原因.一种解决方法是使用
The bottom line is you'll get back whatever you pass to f(whatever)
. That's why it's not a good idea to separate these functions. One work around would be to use
g <- function(...) deparse(f(...))
通过这种方式,参数将传递给f()
,而不会在g()
中重命名.
This way the parameter is passed through to f()
and not renamed in g()
.
另一方面,g <- function(x) deparse(substitute(x)); g(1:10)
产生1:10
的原因是,在这种情况下,substitute
正在查看承诺对象x
(与上述情况下的承诺对象whatever
相反).承诺x
在此处具有代码1:10
和环境R_GlobalEnv
. (同样,可以使用g <- function(x) { print(promise_info(x) ; deparse(substitute(x))
进行检查.因此substitute(x)
会按预期返回1:10
.
On the other hand, g <- function(x) deparse(substitute(x)); g(1:10)
produces 1:10
because, in this case, substitute
is looking at promise object x
(in contrasts to the promise object whatever
in the above case). Promise x
here has the code 1:10
and the environment R_GlobalEnv
. (Again, this can be checked using g <- function(x) { print(promise_info(x) ; deparse(substitute(x))
. So substitute(x)
returns 1:10
as expected.
这篇关于哈德利高级R书中的非标准评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!