The Art of R Programming

(WallPaper) #1

example, where our class"employee"had three fields:name,salary, andunion.
Here are some possible mishaps:



  • We forget to enter the union status.

  • We misspellunionasonion.

  • We create an object of some class other than"employee"but accidentally
    set itsclassattribute to"employee".


In each of these cases, R will not complain. The goal of S4 is to elicit a
complaint and prevent such accidents.
S4 structures are considerably richer than S3 structures, but here we
present just the basics. Table 9-1 shows an overview of the differences
between the two classes.


Table 9-1:Basic R Operators


Operation S3 S4


Define class Implicit in constructor code setClass()
Create object Build list, setclassattr new()
Reference member variable $ @
Implement genericf() Definef.classname() setMethod()
Declare generic UseMethod() setGeneric()


9.2.1 Writing S4 Classes.............................................


You define an S4 class by callingsetClass(). Continuing our employee exam-
ple, we could write the following:



setClass("employee",



  • representation(

  • name="character",

  • salary="numeric",

  • union="logical")
    +)
    [1] "employee"



This defines a new class,"employee", with three member variables of the
specified types.
Now let’s create an instance of this class, for Joe, usingnew(), a built-in
constructor function for S4 classes:



joe <- new("employee",name="Joe",salary=55000,union=T)
joe
An object of class "employee"
Slot "name":
[1] "Joe"



Object-Oriented Programming 223
Free download pdf