Skip to content

S4

S4 Introduction

  • S4 is stricter than S3.
  • It has a formal definition and a uniform way to create objects.
  • Slots: properties of objects. Similar to attributes in JAVA

Define S4 class

student <- setClass("student", slots = list(name = "character", age = "numeric"))

Create S4 Object

method 1
student1 <- new("student", name = "John", age = 18)

The function setClass() returns a generator function, which can be used to create new objects.

method 2
student2 <- student(name = "Linda", age = 17)

Access and modify slots

access slot
student2@name
rewrite slot directly
student2@age <- 20
rewrite with slot() function
slot(student2, "age") <- "20"

List all generic functions

showMethods()

Customize S4 methods

setGeneric("print_info", function(object) standardGeneric("print_info"))

setMethod(
  "print_info",
  "student",
  function(object) {
    cat("Name:", object@name, "\n")
    cat("Age:", object@age, "years old\n")
    }
)

Inheritance

international_student <- setClass("international_student", 
         contains = "student", 
         slots = c(
           Country = "character",
           teammate = "student"
         )
)
student3 <- international_student(name = "X", age = 17, Country = "Canada", teammate = student1)