我正在开发用于R的工具,但无法弄清楚如何在包中替换S3方法。让我们以print.aov为例。我想替换它的主体,但是在stats名称空间内。如果我只是在名称空间中重新分配功能

> reassignInEnv <- function(name, obj, env) {
    if (exists(name, env)) {
        if (bindingIsLocked(name, env)) {
            unlockBinding(name, env)
            assign(name, obj, envir = env)
            lockBinding(name, env)
        } else {
            assign(name, obj, envir = env)
        }
    } else {
        stop("Object does not exist")
    }
}
> reassignInEnv("print.aov", function(x, ...) { print("replaced function!") }, env = getNamespace('stats'))


分派print时将调用先前注册的函数,而不是新的函数。

> print(aov(yield ~ block + N * P + K, npk))
Call:
   aov(formula = yield ~ block + N * P + K, data = npk)

Terms:
                   block        N        P        K      N:P Residuals
Sum of Squares  343.2950 189.2817   8.4017  95.2017  21.2817  218.9033
Deg. of Freedom        5        1        1        1        1        14

Residual standard error: 3.954232
Estimated effects may be unbalanced


我也尝试了R.methodsS3包,但是它不起作用,因为它试图在锁定的环境中进行分配。

> unlockBinding("print.aov", getNamespace('stats'))
> setMethodS3(name = "print", definition = function(x, ...) { print("replaced function!") }, class = "aov", private = TRUE, export = FALSE, envir = getNamespace('stats'))
Error in eval(expr, envir, enclos) :
  cannot add bindings to a locked environment


如何在发生S3方法分派时确保调用新函数?

最佳答案

您尝试过assignInNamespace()吗?

printAOV <- function(x, ...) print("replaced function!")
assignInNamespace("print.aov", printAOV, ns = asNamespace("stats"))

print(aov(yield ~ block + N * P + K, npk))
# [1] "replaced function!"

07-24 09:46