Non-standard expression evaluation in S4 context

This is borrowed from the shiny function exprToFunction

which is used in the function reactive

.

Actual question

How can I defer evaluating an expression (for example, specified via arg expr

) to "grab" its contents when the S4 method is called (as opposed to a standard R function)?

Example

Note that it x_1

does n't exist , so we want to defer the evaluation expr

and just "grab" its contents.

Function 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
# }

      

The unevaluated pass expr

works when the standard R function is called:

foo <- function(expr) {
  captureExpression(expr = expr)
}

foo(x_1 * 2)
# {
#     x_1 * 2
# }

      

Passing unevaluated expr

through doesn't work when calling the S4 method:

setGeneric(
  name = "bar",
  signature = c(
    "expr"
  ),
  def = function(
    expr,
    ...
  ) {
    standardGeneric("bar")       
  }
)
setMethod(
  f = "bar", 
  signature = signature(
    expr = "ANY"
  ), 
  definition = function(
    expr,
    ...
  ) {
  captureExpression(expr = expr, ...)    
})

      

Application of the S4 method:

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

      

I guess it has something to do with how method dispatch is actually done. However, there is perhaps a way that it can be done anyway.

+3


source to share





All Articles