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, ...){

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: