ZetCode

R S4 classes

last modified November 19, 2026

S4 is the formal object system that ships with R in the methods package. A class is declared with setClass, every field is a typed slot, and objects are created with new. The system checks that a slot receives the declared type and that the whole object satisfies a validity function, and its generics can dispatch on more than one argument. This article covers class definitions, slots, validity, generic methods, inheritance, virtual classes, and container classes. The examples use base R 4.5.2 and the methods package, which is attached in every session.

Defining a class

setClass takes a name and a named vector of slots, where each name is followed by the class that the slot accepts. new creates an object and fills the slots from the named arguments. The @ operator reads or writes a slot, and slotNames lists them. Unlike an S3 class, an S4 object stores its class in a formal definition that R can inspect.

define.R
setClass("Member", slots = c(name = "character", age = "numeric"))
alice <- new("Member", name = "Alice", age = 34)
cat("class:", class(alice), "\n")
cat("is Member:", is(alice, "Member"), "\n")
cat("slots:", slotNames(alice), "\n")
cat("name:", alice@name, "\n")
str(alice)

The object reports the class Member and the two slots in the order they were declared. @ accesses a slot by its exact name; the $ operator does not work on S4 objects, and partial matching is not applied. str shows the formal class with its package, here .GlobalEnv because the class was defined in the script. is is the S4 counterpart of inherits; it also understands the class hierarchy that the next sections use.

$ Rscript define.R
class: Member 
is Member: TRUE 
slots: name age 
name: Alice 
Formal class 'Member' [package ".GlobalEnv"] with 2 slots
  ..@ name: chr "Alice"
  ..@ age : num 34

Validity and prototypes

A slot type prevents a character from being stored in a numeric slot, but it cannot express rules such as "the age must not be negative". A validity function does that. setValidity registers a function that returns TRUE for a valid object or a string that describes the first problem. The optional prototype gives default values, so an object can be created without supplying every slot.

validity.R
setClass("Member",
         slots = c(name = "character", age = "numeric"),
         prototype = list(name = "unknown", age = 0))
invisible(setValidity("Member", function(object) {
  if (length(object@name) != 1) {
    return("name must have length one")
  }
  if (object@age < 0) {
    return("age must not be negative")
  }
  TRUE
}))
member <- new("Member", name = "Alice", age = 34)
cat("valid:", validObject(member, test = TRUE), "\n")
member@age <- -3
cat("valid after edit:", validObject(member, test = TRUE), "\n")
empty <- new("Member")
cat("prototype:", empty@name, empty@age, "\n")

The fresh object is valid, and validObject returns TRUE. After the age is changed to a negative number the same call returns the message from the validity function instead, which names the rule that failed. test = TRUE asks for that report rather than an error, so the result can be printed or checked in a condition. new runs the same check when it creates an object and refuses an invalid one. The empty object shows the prototype values unknown and 0.

$ Rscript validity.R
valid: TRUE 
valid after edit: age must not be negative 
prototype: unknown 0 

Methods and show

An S4 generic is created with setGeneric, and methods are registered with setMethod, which takes the generic name, a signature, and a function. The signature names the arguments that select the method; with one class name it dispatches on the first argument, and with a vector of class names it can dispatch on several arguments at once. show is the generic that print uses for S4 objects, so a show method controls how an object appears.

show-method.R
setClass("Member", slots = c(name = "character", age = "numeric"))
invisible(setGeneric("describe", function(x) standardGeneric("describe")))
setMethod("describe", "Member", function(x) {
  sprintf("%s, %d years old", x@name, as.integer(x@age))
})
setMethod("show", "Member", function(object) {
  cat("Member:", object@name, "\n")
})
alice <- new("Member", name = "Alice", age = 34)
show(alice)
cat(describe(alice), "\n")

show prints the short form of the object, and describe returns a sentence. The call to setGeneric returns the name of the generic, so it is wrapped in invisible to keep the script output clean. A method should return a value of the type the generic promises, and show should return its object invisibly. If no method matches a class and the generic has no default method, R stops with an error instead of guessing, so a method for a virtual parent is often the right place for shared behaviour.

$ Rscript show-method.R
Member: Alice 
Alice, 34 years old 

Inheritance

A subclass is declared with contains, which names the parent class. The subclass inherits every slot and every method, and it can add slots of its own. Objects are still created with new, which accepts the slots of both classes. callNextMethod runs the parent method from inside the child method, which is the S4 counterpart of NextMethod.

inheritance.R
setClass("Member", slots = c(name = "character", age = "numeric"))
setClass("Student", contains = "Member", slots = c(school = "character"))
invisible(setGeneric("describe", function(x) standardGeneric("describe")))
setMethod("describe", "Member", function(x) {
  sprintf("%s, %d years old", x@name, as.integer(x@age))
})
setMethod("describe", "Student", function(x) {
  sprintf("%s, studies at %s", callNextMethod(), x@school)
})
carla <- new("Student", name = "Carla", age = 21,
             school = "Charles University")
