ZetCode

R S3 classes

last modified November 19, 2026

R has several object systems. The oldest and simplest is S3, which is built into base R and used by functions such as print, plot, and summary. An S3 object is an ordinary vector, list, or environment with a class attribute, and an S3 method is a function whose name is the generic name followed by a dot and the class name. Calling the generic dispatches to the method that matches the class. This article covers class attributes, constructors, print methods, generic functions, inheritance with NextMethod, and group generics. The examples need no packages beyond base R.

The class attribute

Every object has a type, which is what it is made of, and may have a class, which is how it should behave. class reports the class when one is set and the implicit class otherwise. Assigning a class does not convert the object; it only adds an attribute. is.object reports whether a class attribute is present, and inherits asks whether a class appears in the class vector.

class-attribute.R
member <- list(name = "Alice", age = 34)
cat("class before:", class(member), "\n")
class(member) <- "member"
cat("class after:", class(member), "\n")
cat("type:", typeof(member), "\n")
cat("is object:", is.object(member), "\n")
cat("is member:", inherits(member, "member"), "\n")
str(unclass(member))

The list starts with the implicit class list and keeps the type list after the class is set, because the class is only an attribute. is.object reports TRUE once the attribute exists, and unclass removes it again so that str shows the two fields. The name of the class matters: utils already defines a person class for bibliographic records, together with a $ method, so naming our class person would send member$name to that method and fail. A class name should be unique among the packages that are loaded.

$ Rscript class-attribute.R
class before: list 
class after: member 
type: list 
is object: TRUE 
is member: TRUE 
List of 2
 $ name: chr "Alice"
 $ age : num 34

A constructor

Setting the class by hand in every place that creates an object is error-prone. A constructor is a function that builds the object, sets the class, and often checks the fields. By convention the constructor is named after the class and returns the finished object; structure sets attributes in the same call that creates the list.

constructor.R
new_member <- function(name, age) {
  structure(list(name = name, age = age), class = "member")
}
alice <- new_member("Alice", 34)
bob <- new_member("Bob", 41)
cat("class:", class(alice), "\n")
cat("names:", names(alice), "\n")
cat("ages:", alice$age, bob$age, "\n")
str(alice)

Both objects have the same class and the same two fields, so the rest of the code can rely on that shape. The constructor also gives one place to change the representation later, for example by adding a field or by switching from a list to an environment. str prints the class as an attribute on the list, which is exactly how R stores it. A constructor that takes a single list and validates it is the alternative used by many packages; the direct argument style here is shorter for small classes.

$ Rscript constructor.R
class: member 
names: name age 
ages: 34 41 
List of 2
 $ name: chr "Alice"
 $ age : num 34
 - attr(*, "class")= chr "member"

A print method

print is a generic function: it looks at the class of its argument and calls the method registered for that class. A method for a class named member is therefore called print.member. The method receives the object as its first argument and may receive further arguments through ..., which keeps it compatible with calls that pass printing options.

print-method.R
new_member <- function(name, age) {
  structure(list(name = name, age = age), class = "member")
}
print.member <- function(x, ...) {
  cat(x$name, "is", x$age, "years old\n")
  invisible(x)
}
alice <- new_member("Alice", 34)
print(alice)
cat("---\n")
print(unclass(alice))

print(alice) finds print.member because the object has class member, and the method prints one sentence instead of the internal list. At the interactive prompt the same method runs when the object is typed on a line of its own, because the console calls print on the result. Printing the unclassed list falls back to print.default and shows the fields. A print method should return its argument invisibly, so that the object is not printed a second time when the call returns.

$ Rscript print-method.R
Alice is 34 years old
---
$name
[1] "Alice"

$age
[1] 34

A generic of your own

A generic is a function whose body calls UseMethod with the name of the generic. UseMethod looks at the class of the first argument, finds a function named generic.class, and calls it with the same arguments. The generic itself usually contains nothing else, because any code before UseMethod runs again for every method call. A .default method handles classes that have no specific method.

generic.R
new_member <- function(name, age) {
  structure(list(name = name, age = age), class = "member")
}
describe <- function(x, ...) UseMethod("describe")
describe.member <- function(x, ...) {
  sprintf("%s, %d years old", x$name, as.integer(x$age))
}
describe.default <- function(x, ...) {
  sprintf("an object of class %s", class(x)[1])
}
alice <- new_member("Alice", 34)
cat(describe(alice), "\n")
cat(describe(1:5), "\n")
cat(describe("text"), "\n")

The member is described by its own method, while the integer vector and the string fall through to describe.default, which reports their implicit classes. The method name is built from the generic name and the class name, so describe.member is found without any registration step. The ... in both the generic and the methods is what allows a caller to pass extra arguments that a particular method may use; a method that omits ... stops with an unused argument error when such an argument arrives. The generic can be inspected with methods("describe"), which lists the methods currently visible.

$ Rscript generic.R
Alice, 34 years old 
an object of class integer 
an object of class character 

Inheritance and NextMethod

