Other sites

A Simple Guide to S3 Methods

A few months ago I wrote about my first solo author submission to the R Journal entitled, “A Simple Guide to S3 Methods”. Unfortunately the article didn’t make it to publication on the R Journal, but admittedly that might have been a bit of a long shot.

So, I thought that it might be good if I instead share the article here on my blog and r bloggers, so that people can comment below and share their thoughts.

It is not a complete guide to S3 methods, but more a primer the on whathow, and why S3.

Here we go.

Writing functions in R is an important skill for anyone using R. S3 methods allow for functions to be generalised across different classes and are easy to implement. Whilst many R users are be adept at creating their own functions, it seems that there is room for many more to take advantage of R’s S3 methods. This paper provides a simple and targeted guide to explain what S3 methods are, why people should them, and how they can do it.

A standard principle of programming is DRY – Don’t Repeat Yourself. Under this axiom, the copying and pasting of the same or similar code (copypasta), is avoided and instead replaced with a function, macro, or similar. Having one function to replace several of the same or similar coded sections simplifies code maintenance as it means that only one section of code needs to be maintained, instead of several. This means that if the code breaks, then one simply needs to update the function, rather than finding all of the coded sections that are now broken.

S3 methods in the R programming language are a way of writing functions in R that do different things for objects of different classes. S3 methods are so named as the methods shipped with the release of the third version of the “S” programming language, which R was heavily based upon [@chambers1992, @rclassmethods, @R]. Hence, methods for S 3.0 = S3 Methods.

The function summary() is an S3 method. When applied to an object of class data.frame, summary shows descriptive statistics (Mean, SD, etc.) for each variable. For example, iris is of class data.frame:

class(iris)

## [1] "data.frame"

So applying summary to iris gives us summary information relevant to a dataframe

summary produces a description of the linear model, describing how it was called (call), as well as the residuals, coefficients, t-values, p-values, $R^2$, and more. This output is completely different to the information output from summary used for the iris dataframe.

So how does the same function, summary perform differently for different objects? The answer is that R is helpful, and hides this information. There are in fact, many different summary functions. For example:

summary.lm

summary.data.frame

summary.Date

summary.matrix

Being an S3 method, summary calls the appropriate function based upon the class of the object it operates on. So using summary on an object of class “Date” will evoke the function, summary.Date. But all you need to do is type summary, and the S3 method does the rest. By abstracting away this detail (the object class), the intent becomes clearer.

To further illustrate, using summary on the iris data will actually call the function summary.data.frame, since iris is of class data.frame. We can find the class of an object using class

To summarize, the important feature of S3 methods worth noting is that only the first part, summary, is required to be used on these objects of different classes.

Why hide the text?

Hiding the trailing text after the . avoids the need to use a different summary function for every class. This means that one does not need to remember to use summary.lm for linear models, or summary.data.frame for data frames, or summary.aProposterousClassOfObject. By using S3 methods, cognitive load is reduced – you don’t have to think as much to remember what class an object is – and the commands are more intuitive. To get a summary of most objects, use summary, to plot most objects, use plot. Perhaps the most nifty feature of all is that a user can create their own S3 methods using the same functions such as summary and plot. This means a user can create their own special class of object

test_class1:10class(test_class)"myclass"class(test_class)

## [1] "myclass"

and then write their own S3 method for it – e.g., summary.myclass or plot.myclass, each proiding appropriate summary information, or nice plots, for that object.

How to make your own S3 method?

Creating your own S3 method is not particularly difficult and is usually highly practical. A use case scenario for creating an S3 method is now discussed.

The Residual Sums of Squares (RSS), $\sum(Y_i – \hat{Y})^2$ is a useful metric for determining model accuracy for continuous outcomes. For example, for a Classification and Regression Tree

In this case, one could write three functions, one for each decision tree method: “rss_rpart”, “rss_brt”, and “rss_rf”. But to avoid having three functions and instead use just one, one could place all three functions inside of one function, using an if-then-else clause to direct the object of the appropriate class to the appropriate method. This shall be referred to as a “Poor man’s S3 method”.

dt_rssfunction(x){if("rpart"%in%class(x)){resultsum((residuals(x)**2))return(result)}elseif("gbm"%in%class(x)){resultsum(x$residuals**n2)return(result)}elseif("randomForest"%in%class(x)){tempx$y-x$predictedresultsum(temp**2)return(result)}elsewarning(paste(class(x),"is not of an rpart, gbm, or randomForest object"))}

Here it is in action

dt_rss(fit.rpart)

## [1] 10.17245

The RSS method works, and if it is applied to a class that is not known, a special message is provided

fit.lmlm(Sepal.Width~Species,data=iris)dt_rss(fit.lm)

## Warning in dt_rss(fit.lm): lm is not of an rpart, gbm, or randomForest
## object

The “poor man’s S3 method” does what it needs to do.
However, one must ask how sustainable this would be for an entire programming language? Imagine if a colleague creates a new tree method that needs it’s own rss(). He will need to convince the maintainer to add his class into your ifelse() chain. Failing this, he could just overwrite the function rss(), with predictably disastrous results. In reality, it’s probably better to do all of these things with one method. R’s S3 methods mean that R developers can utilise a common interface without having to update it when new classes come along. It also means overloading clashes are less likely.

So let us create an S3 method to demonstrate.

First define the S3 method with UseMethod()

rssfunction(x)UseMethod("rss")

This creates the building block of an S3 method, the “root”, if you will.

Here we have specified that our method will be called rss. Now we need to create the special cases of rss – the methods rss.rpart, rss.gbm, and rss.randomForest, where the sections of code after rss. are the classes of object we want them to work on.

A default method can also be created – rss.default – which, as the name suggests, is the default method when the argument x is not a class that has a specific version of the method defined.

rss.defaultfunction(x,...){warning(paste("RSS does not know how to handle object of class ",class(x),"and can only be used on classes rpart, gbm, and randomForest"))}

In this case a warning is issued, to let the user know that the object class they were using was not appropriate.

We can now apply the rss method to an rpart model

rss(fit.rpart)

## [1] 10.17245

Also observe what happens when the object used is not of the decision tree classes:

rss(lm.fit)

## Warning in rss.default(lm.fit): RSS does not know how to handle object of
## class function and can only be used on classes rpart, gbm, and randomForest

This guide to S3 methods was written to provide R users with the minimal amount of information to start building their own S3 methods. For a more complete treatment on S3 methods, see Advanced-R, R Packages, and the official S3 documentation.