Using sd as a generic function in R

If I have a class called foo , then just overload the summary function

 summary.foo = function(x, ...) print("bar") 

However, this method does not work with the sd function, i.e.

 > bar = createFooClass() > sd.foo = function(x, ...) print("Hi") > sd(bar) error: is.atomic(x) is not TRUE 

What is the correct way to overload this function?

+8
oop r r-s3
source share
3 answers

You can capture some non-generic function, make it (S3) common and set the original version as 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") 

The final step, if it is in a package, is to add an argument ... to sd.default to enable packet inspection:

 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 behavior:

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

This is described in Section 7.1 of the Language Extension Writing Guide.

+7
source share

You need to define a new generic for sd .

The easiest way is to use S4, because it automatically processes the sd method:

 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 
+3
source share

Look at the sd() code --- it effectively sends internally. In other words, this is not a general function, but a simple old regular function.

The easiest way is to simply change sd() to a branch of the foo class.

+1
source share

Source: https://habr.com/ru/post/651226/


All Articles