元编程和 R 中的替代函数
meta-programming and the substitute function in R
f <- function() {
x <- 6 + 4
substitute(x)
}
f()
以上将输出:
[1] 10
然而,以下:
x <- 6 + 4
substitute(x)
输出:
x
为什么不同?
eval
估值没有发生
eval(substitute(x))
#[1] 10
正如@r2evans 展示的文档描述,我们可以在新环境中对其进行测试以查看实际效果
# create the object in another environment
e1 <- new.env()
e1$x <- 6 + 4
substitute(x) # here x is looked in the global space
#x
substitute(x, env = e1) # specify the `env` and looks for the local env
#[1] 10
@akrun 的回答演示了如何 解决问题,但我认为你的问题“为什么?” 的答案是在 ?substitute
中,它在详细信息中说:
If it is an ordinary variable, its value is substituted, unless env
is .GlobalEnv
in which case the symbol is left unchanged.
(强调我的。)当您在默认提示 >
上执行此操作时,您处于全局环境中。在您的第一个示例中,在函数的命名空间内并非如此。 (至于"Why did R-core decide on this behavior?",我觉得我没有资格回答甚至推测。)
f <- function() {
x <- 6 + 4
substitute(x)
}
f()
以上将输出:
[1] 10
然而,以下:
x <- 6 + 4
substitute(x)
输出:
x
为什么不同?
eval
估值没有发生
eval(substitute(x))
#[1] 10
正如@r2evans 展示的文档描述,我们可以在新环境中对其进行测试以查看实际效果
# create the object in another environment
e1 <- new.env()
e1$x <- 6 + 4
substitute(x) # here x is looked in the global space
#x
substitute(x, env = e1) # specify the `env` and looks for the local env
#[1] 10
@akrun 的回答演示了如何 解决问题,但我认为你的问题“为什么?” 的答案是在 ?substitute
中,它在详细信息中说:
If it is an ordinary variable, its value is substituted, unless
env
is.GlobalEnv
in which case the symbol is left unchanged.
(强调我的。)当您在默认提示 >
上执行此操作时,您处于全局环境中。在您的第一个示例中,在函数的命名空间内并非如此。 (至于"Why did R-core decide on this behavior?",我觉得我没有资格回答甚至推测。)