R S4上下文中表达式的非标准评估

R S4上下文中表达式的非标准评估,r,expression,s4,delayed-execution,R,Expression,S4,Delayed Execution,这是从他们函数中使用的函数中借用的 实际问题 调用S4方法(与标准R函数相反)时,如何延迟表达式的计算(例如通过argexpr指定)以“捕获”其内容 例子 请注意,x_1还不存在,这就是为什么我们要延迟对expr的评估,而只是“捕获”其内容 函数captureExpression: captureExpression <- function( expr, caller_offset = 1, brackets = TRUE ) { out <- eval(substi

这是从他们函数中使用的函数中借用的

实际问题 调用S4方法(与标准R函数相反)时,如何延迟表达式的计算(例如通过arg
expr
指定)以“捕获”其内容

例子 请注意,
x_1
还不存在,这就是为什么我们要延迟对
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
# }
调用S4方法时,通过未计算的
expr
传递不起作用:

setGeneric(
  name = "bar",
  signature = c(
    "expr"
  ),
  def = function(
    expr,
    ...
  ) {
    standardGeneric("bar")       
  }
)
setMethod(
  f = "bar", 
  signature = signature(
    expr = "ANY"
  ), 
  definition = function(
    expr,
    ...
  ) {
  captureExpression(expr = expr, ...)    
})
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
应用S4方法:

setGeneric(
  name = "bar",
  signature = c(
    "expr"
  ),
  def = function(
    expr,
    ...
  ) {
    standardGeneric("bar")       
  }
)
setMethod(
  f = "bar", 
  signature = signature(
    expr = "ANY"
  ), 
  definition = function(
    expr,
    ...
  ) {
  captureExpression(expr = expr, ...)    
})
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
我想这与方法分派的实际执行方式有关。然而,也许有一种方法可以做到这一点