The S4 object system helps organize data and functions in R by creating formal classes and methods. It makes your code clearer and easier to manage.
0
0
S4 object system in R Programming
Introduction
When you want to define complex data structures with strict rules.
When you need to create methods that behave differently for different types of data.
When you want to ensure your objects have specific properties and types.
When building packages that require formal and reliable object definitions.
Syntax
R Programming
setClass("ClassName", slots = list( slot1 = "type1", slot2 = "type2" )) setMethod("methodName", signature(object = "ClassName"), function(object) { # method code })
setClass defines a new class with named slots (like fields) and their types.
setMethod defines a function that works specifically for objects of that class.
Examples
This creates a class
Person with slots for name and age.R Programming
setClass("Person", slots = list( name = "character", age = "numeric" ))
This defines how to print a
Person object nicely.R Programming
setMethod("show", signature(object = "Person"), function(object) { cat("Name:", object@name, "\nAge:", object@age, "\n") })
This creates a
Person object and shows its content.R Programming
p <- new("Person", name = "Alice", age = 30) show(p)
Sample Program
This program defines a Car class with brand and year. It also defines how to print a Car object. Then it creates a Car object and prints it.
R Programming
setClass("Car", slots = list( brand = "character", year = "numeric" )) setMethod("show", signature(object = "Car"), function(object) { cat("Car brand:", object@brand, "\nYear:", object@year, "\n") }) myCar <- new("Car", brand = "Toyota", year = 2020) show(myCar)
OutputSuccess
Important Notes
Use @ to access slots of an S4 object, like object@slotName.
S4 classes enforce slot types strictly, so you must provide correct types when creating objects.
Defining methods for S4 classes helps organize code and supports polymorphism (same function name, different behaviors).
Summary
S4 system creates formal classes with named slots and types.
Methods define how functions behave for specific classes.
S4 helps write clear, organized, and reliable R code.