In R OOP, you can override a generic method for your custom class. For example, you can define print() and plot() methods for an class Foo. It is also easy to overrisk a non-generic method if you use S4 OOP system, through the S4 function setGeneric(). But S3 does not have a function equivalent to setGeneric().
Suppose you want to write a method sample() for class Foo. As the built-in sample() function is not generic, simply defining sample.Foo() will break the original sample(). For example, calling
sample(10,2)
will result in the following error message:
Error in UseMethod(“sample”) :
no applicable method for ‘sample’ applied to an object of class “c(‘double’, ‘numeric’)”
Here is the correct way to override a non-generic method in S3. First, you copy the non-generic method to the default method for the generic method you want to create. Then, you create the generic method and the method for class Foo.
sample.default = sample
sample <- function(obj, ...){
UseMethod('sample')
}
sample.Foo <- function(obj, ...){
DoSomething()
}