15 S4

15.1 Prerequisites

We load the methods package as it contains the S4 object-orientation system.

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 six slots named .Data, year, month, day, hour and minute, which are each of type double. Most fields can be retrieved by identically named accessor (e.g. lubridate::year() will return the field). Just the .Data has a specially named accessor, called methods::gedDataPart().

    As a short example, we’;; create a period of 1 second, 2 minutes, 3 hours, 4 days and 5 weeks.

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

    When we inspect example_12345, we see the fields and infer that the seconds are stored in the .Data field.

  2. Q: What other ways can you find help for a method? Read ?"?" and summarise the details.

    A: Besides adding ? in front of a function call (?method()), we may 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.

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.

    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. role might be of different length than the other slots. Because of this we add a constraint to the validator, that all slots must be of length one.

    # 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.

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

    Supplying neither slots nor contains leads to a constructor for virtual classes.

    Just leaving out contains, but supplying slots, creates a constructor without a superclass.

  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: We may use a slot for the base type and one slot per attribute. Keep in mind, that inheritance matters for ordered factors and dates. Also, special checks like equal lengths of list elements for columns of a data frame should be done within a validator.

    For simplicity we don’t introduce an explicit subclass for ordered factors. Instead, we introduce ordered as a slot.

    The Date2 class stores it’s dates as integers, similarly to base R. A print method for our new class could then be provided.

    Our DataFrame class consists of a list and a slot for row.names. More serious checks should be part of a validator.

15.4 Generics and methods

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

    A: Here we define an age() generic, with a method for the Person class and a replacement function age<-():

  2. Q: In the definition of the generic, why is it necessary to repeat the name of the generic twice?

    A: First the name is needed as the name of the generic. The name also explicitly incorporates method dispatch via standardGeneric() within the generic’s body (def parameter). This behaviour 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. is(object) also contains the superclass, for subclasses like Employee. In order to always return 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. We first create the object hadley of class “Person”:

    Now let’s see, which arguments can be supplied to the show() generic.

    Usually we would use this argument when defining a new method.

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

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

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

15.5 Method dispatch

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

    A: Look at the graph and repeat after me: “I will keep my class structure simple and use multiple inheritance sparingly”.

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

    A: We see, that the method graph below looks simpler than the one above. Relativly speaking, multiple dispatch seems to introduce less complexitiy than multiple inheritance. Use it with care, though!

  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: