Search

Simple yet elegant Object-Oriented programming in R with S3

The R language is peculiar in many ways, and its approach to object-oriented (OO) programming is just one of them. Indeed, base R supports not one, but three different OO systems: S3, S4 and RC classes. And yet, probably none of them would qualify as a fully-fledged OO system before the astonished gaze of an expert in languages such as Python, C++ or Java. In this tutorial, we will review the S3 system, the simplest yet most elegant of them. The use case of the quantities framework (CRAN packages units, errors and quantities) will serve as the basis to study the main concepts behind S3 programming in R: classes, generics, methods and inheritance.

Introduction

You probably heard of John Chambers’ slogans about R, i.e., everything that exists is an object and everything that happens is a function call (and a function is an object too). In most languages, object is an OO concept referring to an instance of a certain class that encapsulates its whole lifetime: construction, associated data, behavior and destruction. In R, instead, roughly speaking, an object is just a base type with possibly some attributes. In other words, everything is about the data in R, while construction, behavior and destruction are defined elsewhere.

Let us start with the common example: what are factors in R? What makes them so special?

As you can see, factors are just integer vectors with some metadata stored as an attribute named levels. Note also that there is a special attribute called class which is central in defining how these objects behave. Where and how to do it is what S3 programming is about. This decoupling makes S3 less formal and more error-prone, but on the other hand, it is much more flexible, because it allows you e.g. to extend classes in other packages without requiring them to modify a single bit.

Arguably, there are two main use cases for an S3-style design:

Certain procedure generates a list of heterogeneous things that needs to be subsequently manipulated as a whole. For example, the output from a linear regression:

Certain base type requires to be enriched with some metadata that needs to be manipulated alongside it to provide some additional functionality (e.g., factors).

In this practical introduction to S3 programming, we will cover the second use case by reviewing the basic design of the quantities framework, which enables quantity calculus for R vectors, matrices and arrays, with automatic propagation, conversion, derivation and simplification of magnitudes and uncertainties.

Defining a new object

As a motivating example, we would like R to be able to automatically handle measurements with uncertainty (hereinafter, for convenience, just errors). Base numeric vectors are just fine to handle measurements; we just need to add the errors as metadata (in an attribute) and choose a proper class. In order to do this, no special care is needed beyond 1) avoiding special attribute names for our metadata, with special meaning (such as class, names, dim and dimnames), and 2) avoiding class names that are already in use out there.

In our case, we will store the errors in an attribute called errors, and the class name will be errors (not fanciful, just convenient). The first piece we need is a constructor:

Modifying the behavior: generics, methods and groups

One of the first things we would probably want to do with our new object is to print it properly, because our users are not interested in the implementation details that we are able to see above (i.e., the actual attributes). Therefore, we need to provide a print method.

There are great sources to teach you all the technical details about S3 (there are some links at the end of this article). We will limit ourselves here to briefly introduce the basic building blocks of S3 programming: generics and methods. Many (most?) of the functions you daily use are generics (or internal generics, which are internally implemented functions that mostly behave like generics; see help(InternalMethods)).

This basically means that you can write methods for those generics to implement how they behave when they are applied to a particular object class. And this is as easy as writing a function named <generic>.<class>. The signature of this function must accommodate, at least, the same arguments as the generic. In other words, a method can be more specific than the generic, but cannot lose generality. Some examples:

For generic foo(x), method must be foo.bar(x).

For generic foo(x, y, z), method can be foo.bar(x, y, z), or, if you are just interested in the first argument, for example, you may use dots foo.bar(x, ...) to summarize the rest of them.

For generic foo(x, ...), method can be foo.bar(x, ...), or you may be more specific and take some arguments out of the dots foo.bar(x, y, z, ...) (see help(print) for examples).

In the following example, print.errors is defined. This particular implementation just shows a maximum of 5 error terms and then delegates the printing of the main vector of values to the default method by calling NextMethod.

Dropping the class and the attribute is not needed in general, but in this case we do not want the default printing method (print.default) to show them, so we remove them before calling NextMethod. The latter is not required either, but it is highly advisable if we want to support inheritance, as we will see later.

Now, if we try to print our object again,

x

