15.2 Basics overview

15.2.1 Set class

Define the class:

setClass("Person", 
  slots = c(
    name = "character", 
    age = "numeric"
  )
)

Create an instance of the class

john <- new("Person", name = "John Smith", age = NA_real_)

15.2.2 Set generics

Define generic functions for setting and getting the age slot

# get the value
setGeneric("age", function(x) standardGeneric("age"))
#> [1] "age"
# set the value
setGeneric("age<-", function(x, value) standardGeneric("age<-"))
#> [1] "age<-"

15.2.3 Set methods

Define methods for the generics:

# get the value
setMethod("age", "Person", function(x) x@age)
# set the value
setMethod("age<-", "Person", function(x, value) {
  x@age <- value
  x
})

# set the value
age(john) <- 50
# get the value
age(john)
#> [1] 50

To give a flavor, there is only one method per slot. In more realistic cases, there might be several methods.