TExcelTAD
Home › R › R S3 Classes

R S3 Classes

R has several object-oriented systems. The oldest and most widely used is S3. It is very lightweight: an S3 object is an ordinary list (or vector) with a class attribute, and methods are ordinary functions named generic.class.

You've been using S3 all along: print(), summary() and plot() behave differently for data frames, factors and models because they are S3 generic functions.

r · try it yourself
class(mtcars)
class(factor("a"))
fit <- lm(mpg ~ wt, data = mtcars)
class(fit)
head(methods(summary), 5)
[1] "data.frame"
[1] "factor"
[1] "lm"
[1] "summary.Date"    "summary.POSIXct" "summary.POSIXlt" "summary.aov"
[5] "summary.aovlist"

Creating an S3 object

Build the data (usually a list) and set its class with structure() or class<-. A constructor function keeps this in one place:

r · try it yourself
new_account <- function(owner, balance = 0) {
  stopifnot(is.character(owner), is.numeric(balance))
  obj <- list(owner = owner, balance = balance)
  class(obj) <- "account"
  obj
}
acc <- new_account("Maya", 120)
class(acc)
acc$balance
inherits(acc, "account")
[1] "account"
[1] 120
[1] TRUE

Writing methods

To control how an object prints, write a function called print.account. When you call print(acc) (or just auto-print it), R looks at the class and dispatches to that method:

r · try it yourself
new_account <- function(owner, balance = 0) {
  structure(list(owner = owner, balance = balance), class = "account")
}
print.account <- function(x, ...) {
  cat("<account>", x$owner, "has", sprintf("$%.2f", x$balance), "\n")
  invisible(x)
}
summary.account <- function(object, ...) {
  status <- if (object$balance > 0) "in credit" else "empty"
  cat("Account of", object$owner, "is", status, "\n")
}
acc <- new_account("Maya", 120)
acc
summary(acc)
summary(new_account("Leo"))
<account> Maya has $120.00
Account of Maya is in credit
Account of Leo is empty

By convention, print methods return the object invisibly so that x <- print(x) works.

Your own generic functions

A generic is a function that just calls UseMethod(). Add a .default method as the fallback for other classes:

r · try it yourself
deposit <- function(acc, amount) UseMethod("deposit")
deposit.account <- function(acc, amount) {
  acc$balance <- acc$balance + amount
  acc
}
deposit.default <- function(acc, amount) {
  stop("deposit() needs an account, not a ", class(acc)[1])
}
acc <- structure(list(owner = "Maya", balance = 120), class = "account")
acc <- deposit(acc, 30)
acc$balance
deposit(42, 10)
[1] 150
Error in deposit.default(42, 10) : deposit() needs an account, not a numeric

Note that R objects are copied when modified, so deposit() returns the updated account and we assign it back.

Inheritance

The class attribute can be a vector. R tries the methods for each class in order, and NextMethod() passes control to the next one:

r · try it yourself
print.account <- function(x, ...) {
  cat("Owner:", x$owner, " Balance:", x$balance, "\n")
  invisible(x)
}
print.savings <- function(x, ...) {
  cat("Savings account at", x$rate * 100, "% interest\n")
  NextMethod()
}
s <- structure(list(owner = "Ravi", balance = 500, rate = 0.03),
               class = c("savings", "account"))
s
inherits(s, "account")
Savings account at 3 % interest
Owner: Ravi  Balance: 500
[1] TRUE

Operator and format methods

Operators are generics too. Defining +.money or format.money makes your class feel built in:

r · try it yourself
money <- function(x) structure(x, class = "money")
format.money <- function(x, ...) sprintf("$%.2f", unclass(x))
print.money <- function(x, ...) print(format(x), quote = FALSE)
"+.money" <- function(e1, e2) money(unclass(e1) + unclass(e2))
price <- money(c(4.5, 12))
price
price + money(0.99)
[1] $4.50  $12.00
[1] $5.49  $12.99

unclass() strips the class so the underlying numbers can be used directly, avoiding infinite recursion inside the method.

Note: R also has the more formal S4 system (setClass(), setGeneric(), setMethod() in the methods package) and R5 reference classes (setRefClass()) with mutable objects. S3 remains the most common in everyday R code.

Test yourself

What makes an R list an S3 object of class "car"?

  1. Calling new("car")
  2. Setting its class attribute to "car"
  3. Defining class car {}
  4. Using setClass()

Which function should print(x) call for an object of class "car"?

  1. car.print
  2. print_car
  3. print.car
  4. car$print

What does the body of a generic function usually contain?

  1. UseMethod("name")
  2. NextMethod()
  3. return(class(x))
  4. setGeneric()