15 S4

15.1 Prerequisites

We load the methods package for anything specifically related to S4 and the lubridate package for the first exercise.


15.2 Basics

  1. Q: lubridate::period() returns an S4 class. What slots does it have? What class is each slot? What accessors does it provide?

    A: Objects of the S4 Period class have the six slots .Data, year, month, day, hour and minute, which are each of type double. Except for .Data all fields have similar named accessors. .Data can be accessed via methods::gedDataPart(). As a short example, we create a period of 1 second, 2 minutes, 3 hours, 4 days and 1 week.

    example12345 <- period(c(1, 2, 3, 4, 5), 
              c("second", "minute", "hour", "day", "week"))

    This should add up to a period of 39 days, 3 hours, 2 minutes and 1 second.

    #> [1] "39d 3H 2M 1S"

    When we inspect our example12345, we can see the fields and conclude that the seconds are stored in the .Data field.

    #> Formal class 'Period' [package "lubridate"] with 6 slots
    #>   [email protected] .Data : num 1
    #>   [email protected] year  : num 0
    #>   [email protected] month : num 0
    #>   [email protected] day   : num 39
    #>   [email protected] hour  : num 3
    #>   [email protected] minute: num 2
  2. Q: What other ways can you find help for a method? Read ?"?" and summarise the details.

    A: We can find

    • general documentation for a generic via ?genericName
    • general documentation for the methods of a generic via methods?genericName
    • documentation for a specific method via ClassName?methodName

    We can also get help for a specific method by adding ? in front of a function call, e.g. ?show(hadley).

