Posts tagged ‘non-generic method’

December 16, 2012

Override a non-generic method in S3 OOP system

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


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, ...){
sample.Foo <- function(obj, ...){