Of course! This is a fundamental and excellent question for anyone wanting to understand how R really works.
In simple terms:
An S3 object in R is a regular R object (like a list, vector, or matrix) that has been given a special class attribute. This class attribute tells generic functions like print(), summary(), and plot() how to behave when they are called on that object.
Let's break that down. The S3 system is R's simplest and most common Object-Oriented (OO) system. It's built on three key components:
-
The Object (The Data): This is just a standard R data structure. Most commonly, S3 objects are lists, because lists can hold different types of data (e.g., a number, a character string, and a data frame all in one object).
-
The class Attribute (The Label): This is a character string assigned to the object to tell R what "kind" of object it is. This is the only thing that makes a regular list an "S3 object".
-
Generic Functions and Methods (The Behavior):
- A Generic Function is a dispatcher function like
print(). Its only job is to look at the class of the object it's given and find the right "method" to run. If you look at the code for print, you'll see UseMethod("print").
- A Method is a specific version of a generic function for a particular class. Methods follow a strict naming convention:
generic.class. For example, the print method for an object of class lm (linear model) is a function called print.lm.
A Practical Walkthrough Example
Let's create our own S3 object from scratch. Imagine we want to represent an employee.
Step 1: Create the base object (a simple list)
Our employee will have a name, an ID, and a start date. A list is a perfect way to store this.
# This is just a regular list for now
employee_data <- list(
name = "Alice",
id_number = 901,
start_date = as.Date("2021-10-26")
)
# Let's see its class
class(employee_data)
# [1] "list"
# If we print it, we get the default list printout
print(employee_data)
# $name
# [1] "Alice"
#
# $id_number
# [1] 901
#
# $start_date
# [1] "2021-10-26"
Step 2: Make it an S3 object by assigning a class
We can turn this list into an employee object using the class() function or structure().
# Option 1: Assign the class directly
class(employee_data) <- "employee"
# Let's check the class again
class(employee_data)
# [1] "employee"
# Now it's an S3 object!
# But if we print it now, R doesn't know what to do...
print(employee_data)
When we print it now, R looks for a function called print.employee. It can't find one, so it falls back to the default method, print.default, which gives us the same list output as before.
Step 3: Create a method for our new class
This is where the magic happens. We will define our own print method specifically for the employee class.
# Define a method for the generic function `print` and class `employee`
print.employee <- function(x, ...) {
cat("Employee Details\n")
cat("----------------\n")
cat("Name:", x$name, "\n")
cat("ID: ", x$id_number, "\n")
}
Step 4: See Method Dispatch in Action
Now, let's call print() on our object again.
# R will now find and use our custom print.employee method!
print(employee_data)
# Employee Details
# ----------------
# Name: Alice
# ID: 901
What just happened?
- We called
print(employee_data).
- The generic
print function inspected the object and saw class(employee_data) is "employee".
- It then searched for a function named
print.employee.
- It found the one we just created and executed it. This process is called method dispatch.
We can create methods for other generics too, like summary.
summary.employee <- function(object, ...) {
days_worked <- as.numeric(Sys.Date() - object$start_date)
cat(object$name, "has been an employee for approximately", round(days_worked), "days.\n")
}
# Now call summary() on our object
summary(employee_data)
# Alice has been an employee for approximately 940 days.
Key Characteristics of S3
- Informal and Flexible: You don't need to formally define a class. You can just assign a class attribute to any object at any time.
- Function-Centric: The methods belong to the generic functions, not to the object or the class. You write
print.employee(), not employee$print().
- Ubiquitous: S3 is the most widely used OO system in R. You are using it all the time without even realizing it.
data.frame is an S3 class.
- The output of
lm() (linear model) is an S3 object of class "lm".
factor and Date are S3 classes.
S3 vs. Other R OO Systems
- S4: More formal and strict. Classes and their "slots" (attributes) are formally defined using
setClass(). Methods are also formally defined with setMethod(). It's used heavily in the Bioconductor project.
- R6: Behaves more like object-oriented systems in other languages (like Python or Java). Methods belong to the objects, and objects can have state that changes. It's great for building applications or simulations where you need to manage complex, stateful objects.