在R中泛型函数中的UseMethod()之后执行代码?

时间:2019-05-22 09:17:35

标签: r r-s3 generic-function

我想拥有以下通用功能

  1. 检查是否有允许的格式(可行),
  2. than根据参数x的类型执行通用函数(有效)
  3. 在调用UseMethod()之后评估语句(不起作用-符合预期)

现在它在UseMethod的帮助中指出

  

调用UseMethod之后的任何语句都不会被评估,因为UseMethod不返回。

所以这并不奇怪。但是,除了定义调用validate_after()后跟validate()的附加功能cat(“Validation completed”)之外,我是否可以实现此目标?

validate <- function (
  x,
  allowedFormats
) {

  # Check arguments ---------------------------------------------------------

  allowedFormats <- c("none", "html", "pdf", "word", "all")
  if (!(report %in% allowedFormats)) {
    stop("'report' has to be one of the following values: ", allowedFormats)
  }

  UseMethod("validate", x)

  cat(“Validation completed”)
}

1 个答案:

答案 0 :(得分:0)

根据您希望实现的目标,使用“ on.exit”命令可能是可行的,如下所示:

test <- function(x, ...){
    if(!is.integer(x))
        stop("wups")
    on.exit(cat("'On exit' executes after UseMethod, but before the value is returned. x = ", x,"\n"))
    UseMethod("test")
}
test.integer <- function(x, ...){
    cat("hello i am in a function\n")
    x <- x + 3
    cat("I am done calculating. x + 3 = ",x,"\n")
    return(x)
}
test(1:3)

hello i am in a function
I am done calculating. x + 3 =  4 5 6 
'On exit' executes after UseMethod, but before the value is returned. x =  1 2 3 
[1] 4 5 6

这不一定是完美的解决方案。例如,如果希望对方法结果执行一些额外的计算,则结果不会传播到泛型函数(因为UseMethod不返回)。可能的解决方法是强制将环境馈入被调用的方法中,以将结果存储在其中。