## Errors: 0.1 0.2 0.3 0.4 0.5 ...
## [1] 1 2 3 4 5 6 7 8 9 10

The output looks nicer. Basically, when print is called, it takes the class, errors, and looks for a method called print.errors. Before we defined it, nothing was found and thus the default method was called. If you call methods(print) you will see that there are hundreds of print methods defined for hundreds of different classes, and our new method is of course listed there.

The next step would be to implement common functions to work with vectors in R, such as [ and c.

Now, we can subset and concatenate errors objects, and their errors are also handled appropriately.

c(x[3], x[7:9])

## Errors: 0.3 0.7 0.8 0.9
## [1] 3 7 8 9

Next, we would like to be able to operate normally with these vectors so that errors are automatically recomputed and propagated. At this point, you are probably guessing that we basically need to start reimplementing a bunch of mathematical functions and arithmetic operations to work with our new class. And you are actually right, but there is a shortcut for that.

Fortunately, R defines what is called S3 group generics (see help(groupGeneric)). These are four pre-specified groups of functions containing the following generics:

Group Math includes mathematical functions:

abs, sign, sqrt

Rounding functions (floor, ceiling…)

Exponential, logarithms and trigonometric functions (cos, sin…)

Special functions such as gamma

Cumulative sum, product, max and min

Group Ops includes arithmetic operations:

Addition, subtraction, multiplication, power, division and modulo

Logic and boolean operators

Group Summary includes:

all, any, sum, prod, min, max, range

Group Complex includes functions to work with complex numbers:

Argument, conjugate, real/imaginary parts, modulus

The existence of these groups means that we can simply write a single method for a whole category to provide for all the functions included. And this is what the errors package does by implementing Math.errors, Ops.errors and Summary.errors. We can take a glimpse into one of these methods:

All the arithmetic operators, as well as logical and boolean operators, share a lot of properties. But still, it is clear that we need some mechanism to be able to do different things depending on which one was called. To solve this, the S3 dispatching mechanism sets for us special variables:

.Generic contains the name of the generic function.

.Method contains the name of the method.

.Class contains the class(es) of the object.

This way, checking .Generic allows us to issue a warning if a non-supported method is called, and then delegate to NextMethod.

Note also that the Ops group is pretty special for two reasons: first, there are unary operators (e.g., -1), so sometimes the second argument is missing, and we need to take that into account; secondly, these operators are commutative, and therefore S3 supports double dispatch in this case.

Finally, Ops.errors addresses all the arithmetic operators in a unified way: it computes two derivatives depending on .Generic and then propagates the uncertainty using an auxiliary function that implements the Taylor Series Method.

What we have seen here is just a taste of the actual implementation of the errors package. Now, let’s clear the workspace and load it to check the complete functionality.

Implementing new functionality: new generics

So far, we have explored S3 programming mostly by extending existing generics with methods for a new class of our own. But what if we want to add new functionality? You have probably already guessed that you need to implement your own generics. Let’s take a step back and use a simpler classic example to demonstrate this.

As you can see, implementing a new generic is as easy as defining a function that calls UseMethod with the name of the generic. More advanced uses may, for example, manipulate the input variables before calling UseMethod, but this basic template would fit most use cases.

Combining functionality: inheritance

Inheritance is also possible with S3 programming. Instead of assigning a single class, there may be multiple classes defined as a character vector. When this happens, R dispatches the first class, and subsequent calls to NextMethod look for other methods in the class vector. This means that, if we want our object to resemble parent-child relationships, parent classes must go first in the class vector.

This is exactly what the package quantities does to combine the functionality of packages errors and units. As we have seen, errors defines uncertainty metadata for R vectors, and units does the same for measurement units. To achieve a complete calculus system, quantities prepends a superclass to be able to orchestrate units and errors while keeping them completely independent.

Summary

Define a constructor (possibly a validator too) that sets the class and the attributes.

Define new generics with UseMethod.

Implement methods for new and existing generics with a proper use of NextMethod to support inheritance and also avoid code duplication.

In contrast to other OO systems, objects hold the data, and methods live outside as independent functions. The developer needs to invest more effort and care to ensure correctness and support inheritance, but in exchange, it is a very flexible system, because it is easy to extend without modifying the object.