【发布时间】:2018-05-23 21:11:29
【问题描述】:
do.call 的文档指出:
如果
quote是FALSE,默认值,则计算参数(在调用环境中,而不是在envir中)。
这句话告诉我,当quote = FALSE 时,指定envir 没有区别。然而,事实并非如此,事实上我遇到过需要指定envir 才能使函数工作的情况。
最简单的可重现示例:
g1 <- function(x) {
args <- as.list(match.call())
args[[1]] <- NULL # remove the function call
do.call(print, args, quote = FALSE) # call print()
}
g2 <- function(x) {
args <- as.list(match.call())
args[[1]] <- NULL # remove the function call
do.call(print, args, quote = FALSE, envir = parent.frame()) # call print(), specifying envir
}
h1 <- function(x, y) {
g1(x*y)
}
h2 <- function(x, y) {
g2(x*y)
}
有了这些功能,h2() 的行为就像人们想象的那样,但h1() 却没有:
h1(2, 3)
#Error in print(x) : object 'y' not found
h2(2, 3)
#[1] 6
y <- 100
h1(2, 3)
#[1] 600
## Looks like g1() took the value of y from the global environment
h2(2, 3)
#[1] 6
谁能给我解释一下这里发生了什么?
注意:有一个相关的帖子here,但我阅读的答案并没有具体说明do.call() 对envir 变量的作用。
【问题讨论】:
标签: r