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
.
Argument | Description | Default |
---|---|---|
Class | A character value specifying the name for the new class. (This is the only required argument.) | |
representation | A 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.) | |
prototype | An object containing the default object for slots in the class. | |
contains | A character vector containing the names of the classes that this class extends (usually called superclasses). | character() |
validity | A function that checks the validity of an object of this
class. (Default is no validity check.) May be changed later with
setValidity . | |
access | Not used; included for compatibility with S-PLUS. | |
where | The environment in which to store the object definition. | Default is the environment in which setClass was
called. |
version | Not used; included for compatibility with S-PLUS. | |
sealed | A logical value to indicate if this class can be
redefined by calling setClass
again with the same class name. | |
package | A character value specifying the ... |
Get R in a Nutshell, 2nd Edition 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.