The S3 object system helps organize data and functions in R by grouping related information and actions together. It makes your code easier to understand and extend.
S3 object system in R Programming
Use the function UseMethod("generic_function") inside a generic function. Define methods with the name generic_function.classname <- function(object) { ... }. Create objects by assigning a class attribute: class(object) <- "classname".
The generic function decides which method to call based on the object's class.
Classes in S3 are just character strings assigned to objects.
print.myclass <- function(x) { cat("This is an object of class 'myclass':", x, "\n") } obj <- 42 class(obj) <- "myclass" print(obj)
summary.mydata <- function(object) {
cat("Summary of mydata object:\n")
cat("Length:", length(object), "\n")
}
myobj <- 1:5
class(myobj) <- "mydata"
summary(myobj)This program defines a generic function greet and two methods for classes 'person' and 'dog'. It shows how the same function name can do different things based on the object's class.
greet <- function(x) {
UseMethod("greet")
}
greet.person <- function(x) {
cat("Hello,", x$name, "!\n")
}
greet.dog <- function(x) {
cat("Woof!", x$name, "is happy to see you!\n")
}
person1 <- list(name = "Alice")
class(person1) <- "person"
dog1 <- list(name = "Buddy")
class(dog1) <- "dog"
# Call greet for different objects
greet(person1)
greet(dog1)S3 is simple and flexible but does not enforce strict class definitions.
Method names must follow the pattern generic.class for S3 dispatch to work.
You can assign multiple classes by setting class to a vector of names.
S3 lets you write functions that behave differently for different object types.
It uses simple naming rules and class attributes to decide which method to run.
S3 is great for organizing code and making it easier to extend.