Unlocking the Power of S3 Classes in R
Discover the Simplicity and Flexibility of S3 Classes
The S3 class is the most popular class in the R programming language, and for good reason. Its simplicity and ease of implementation make it a go-to choice for many developers. In fact, most of the classes that come predefined in R are of this type.
Building an S3 Class from Scratch
To create an S3 class, you start by creating a list with various components. Then, you use the class()
function to assign a class to the list. For instance, let’s create a class called Employee_Info
with three components: name
, age
, and role
.
R
employee1 <- list(name = "John Doe", age = 30, role = "Manager")
class(employee1) <- "Employee_Info"
Creating an S3 Object
An S3 object is essentially a list with its class attributes assigned some names. You can create an object of the Employee_Info
class by simply using the list name employee1
.
R
employee1
The Magic of Generic Functions and Methods
But what happens when you try to print an object of the Employee_Info
class? The answer lies in generic functions and methods. A generic function is composed of multiple functions implementing the same operation for different types. In this case, the print()
function is a generic function that has a collection of methods.
R
methods(print)
When you call print()
on an object of class Employee_Info
, it looks for a method of the form print.Employee_Info()
. If it can’t find one, it falls back to the default method print.default()
.
Taking Control with Custom Methods
But what if you want to customize the way your Employee_Info
objects are printed? You can write your own method! Let’s create a method called print.Employee_Info()
that prints the object in a more readable format.
R
print.Employee_Info <- function(obj) {
cat("Name:", obj$name, "\n")
cat("Age:", obj$age, "\n")
cat("Role:", obj$role, "\n")
}
Now, whenever you print an object of the Employee_Info
class, the print.Employee_Info()
method will be called.
R
employee1
The output will be a nicely formatted display of the employee’s information. With S3 classes and custom methods, the possibilities are endless!