Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Advanced R

Object-Oriented Programming in R: S3, S4, Reference Classes and R6

Understand R's object systems: S3 classes and generics (UseMethod, NextMethod), S4 classes with validity, reference classes, R6 with private fields, and when to choose each.

R has not one but several object-oriented systems, which confuses newcomers. The reason is history: S3 came first and is simple and informal, S4 added formal classes, and Reference Classes and the R6 package added mutable objects like those in Java or Python. Whichever you use, you are still doing the same two things: bundling data into objects, and choosing the right code for an object's class at run time.

You have already used S3 without knowing it: print(), summary() and plot() do different things for a number, a data frame and a fitted lm model because they are S3 generic functions that dispatch on the class of their first argument.

R is not available on this site, so the code is read-only; the printed lines are the standard results of these small examples. The Python block at the end shows equivalent dispatch and inheritance that you can run.

S3: simple and flexible

An S3 object is any ordinary R object with a class attribute. There is no formal class definition at all.

R
dog <- structure(list(name = "Rex", sound = "Woof"), class = c("dog", "animal"))
class(dog)                  # "dog" "animal"
inherits(dog, "animal")     # TRUE

The class is a vector: from most specific to most general. That vector is the inheritance chain.

Generics and methods

A generic is a function that calls UseMethod(). A method is a function named generic.class.

R
speak <- function(x, ...) UseMethod("speak")

speak.animal  <- function(x, ...) cat(x$name, "makes a sound\n")
speak.default <- function(x, ...) cat("Nothing to say\n")
speak.dog     <- function(x, ...) {
  cat(x$name, "says", x$sound, "\n")
  NextMethod()               # continue with the next class in the chain
}

speak(dog)
# Rex says Woof 
# Rex makes a sound
speak(42)                    # Nothing to say   (falls back to the default method)

R looks at the object's classes in order, runs the first method it finds, and NextMethod() moves on to the next class. speak(42) has no speak.numeric, so the default method runs.

flowchart LR
  A["speak(dog)"] --> B["speak.dog"]
  B -->|"NextMethod()"| C["speak.animal"]
  C -->|"no more classes"| D["speak.default"]

Dispatch follows the class vector, then falls back to the default.

Customizing printing and operators

Define print.<class> (or format.<class>) and R uses it whenever the object is shown:

R
money <- function(x) structure(x, class = "money")
print.money <- function(x, ...) cat(sprintf("$%.2f\n", unclass(x)))

m <- money(5)
m                      # $5.00     (auto-printing calls print.money)

You can overload operators through the group generic Ops:

R
Ops.money <- function(e1, e2) {
  v <- get(.Generic)(unclass(e1), unclass(e2))
  if (.Generic %in% c("+", "-", "*", "/")) money(v) else v
}
money(5) + money(2.5)  # $7.50
money(5) > money(2)    # TRUE

.Generic holds the operator being called ("+", ">", ...), so one function handles all of them. Remove the class with unclass() to see the raw data, and list the methods of a generic with methods("speak").

The constructor pattern

Because S3 does no checking, good code adds it by convention: a low-level constructor, a validator and a friendly helper.

R
new_temperature <- function(x = double(), unit = "C") {
  stopifnot(is.double(x))
  structure(x, unit = unit, class = "temperature")
}
validate_temperature <- function(t) {
  if (any(t < -273.15 & attr(t, "unit") == "C")) stop("below absolute zero", call. = FALSE)
  t
}
temperature <- function(x, unit = "C") validate_temperature(new_temperature(as.double(x), unit))

S4: formal classes

S4 declares classes with named, typed slots, and generics with explicit signatures. It catches mistakes early and is used by large frameworks such as Bioconductor.

R
setClass("Person",
  representation(name = "character", age = "numeric"),
  validity = function(object) {
    if (object@age < 0) "age must be non-negative" else TRUE
  })

p <- new("Person", name = "Ann", age = 30)
p@name                         # "Ann"     (@ reads a slot)
isVirtualClass("Person")       # FALSE

new("Person", name = "Bob", age = -1)
# Error: invalid class "Person" object: age must be non-negative

Methods are attached to generics with setGeneric() and setMethod():

