S3 and S4 Classes (R)

S3 and S4 are R's two main object-oriented systems. S3 is informal and uses a class attribute plus generic functions; S4 is formal with declared slots, types, and stricter method dispatch.

R

S3 is R's simplest OOP system and by far the most common. An object is just data with a class attribute, and 'methods' are functions named generic.class (like print.lm or summary.data.frame). A generic such as print() dispatches to the right method based on the object's class. It's flexible and lightweight, but offers no validation.

S4 is a formal system: you define a class with setClass() declaring named, typed slots, create objects with new(), and define methods with setGeneric()/setMethod(). It enforces structure and supports multiple dispatch (choosing a method based on the classes of several arguments), at the cost of more ceremony. It's used by rigorous packages like those in Bioconductor.

R also has Reference Classes (R5) and the modern R6 package for mutable, encapsulated objects. For most everyday R, S3 is enough; reach for S4 when you need strict contracts and validation.

Syntax

# S3
class(obj) <- "myclass"
print.myclass <- function(x, ...) { ... }

Examples

R

# S3 example
dog <- list(name = "Rex")
class(dog) <- "dog"
print.dog <- function(x, ...) cat("Dog:", x$name, "\n")
print(dog)

Output:

Dog: Rex

See also

Back to the Dictionary