我正在为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方法调度时调用新函数?
答案 0 :(得分:4)
您是否尝试过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!"