15.3 Classes

  1. Q: Extend the Person class with fields to match utils::person(). Think about what slots you will need, what class each slot should have, and what you’ll need to check in your validity method.

    A: The Person class from the textbook contains the slots name and age. The person class from the utils package contains the slots given, family, role, email and comment. All these slots must be of type character. Further, the entries in the role slot must match one of the following abbreviations “aut”, “com”, “cph”, “cre”, “ctb”, “ctr”, “dtc”, “fnd”, “rev”, “ths”, “trl”. Therefore, we include all these slots in our new definition of the Person class. As role might be of different length than the other slots, we include the constraint that all slots must be of length one to the validator.

    # Definition of the Person class
         slots = c(
           name = "character", 
           age = "numeric",
           given = "character",
           family = "character",
           role = "character",
           email = "character",
           comment = "character"
         prototype = list(
           name = NA_character_,
           age = NA_real_,
           given = NA_character_,
           family = NA_character_,
           role = NA_character_,
           email = NA_character_,
           comment = NA_character_
    # Helper to create instances of the Person class
    Person <- function(name, age = NA, 
                   given = NA_character_,
                   family = NA_character_,
                   role = NA_character_,
                   email = NA_character_,
                   comment = NA_character_) {
      age <- as.double(age)
      new("Person", name = name, age = age, 
      given = given, family = family, 
      role = role, email = email,
      comment = comment)
    # Validator to ensure that each slot is of length one
    setValidity("Person", function(object) {
      if (length(object@name)    != 1 |
          length(object@age)     != 1 |
          length(object@given)   != 1 |
          length(object@family)  != 1 |
          length(object@email)   != 1 |
          length(object@comment) != 1) {
        "@name, @age, @given, @family, @email, @comment must be of length 1"
      if (!all(object@role %in% c(NA_character_, 
            "aut", "com", "cph", "cre", "ctb",
            "ctr", "dtc", "fnd", "rev", "ths", "trl"))) {
        paste("@role (s) must be one of", 
              paste (c(NA_character_, 
                                     "aut", "com", "cph", "cre", "ctb",
                                     "ctr", "dtc", "fnd", "rev", "ths", "trl"),
                     collapse = ", "), ".")
    #> Class "Person" [in ".GlobalEnv"]
    #> Slots:
    #> Name:       name       age     given    family      role     email
    #> Class: character   numeric character character character character
    #> Name:    comment
    #> Class: character
  2. Q: What happens if you define a new S4 class that doesn’t have any slots? (Hint: read about virtual classes in ?setClass.)

    A: It depends on the other arguments.

    If we supply a class that doesn’t exist, we’ll get an error

             slots = c(skill = "ANY"),
             contains = "Human")
    #> Error in reconcilePropertiesAndPrototype(name, slots, prototype,
    #> superClasses, : no definition was found for superclass "Human" in the
    #> specification of class "Programmer"

    To can get around that, we register the new class before we define the new class.

    .Programmer <- setClass("Programmer",
                            slots = c(Skill = "ANY"),
                            contains = "Human")

    Supplying neither slots nor contains results in a constructor for virtual classes

    .VirtualProgrammer <- setClass("VirtualProgrammer")
    # equal to contains = "VIRTUAL" (here you could also supply slots)
    .VirtualProgrammer <- setClass("VirtualProgrammer",
                                   contains = "VIRTUAL")

    Just leaving out contains, but supplying slots results in a constructor without superclass

    .DataScientist <- setClass("RProgrammer",
                               slots = c(stats = "ANY",
                                         math = "ANY",
                                         programming = "ANY"))
  3. Q: Imagine you were going to reimplement factors, dates, and data frames in S4. Sketch out the setClass() calls that you would use to define the classes. Think about appropriate slots and prototype.

    A: The basic idea is to use a slot for the base type and one slot per attribute. Inheritance matters for ordered factors and dates. Special checks like equal lengths of list elements for columns of a data frame should be done within a validator.

15.4 Generics and methods

  1. Q: Add age() accessors for the Person class.

    A: Similar as shown for name() in the chapter, we define an age() generic, with a method for the Person class and a replacement function age<-():

    setGeneric("age", function(x) standardGeneric("age"))
    #> [1] "age"
    setMethod("age", "Person", function(x) x@age)
    setGeneric("age<-", function(x, value) standardGeneric("age<-"))
    #> [1] "age<-"
    setMethod("age<-", "Person", function(x, value) {
      x@age <- value
  2. Q: In the definition of the generic, why is it necessary to repeat the name of the generic twice?

    A: The name is needed as the name of the generic as well as to explicitly incorporate method dispatch via standardGeneric() within the generic’s body (def parameter). This is similar to UseMethod() in S3.

  3. Q: Why does the show() method defined in Section 15.4.3 use is(object)[[1]]? (Hint: try printing the employee subclass.)

    A: is(object) returns the class of the object. In cases of subclasses like Employee, is(object) contains also the superclass. In order to return always the most specific class (the subclass), show() returns the first element of is(object).

  4. Q: What happens if you define a method with different argument names to the generic?

    A: It depends. Lets first create the object hadley of class “Person”:

    .Person <- setClass("Person", 
                        slots = c(name = "character", 
                                  age = "numeric"))
    hadley <- .Person(name = "Hadley")
    #> An object of class "Person"
    #> Slot "name":
    #> [1] "Hadley"
    #> Slot "age":
    #> numeric(0)

    Now let us see, which arguments can be supplied to the show() generic

    #> $object

    Usually we would use this argument when defining a new method

    setMethod("show", "Person", 
                cat(object@name, "creates hard exercises")
    #> Hadley creates hard exercises

    When we supply another name as a first element of our method (e.g. x instead of object), this will be matched to the correct object argument and we receive a warning. Our method will work, though

    setMethod("show", "Person", 
                cat(x@name, "creates hard exercises")
    #> Warning: For function 'show', signature 'Person': argument in method
    #> definition changed from (x) to (object)
    #> Hadley creates hard exercises

    If we add more arguments to our method than our generic can handle, we will get an error

    setMethod("show", "Person", 
              function(x, y){
                cat(x@name, "is", x@age, "years old")
    #> Error in conformMethod(signature, mnames, fnames, f, fdef, definition): in
    #> method for 'show' with signature 'object="Person"': formal arguments
    #> (object = "Person") omitted in the method definition cannot be in the
    #> signature

    If we do this with arguments added to the correctly written object argument, we will get the informative error message, that we could add other argument names for generics, which can take the ... argument

    setMethod("show", "Person", 
              function(object, y){
                cat(object@name, "is", object@age, "years old")
    #> Error in rematchDefinition(definition, fdef, mnames, fnames, signature):
    #> methods can add arguments to the generic 'show' only if '...' is an
    #> argument to the generic

15.5 Method dispatch

  1. Q: Draw the method graph for f(😅, 😽).

    A: TODO: This should be straight forward. We just need the class graph from above and insert the graph including the superclasses for both emojis into f(,). Everything then should follow the logic from the chapter…

  2. Q: Draw the method graph for f(😃, 😉, 😙).

    A: TODO: The same as in the last exercise. The challenge here might be to visualize the dispatch efficiently for the combination of three arguments at once.

  3. Q: Take the last example which shows multiple dispatch over two classes that use multiple inheritance. What happens if you define a method for all terminal classes? Why does method dispatch not save us much work here?

    A: We will introduce ambiguity, since one class has distance 2 to all terminal nodes and the other four have distance 1 to two terminal nodes each. To resolve this ambiguity we have to define five more methods, one per class combination.

15.6 S4 and S3

  1. Q: What would a full setOldClass() definition look like for an ordered factor (i.e. add slots and prototype the definition above)?


  2. Q: Define a length method for the Person class.

    A: We can define this method as an S3 method and register it afterwards:

    length.Person <- function(x) "a"
    setMethod("length", "Person", length.Person)