Chapter 15 S4
15.2 Basics
Broadly, what is a generic and method in S4 and what is their relationship?
setClass("Person",
slots = c(
name = "character",
age = "numeric"
)
)
setGeneric("age", function(x) standardGeneric("age"))
setGeneric("age<-", function(x, value) standardGeneric("age<-"))
setMethod("age", "Person", function(x) x@age)
setMethod("age<-", "Person", function(x, value) {
x@age <- value
x
})
john <- new("Person", name = "John Smith", age = 12)
age(john)
[1] 12
A generic is a function that will dispatch differently based on the class it is applied to. Above we apply the age
generic to Person
using setMethod
but we could create an age
method that behaves differently for another class, like dogs (which will add 7 to the supplied age)
setClass("Person", slots = c(name = "character",age = "numeric"))
setGeneric("age", function(x) standardGeneric("age"))
setGeneric("age<-", function(x, value) standardGeneric("age<-"))
setMethod("age", "Person", function(x) x@age)
setMethod("age<-", "Person", function(x, value) {
x@age <- value
x
})
setClass("Dog", slots = c(name = "character", age = "numeric"))
# You want the age generic to automatically return 7x the slot in human years
setMethod("age", "Dog", function(x) {x@age*7} )
setMethod("age<-", "Dog", function(x, value) {
x@age <- value
x
})
spot <- new("Dog", name = "Spot Smith", age = 12)
age(spot)
[1] 84
What is standardGeneric
doing in the example above?
It’s the same thing as UseMethod
but for S4
15.3.6.2 Exercises
What is a virtual class and how does it relate to setClassUnion
[see ?setClass
]
A virtual class is a class that cannot be instanciated. Rather than define two of the same methods for two classes, give them both a virtual parent class with the shared method.
Signature
In our own words what exactly is a signature? Are there any signatures within our Person
example? If not can we add one?
15.5.1 Single dispatch
What’s a use case in the wild for ANY
?