这是借自shiny's http://shiny.rstudio.com/功能exprToFunction https://github.com/rstudio/shiny/blob/master/R/utils.R#L382这是在他们使用的reactive https://github.com/rstudio/shiny/blob/master/R/reactives.R#L437功能。
实际问题
如何延迟表达式的计算(例如通过 arg 指定expr
)以便在调用 S4 方法(而不是标准 R 函数)时“捕获”其内容?
Example
注意x_1
does not尚存在,这就是为什么我们要推迟评估expr
并只是“捕获”其内容。
功能captureExpression
:
captureExpression <- function(
expr,
caller_offset = 1,
brackets = TRUE
) {
out <- eval(substitute(substitute(expr)), parent.frame(caller_offset))
if (brackets && class(out) != "{") {
out <- substitute({CODE}, list(CODE = out))
}
out
}
captureExpression(x_1 * 2)
# {
# x_1 * 2
# }
Passing 未评估的 expr
through 在调用标准 R 函数时有效:
foo <- function(expr) {
captureExpression(expr = expr)
}
foo(x_1 * 2)
# {
# x_1 * 2
# }
Passing 未评估的 expr
调用 S4 方法时 through 不起作用:
setGeneric(
name = "bar",
signature = c(
"expr"
),
def = function(
expr,
...
) {
standardGeneric("bar")
}
)
setMethod(
f = "bar",
signature = signature(
expr = "ANY"
),
definition = function(
expr,
...
) {
captureExpression(expr = expr, ...)
})
应用S4方法:
bar(x_1 * 2)
# Error in bar(x_1 * 2) :
# error in evaluating the argument 'expr' in selecting a method for function 'bar': Error:
# object 'x_1' not found
bar(x_1 * 2, caller_offset = 2)
# Error in bar(x_1 * 2, caller_offset = 2) :
# error in evaluating the argument 'expr' in selecting a method for function 'bar': Error:
# object 'x_1' not found
bar(x_1 * 2, caller_offset = 3)
# Error in bar(x_1 * 2, caller_offset = 3) :
# error in evaluating the argument 'expr' in selecting a method for function 'bar': Error:
# object 'x_1' not found
我想这与方法分派的实际执行方式有关。然而,也许有一种方法可以做到这一点。