Skip to Content
R in a Nutshell, 2nd Edition
book

R in a Nutshell, 2nd Edition

by Joseph Adler
October 2012
Beginner to intermediate
721 pages
21h 38m
English
O'Reilly Media, Inc.
Content preview from R in a Nutshell, 2nd Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

R in a Nutshell

R in a Nutshell

Joseph Adler
The R Book, 2nd Edition

The R Book, 2nd Edition

Michael J. Crawley
The R Book

The R Book

Michael J. Crawley
R Packages

R Packages

Hadley Wickham

Publisher Resources

ISBN: 9781449358204Errata Page