【发布时间】:2012-06-20 01:53:07
【问题描述】:
在我的 R 开发中,我需要将函数原语包装在 proto 对象中,以便在调用对象的 $perform() 方法时可以自动将许多参数传递给函数。函数调用在内部通过do.call() 进行。一切都很好,除非函数试图从定义它的闭包中访问变量。在这种情况下,该函数无法解析名称。
这是我发现的最小的重现该行为的示例:
library(proto)
make_command <- function(operation) {
proto(
func = operation,
perform = function(., ...) {
func <- with(., func) # unbinds proto method
do.call(func, list(), envir=environment(operation))
}
)
}
test_case <- function() {
result <- 100
make_command(function() result)$perform()
}
# Will generate error:
# Error in function () : object 'result' not found
test_case()
我有一个可重现的testthat 测试,它还输出大量诊断输出。诊断输出让我难过。通过查找父环境链,位于函数内部的我的诊断代码找到并打印了函数未能找到的相同变量。 See this gist.。
如何正确设置do.call的环境?
【问题讨论】: