The Art of R Programming

(WallPaper) #1
This chapter covers OOP in R. We’ll discuss programming in the two
types of classes, S3 and S4, and then present a few useful OOP-related R
utilities.

9.1 S3 Classes.................................................................


The original R structure for classes, known as S3, is still the dominant class
paradigm in R use today. Indeed, most of R’s own built-in classes are of the
S3 type.
An S3 class consists of a list, with a class name attribute anddispatch
capability added. The latter enables the use of generic functions, as we saw
in Chapter 1. S4 classes were developed later, with goal of addingsafety,
meaning that you cannot accidentally access a class component that is not
already in existence.

9.1.1 S3 Generic Functions...........................................


As mentioned, R is polymorphic, in the sense that the same function can
lead to different operations for different classes. You can applyplot(), for
example, to many different types of objects, getting a different type of plot
for each. The same is true forprint(),summary(), and many other functions.
In this manner, we get a uniform interface to different classes. For exam-
ple, if you are writing code that includes plot operations, polymorphism may
allow you to write your program without worrying about the various types of
objects that might be plotted.
In addition, polymorphism certainly makes things easier to remem-
ber for the user and makes it fun and convenient to explore new library
functions and associated classes. If a function is new to you, just try running
plot()on the function’s output; it will likely work. From a programmer’s
viewpoint, polymorphism allows writing fairly general code, without worry-
ing about what type of object is being manipulated, because the underlying
class mechanisms take care of that.
The functions that work with polymorphism, such asplot()andprint(),
are known asgeneric functions. When a generic function is called, R will then
dispatch the call to the proper class method, meaning that it will reroute the
call to a function defined for the object’s class.

9.1.2 Example: OOP in the lm() Linear Model Function..................


As an example, let’s look at a simple regression analysis run via R’slm()func-
tion. First, let’s see whatlm()does:

> ?lm

The output of this help query will tell you, among other things, that this
function returns an object of class"lm".

208 Chapter 9

Free download pdf