The class attribute can hold a vector of names, ordered from the most specific class to the most general. Dispatch tries the first name, then the second, and so on. A method can call NextMethod to continue the search from the next class in the vector, which lets a subclass add its own detail to the behaviour of its parent instead of repeating it.

inheritance.R
new_member <- function(name, age) {
  structure(list(name = name, age = age), class = "member")
}
new_student <- function(name, age, school) {
  structure(c(unclass(new_member(name, age)), list(school = school)),
            class = c("student", "member"))
}
describe <- function(x, ...) UseMethod("describe")
describe.member <- function(x, ...) {
  sprintf("%s, %d years old", x$name, as.integer(x$age))
}
describe.student <- function(x, ...) {
  sprintf("%s, studies at %s", NextMethod(), x$school)
}
carla <- new_student("Carla", 21, "Charles University")
cat("class:", class(carla), "\n")
cat("is member:", inherits(carla, "member"), "\n")
cat(describe(carla), "\n")

The student object has the class vector c("student", "member"), so describe first finds describe.student. That method calls NextMethod, which runs describe.member with the same object and returns the first part of the sentence; the student method then appends the school. A student is also a member, which inherits confirms, so any code that accepts a member accepts a student too. The order of the class vector is the dispatch order, so a more specific class must come first.

$ Rscript inheritance.R
class: student member 
is member: TRUE 
Carla, 21 years old, studies at Charles University 

Group generics

Arithmetic, comparison, and summary functions are group generics: one method covers a whole family of operators. A method named Ops.money receives every binary operator in the group, and .Generic holds the name of the operator that was called. The method can run the default operation with NextMethod and then restore the class and the currency attribute.

ops.R
money <- function(amount, currency = "EUR") {
  structure(amount, class = "money", currency = currency)
}
format.money <- function(x, ...) {
  sprintf("%.2f %s", unclass(x), attr(x, "currency"))
}
print.money <- function(x, ...) {
  cat(format(x), "\n")
  invisible(x)
}
Ops.money <- function(e1, e2) {
  if (.Generic %in% c("==", "!=", "<", "<=", ">", ">=")) {
    return(NextMethod())
  }
  if (!inherits(e1, "money")) {
    e1 <- e2
  }
  structure(NextMethod(), class = "money",
            currency = attr(e1, "currency"))
}
price <- money(19.99)
shipping <- money(4.50)
print(price + shipping)
print(price * 3)
cat("more expensive:", price > shipping, "\n")

Adding two amounts keeps the class and prints 24.49 EUR, and multiplying by a plain number keeps it as well, because the method copies the currency from whichever argument carries it. Comparisons are returned early and stay logical: a comparison that came back as a money object would print as an amount and would break if and which. The same pattern applies to Summary.money for sum, min, and max, and to Math.money for the mathematical functions.

$ Rscript ops.R
24.49 EUR 
59.97 EUR 
more expensive: TRUE 

A complete example

The last script uses two methods on base generics. print.member formats a row, and as.data.frame.member turns one object into a one-row data frame. Applying the coercion to a list of members and binding the rows with do.call(rbind, ...) produces a table; do.call passes the elements of the list as separate arguments to rbind. This is the usual way to move from a list of objects to a data frame without writing a loop.

report.R
new_member <- function(name, age) {
  structure(list(name = name, age = age), class = "member")
}
print.member <- function(x, ...) {
  cat(sprintf("%-8s %3d\n", x$name, as.integer(x$age)))
  invisible(x)
}
as.data.frame.member <- function(x, ...) {
  data.frame(name = x$name, age = x$age, stringsAsFactors = FALSE)
}
people <- list(new_member("Alice", 34),
               new_member("Bob", 41),
               new_member("Carla", 29))
for (member in people) {
  print(member)
}
roster <- do.call(rbind, lapply(people, as.data.frame))
print(roster)
cat("mean age:", mean(roster$age), "\n")

The loop prints three aligned rows with the names padded to eight characters, and as.data.frame dispatches on each member inside lapply. The result is a data frame with one row per person, so the ordinary data frame tools apply: mean returns 34.66667, and subset or order would work without knowing anything about the class. This is the practical value of S3: a class adds behaviour to ordinary data while leaving the data accessible to every function that already works on lists and data frames.

$ Rscript report.R
Alice     34
Bob       41
Carla     29
   name age
1 Alice  34
2   Bob  41
3 Carla  29
mean age: 34.66667 

Next steps

The S4 classes article repeats this work with formal classes, typed slots, and validity checks, and the R6 classes article covers mutable objects with reference semantics. The functions article explains the argument matching and ... that the methods rely on, the lists article covers the container used by most S3 objects, and the apply family article shows the lapply pattern used in the last example.

Source

Advanced R: S3

R documentation: UseMethod and NextMethod

R documentation: group generic functions

R documentation: class

In this article we have given a list a class attribute and built objects with a constructor. We wrote a print method, defined a generic with methods for our class and a default, and added a subclass that extends the parent with NextMethod. A group generic kept the class through arithmetic while leaving comparisons logical, and the final script turned a list of objects into a data frame. The series continues with R S4 classes.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.