R
setGeneric("greet", function(obj, ...) standardGeneric("greet"))
# [1] "greet"
setMethod("greet", "Person", function(obj, ...) cat("Hi,", obj@name, "\n"))
greet(p)                       # Hi, Ann

setClass("Student", contains = "Person", representation(school = "character"))
setMethod("greet", "Student", function(obj, ...) {
  callNextMethod()             # run the Person method first
  cat("I study at", obj@school, "\n")
})
greet(new("Student", name = "Cy", age = 20, school = "MIT"))
# Hi, Cy
# I study at MIT

setMethod("show", "Person", ...) customizes how an object prints. S4 supports multiple dispatch: a method can depend on the classes of several arguments (setMethod("combine", signature("A", "B"), ...)), something S3 cannot do.

Reference classes and R6: mutable objects

S3 and S4 objects are copy-on-modify: changing a copy leaves the original alone, like ordinary R values. Some problems (a bank account, a connection, a game state) are easier with objects that change in place and are shared by reference. R6 is the popular package for that:

R
library(R6)

Counter <- R6Class("Counter",
  public = list(
    n = 0,
    add = function(k = 1) {
      self$n <- self$n + k
      invisible(self)          # returning self allows chaining
    }
  )
)

c1 <- Counter$new()
c1$add()$add(5)                # chained calls
c1$n                           # 6
c2 <- c1                       # NOT a copy: both names point to one object
c2$add(); c1$n                 # 7
c3 <- c1$clone()               # a real copy

R6 classes support private members, active bindings (fields computed on access), inheritance with inherit = Parent, and super$method() to call the parent. A bank account that hides its balance:

R
Account <- R6Class("Account",
  private = list(balance = 0),
  public = list(
    deposit  = function(x) { private$balance <- private$balance + x; invisible(self) },
    get_balance = function() private$balance
  )
)
a <- Account$new(); a$deposit(100)$deposit(50)
a$get_balance()                # 150

Base R's own version, setRefClass(), works similarly with fields and methods lists, but R6 is faster, simpler and used far more often.

Which one should I use?

System Style Use it when
S3 informal, methods belong to generics most everyday code: printing, summaries, packages
S4 formal slots, validity, multiple dispatch large systems, Bioconductor, strict contracts
R6 mutable objects, methods belong to the object stateful things: connections, simulations, caches
Reference classes like R6, built into base R when you cannot add a dependency

A good default: write S3, add a constructor and validator, and reach for R6 only when you truly need mutable state.

The same ideas in Python

Python's singledispatch and class inheritance map directly onto S3 generics and NextMethod(). Run this comparison.

Python Python comparison: generics, inheritance and mutable objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Calling a method directly (print.money(x)) instead of the generic. Always call the generic.
  • Forgetting NextMethod() when a child method should extend the parent behavior.
  • Writing setClass() slots as numeric and then storing a string; S4 raises an error, S3 would not.
  • Expecting c2 <- c1 to copy an R6 object. Use c1$clone().
  • Putting a method name's dot into a class name: speak.my.dog is ambiguous between class my.dog and dog method. Avoid dots in class names.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an S3 generic function contain?

    A generic is a small function that calls UseMethod("name"), which then dispatches to name.class methods.
  2. 2. In a method speak.dog, what does NextMethod() do?

    NextMethod() continues the dispatch with the next class in the chain, allowing child methods to extend their parents.
  3. 3. How do you read the slot called name of an S4 object p?

    S4 slots are accessed with @. R6 and lists use $.
  4. 4. What happens after c2 <- c1 when c1 is an R6 object?

    R6 objects have reference semantics. Use c1$clone() to make a copy.
  5. 5. Which system supports multiple dispatch?

    S4 generics can dispatch on the classes of several arguments.

Summary

  • S3: any object with a class attribute; generics call UseMethod(), methods are generic.class, NextMethod() chains to parents.
  • Add a constructor and validator to S3 classes by convention.
  • S4: setClass(), new(), slots with @, validity, setGeneric()/setMethod(), callNextMethod(), multiple dispatch.
  • R6 (and Reference Classes) provide mutable objects with reference semantics, private members and clone().
  • Default to S3; use R6 for stateful objects and S4 for formal, large systems.

Next: Error Handling and Debugging in R