O'Reilly logo

R in a Nutshell, 2nd Edition by Joseph Adler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Object-Oriented Programming in R: S4 Classes

Now that we’ve seen a quick introduction to object-oriented programming in R, let’s talk about the functions for building classes in more depth.

Defining Classes

To create a new class in R, you use the setClass function:

setClass(Class, representation, prototype, contains=character(),
         validity, access, where, version, sealed, package,
         S3methods = FALSE)

Here is a description of the arguments to setClass.

ArgumentDescriptionDefault
ClassA character value specifying the name for the new class. (This is the only required argument.) 
representationA named list of the different slots in the class and the object name associated with each one. (You can specify “ANY” if you want to allow arbitrary objects to be stored in the slot.) 
prototypeAn object containing the default object for slots in the class. 
containsA character vector containing the names of the classes that this class extends (usually called superclasses).character()
validityA function that checks the validity of an object of this class. (Default is no validity check.) May be changed later with setValidity. 
accessNot used; included for compatibility with S-PLUS. 
whereThe environment in which to store the object definition.Default is the environment in which setClass was called.
versionNot used; included for compatibility with S-PLUS. 
sealedA logical value to indicate if this class can be redefined by calling setClass again with the same class name. 
packageA character value specifying the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required