evoalgs-r-practise/intro/classes.R

42 lines
1.1 KiB
R

# S3 and S4 are two different object-oriented programming (OOP) systems in R.
# S3 is a simple and informal OOP system, while S4 is a more formal and rigorous OOP system.
# S3 Classes
# ----------
# Creating an S3 class
create_person_s3 <- function(name, age) {
obj <- list(name=name, age=age)
class(obj) <- "PersonS3"
return(obj)
}
# Creating a print method for the S3 class
print.PersonS3 <- function(x) {
cat("PersonS3: Name =", x$name, "- Age =", x$age, "\n")
}
# Example of creating and printing an S3 object
person_s3 <- create_person_s3("Alice", 30)
print(person_s3)
# S4 Classes
# ----------
# Defining an S4 class
setClass("PersonS4",
slots = list(name = "character", age = "numeric"))
# Creating a constructor for the S4 class
create_person_s4 <- function(name, age) {
obj <- new("PersonS4", name=name, age=age)
return(obj)
}
# Creating a show method for the S4 class (similar to print method)
setMethod("show", "PersonS4", function(object) {
cat("PersonS4: Name =", object@name, "- Age =", object@age, "\n")
})
# Example of creating and showing an S4 object
person_s4 <- create_person_s4("Bob", 25)
show(person_s4)