如果我有一门课叫 foo
,那么很容易重载 summary
功能
summary.foo = function(x, ...) print("bar")
但是,此技术不适用于
sd
函数,即> bar = createFooClass()
> sd.foo = function(x, ...) print("Hi")
> sd(bar)
error: is.atomic(x) is not TRUE
重载这个函数的正确方法是什么?
最佳答案
您可以劫持任何非通用函数,使其(S3)通用并将原始版本设置为默认版本。例如:
## make an S3 generic for sd
sd <- function(x, ...) UseMethod("sd")
## take the usual definition of sd,
## and set it to be the default method
sd.default <- stats::sd
## create a method for our class "foo"
sd.foo = function(x, ...) print("Hi")
最后一步,如果这是在一个包中,是添加一个
...
论据 sd.default
允许通过包裹检查:formals(sd.default) <- c(formals(sd.default), alist(... = ))
给予:
> args(sd.default)
function (x, na.rm = FALSE, ...)
NULL
> args(stats::sd)
function (x, na.rm = FALSE)
NULL
这然后给出了所需的行为:
> bar <- 1:10
> sd(bar)
[1] 3.027650
> class(bar) <- "foo"
> sd(bar)
[1] "Hi"
这记录在 section 7.1 中编写 R 扩展手册
关于oop - 在 R 中使用 sd 作为通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4728342/