In oops, the S3 is used to overload any function. So that we can call the functions with different names, and it depends on the type of input parameter or the number of parameters, and the S4 is the most important characteristic of oops. However, this is a limitation, as it is quite difficult to debug. There is an optional reference class for S4.
In the context of the R programming language, S3 and S4 refer to two different systems for implementing object-oriented programming (OOP) features. Both systems are used to create and manage objects with associated methods, but they have some differences in terms of design and functionality.
S3 System:
Informal and Flexible: S3 (Simple S Objects) is an informal and flexible OOP system in R.
Generic Functions: It allows the creation of generic functions, which are functions that behave differently based on the class of the input object.
No Formal Classes: S3 does not have formal class definitions. Objects are assigned classes using the class() function.
Method Dispatch: The method dispatch is based on the class of the first argument of a generic function. If you have a function like print(), it may have different behaviors for different classes of objects.
Example of S3:
# Creating an S3 object
my_vector <- 1:5
class(my_vector) <- “my_class”
# Creating a generic function
my_generic_function <- function(x) {
UseMethod(“my_generic_function”)
}
# Creating methods for different classes
my_generic_function.my_class <- function(x) {
print(“This is a method for my_class”)
}
# Calling the generic function
my_generic_function(my_vector)
S4 System:
Formal and Strict: S4 is a more formal and strict OOP system in R.
Formal Class Definitions: It allows the definition of formal classes with slots, which are similar to fields or attributes in other programming languages.
Explicit Method Definitions: S4 requires explicit method definitions for functions associated with classes.
Multiple Dispatch: Method dispatch in S4 is based on the classes of all arguments, allowing for multiple dispatch.
Example of S4:
# Creating an S4 class
setClass(“MyClass”, slots = list(data = “numeric”))
# Creating an object of the S4 class
my_object <- new(“MyClass”, data = 1:5)
# Creating a method for the S4 class
setMethod(“myMethod”, signature = “MyClass”, function(object) {
print(“This is a method for MyClass”)
})
# Calling the method
myMethod(my_object)
In summary, S3 is more lightweight and informal, while S4 is more formal and strict, providing features like formal class definitions and multiple dispatch. The choice between S3 and S4 depends on the complexity and formality required for the specific OOP implementation in your R code.