Chapter 10. Object-Oriented Programming

The R system includes some support for object-oriented programming (OOP). OOP has become the preferred paradigm for organizing computer software; it’s used in almost every modern programming language (Java, C#, Ruby, and Objective C, among others) and in quite a few old ones (Smalltalk, C++). It’s easy to understand why: OOP methods lead to code that is faster to write, easier to maintain, and less likely to contain errors. Many R packages are written using OOP mechanisms.

If all you plan to do with R is to load some data, build some statistical models, and plot some charts, you can probably skim this chapter. On the other hand, if you want to write your own code for loading data, building statistical models, and plotting charts, you probably should read this chapter more carefully.

R includes two different mechanisms for object-oriented programming. As you may recall, the R language is derived from the S language. S’s object-oriented programming system evolved over time. Around 1990, S version 3 (thus S3) introduced class attributes that allowed single-argument methods. Many R functions (such as the statistical modeling software) were implemented using S3 methods, so S3 methods are still around today. In S version 4 (hence S4), formal classes and methods were introduced that allowed multiple arguments, more abstract types, and more sophisticated inheritance. Many new packages were implemented using S4 methods (and you can find S4 implementations ...

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.