【发布时间】:2019-11-06 17:36:26
【问题描述】:
f <- function() {
x <- 6 + 4
substitute(x)
}
f()
上面会输出:
[1] 10
但是,以下:
x <- 6 + 4
substitute(x)
输出:
x
它们为什么不同?
【问题讨论】:
标签: r metaprogramming substitution
f <- function() {
x <- 6 + 4
substitute(x)
}
f()
上面会输出:
[1] 10
但是,以下:
x <- 6 + 4
substitute(x)
输出:
x
它们为什么不同?
【问题讨论】:
标签: r metaprogramming substitution
@akrun 的回答展示了 如何 解决问题,但我认为您的“为什么?” 问题的答案在 ?substitute 中,上面写着在详情中:
如果是普通变量,则替换它的值,除非
env是.GlobalEnv,在这种情况下符号保持不变。
(强调我的。)当您在默认提示 > 上执行此操作时,您处于全局环境中。在您的第一个示例中,在函数的命名空间中并非如此。 (至于“为什么R-core会做出这种行为?”,我觉得我没有资格回答甚至推测。)
【讨论】:
substitute(X, list(X = x)) 是一种常见的用法,在这里可以使用
evaluation 没有发生
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
【讨论】: