Old-School OOP in R: S3

This section is about S3 classes and methods. Although S4 classes and methods are much more capable than S3 classes and methods, many important R functions were written before S4 objects were implemented (such as the statistical modeling software). In order to understand, modify, or extend this software, you have to know how S3 classes are implemented.

S3 Classes

As we saw above, S4 classes implement most features of modern object-oriented programming languages: formal class definitions, simple and multiple inheritance, parameteric polymorphism, and encapsulation. Unfortunately, S3 classes don’t implement most of these features.

S3 classes are implemented through an object attribute. An S3 object is simply a primitive R object with additional attributes, including a class name. There is no formal definition for an S3 object; you can manually change the attributes, including the class. Above, we used time series as an example of an S4 class. There is an existing S3 class for representing time series, called “ts” objects. Let’s create a sample time series object and look at how it is implemented. Specifically, we’ll look at the attributes of the object and then use typeof and unclass to examine the underlying object:

> my.ts <- ts(data=c(1,2,3,4,5),start=c(2009,2),frequency=12) > my.ts Feb Mar Apr May Jun 2009 1 2 3 4 5 > attributes(my.ts) $tsp [1] 2009.083 2009.417 12.000 $class [1] "ts" > typeof(my.ts) [1] "double" > unclass(my.ts) [1] 1 2 3 4 5 attr(,"tsp") ...

Get R in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.