cat("class:", class(carla), "\n")
cat("is Member:", is(carla, "Member"), "\n")
cat("slots:", slotNames(carla), "\n")
cat(describe(carla), "\n")

The student has the slots school, name, and age, with the inherited slots listed after the new one. The class is reported as Student only, unlike an S3 class vector, because the parent relationship is stored in the class definition rather than in the object. is(carla, "Member") follows that definition and returns TRUE. callNextMethod produces the parent part of the sentence, and the student method adds the school to it.

$ Rscript inheritance.R
class: Student 
is Member: TRUE 
slots: school name age 
Carla, 21 years old, studies at Charles University 

Virtual classes

A virtual class cannot be instantiated, because it exists to define a common interface for its subclasses. contains = "VIRTUAL" marks it as virtual. The subclasses inherit its slots, and a generic declares the operation that the subclasses provide. This is the S4 way to write polymorphic code over a family of types.

virtual.R
setClass("Shape", contains = "VIRTUAL", slots = c(name = "character"))
setClass("Circle", contains = "Shape", slots = c(radius = "numeric"))
setClass("Rectangle", contains = "Shape",
         slots = c(width = "numeric", height = "numeric"))
invisible(setGeneric("area", function(shape) standardGeneric("area")))
setMethod("area", "Circle", function(shape) {
  pi * shape@radius^2
})
setMethod("area", "Rectangle", function(shape) {
  shape@width * shape@height
})
shapes <- list(
  new("Circle", name = "pond", radius = 2),
  new("Rectangle", name = "lawn", width = 3, height = 4)
)
for (shape in shapes) {
  cat(shape@name, ":", round(area(shape), 2), "\n")
}
cat("virtual:", isVirtualClass("Shape"), "\n")

The list holds two different classes, and area selects the method from the class of each element, so a loop needs no type test. The circle covers 12.57 square units and the rectangle 12, and the shape has a name in both cases because the slot comes from the virtual parent. Calling new("Shape") would fail because the class is virtual. isVirtualClass confirms the marking, which is useful in code that inspects a class before using it.

$ Rscript virtual.R
pond : 12.57 
lawn : 12 
virtual: TRUE 

A complete example

The final example collects shapes in a container class. The container has a label and a list of shapes, and it defines two methods: length returns the number of shapes, and show prints a line for each. length and show already exist as generics, so the methods extend functions that the rest of R already calls.

bundle.R
setClass("Shape", contains = "VIRTUAL", slots = c(name = "character"))
setClass("Circle", contains = "Shape", slots = c(radius = "numeric"))
setClass("Rectangle", contains = "Shape",
         slots = c(width = "numeric", height = "numeric"))
invisible(setGeneric("area", function(shape) standardGeneric("area")))
setMethod("area", "Circle", function(shape) {
  pi * shape@radius^2
})
setMethod("area", "Rectangle", function(shape) {
  shape@width * shape@height
})
setClass("Bundle", slots = c(label = "character", shapes = "list"))
setMethod("length", "Bundle", function(x) {
  length(x@shapes)
})
setMethod("show", "Bundle", function(object) {
  cat("Bundle:", object@label, "with", length(object), "shapes\n")
  for (shape in object@shapes) {
    cat(" ", shape@name, round(area(shape), 2), "\n")
  }
})
bundle <- new("Bundle", label = "garden",
              shapes = list(new("Circle", name = "pond", radius = 1.5),
                            new("Rectangle", name = "lawn",
                                width = 4, height = 3)))
show(bundle)
areas <- sapply(bundle@shapes, area)
cat("total area:", round(sum(areas), 2), "\n")
cat("largest:", bundle@shapes[[which.max(areas)]]@name, "\n")

length(bundle) now returns two, and show uses it in the header, so the two methods cooperate. The areas are computed by applying area to each element of the slot, which dispatches on the class of every shape, and which.max picks the largest. The pond covers 7.07 square units and the lawn 12, for a total of 19.07. A container class like this is how S4 code groups objects while keeping each element's own behaviour.

$ Rscript bundle.R
Bundle: garden with 2 shapes
  pond 7.07 
  lawn 12 
total area: 19.07 
largest: lawn 

Next steps

The R6 classes article covers mutable objects with reference semantics, which suit stateful programs better than the value-based S4 objects here. The S3 classes article introduces the lighter system that most of base R uses, and the functions article explains the argument matching that new and the methods rely on. The lists article describes the slot type used for the container in the last example.

Source

Advanced R: S4

R documentation: setClass

R documentation: validObject

R documentation: setGeneric

R documentation: setMethod

R documentation: show

In this article we have defined S4 classes with typed slots and created objects with new. We added a prototype and a validity rule, wrote a show method and a generic of our own, and extended a class through contains and callNextMethod. A virtual shape class dispatched over a list of subclasses, and a bundle class extended length and show. The series continues with R R6 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.