Using sd as a generic function in R

你说的曾经没有我的故事 提交于 2019-11-29 13:34:17

You can hijack any non-generic function, make it (S3) generic and set the original version to be the default version. For example:

## 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")

A final step, if this is in a package, is to add a ... argument to sd.default to allow passing of package checks:

formals(sd.default) <- c(formals(sd.default), alist(... = ))

giving:

> args(sd.default)
function (x, na.rm = FALSE, ...) 
NULL
> args(stats::sd)
function (x, na.rm = FALSE) 
NULL

This then gives the desired behaviour:

> bar <- 1:10
> sd(bar)
[1] 3.027650
> class(bar) <- "foo"
> sd(bar)
[1] "Hi"

This is documented in section 7.1 of the Writing R Extensions manual

You need to define a new generic for sd.

The easiest way is to use S4, because it handles the default "sd" method automatically:

setClass("foo", list(a = "numeric", names = "character"))

setGeneric("sd")

setMethod("sd", "foo", 
          function(x,  na.rm = FALSE){
              print("This is a foo object!")
              callNextMethod(x@a)
              })

tf <- new("foo", a = 1:10)
sd(tf)
#[1] "This is a foo object!"
#[1] 3.027650

Look at the code of sd()---it effectively dispatches internally. In other words, it is not a generic function but a plain old regular function.

The easiest may just be to modify sd() to branch on class foo.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!