10 S3

10.1 Basics

  1. Q: The most important S3 objects in base R are factors, data frames, difftimes, and date/times (Dates, POSIXct, POSIXlt). You’ve already seen the attributes and base type that factors are built on. What base types and attributes are the others built on?

    A: TODO: Add answer for difftime.

    data frame: Data frames are build up on (named) lists. Together with the row.names attribute and after setting the class to “data.frame”, we get a classical data frame

    date/times (Dates, POSIXct, POSIXlt): Date is just a double with the class attribute set to “Date”

    POSIXct is a class for date/times that inherits from POSIXt and is built on doubles as well. The only attribute is tz (for timezone)

    POSIXlt is another date/time class that inherits from POSIXt. It is built on top of a named list and a tzone attribute. Differences between POSIXct and POSIXlt are described in ?DateTimeClasses.

  2. Q: Describe the difference between t.test() and t.data.frame()?

    A:

  3. Q: Describe the difference in behaviour in these two calls.

    A: Since mean() is a generic and some_days is an object of class Date, the first call results in mean.Date(some_days).

    In the second call unclass() removes the class attribute from some_days, which means that unclass(some_days) is not an OO object and the call results in mean.default(unclass(some_days)), which calculates the mean of the underlying double.

    When you look into the source code of mean.Date() (one line), you will see that the difference in the resulting objects is only the class attribute.

  4. Q: What does the as.data.frame.data.frame() method do? Why is it confusing? How should you avoid this confusion in your own code?

    A: The name is confusing, because it is not clear, from the name, if it is a normal function, a generic or a method. Even if we know, that it is a method, the name doesn’t tell us, which part is the name of the generic and which part is the class name.
    We can easily avoid this confusion, by forgoing to use period separated class and function names.

    To reveal the solution: as.data.frame.data.frame() is the data frame method of the as.data.frame() generic. Methods of this generic generally coerce objects to data frames.
    This specific method strips all class attributes preceding the “data.frame” class.
    If row names are supplied, this method will check their length and then set these as new “row.names” attribute.

  5. Q: What does the following code return? What base type is it built on? What attributes does it use?

    A: It returns the Empirical Cumulative Distribution Function of rpois(100, 10). It is built on the base type “closure” and it saves the expression, which was used to create it, in its call attribute.

10.2 Classes

  1. Q: Write a constructor for data.frame objects. What base type is a data frame built on? What attributes does it use? What are the restrictions placed on the individual elements? What about the names?

    A: Data frames are built on (named) lists and their only attribute is row.names. Row names must be unique and have the same length as observations within the data. They must be of type integer or character. Also all elements must have the same length. Technically there are no restrictions to column names apart to those of lists, so one could surround special names via backticks at creation (of course this is not recommended). A very good constructor regarding these criteria is already implemented within the sloop package.

  2. Q: Enhance our factor() helper to have better behaviour when one or more values is not found in levels. What does base::factor() do in this situation?

    A: base::factor() converts these values (silently) into NA’s. To improve our factor() helper, we write a more informative error message.

  3. Q: Carefully read the source code of factor(). What does it do that our constructor does not?

    A: It allows more general values as x input and converts them to character or replaces them by character(0) (in case of NULL). It also ensures that the levels are unique. This is done by setting the levels via the base::levels<- function, which fails when one tries to supply duplicated level values.

  4. Q: Factors have an optional “contrasts” attribute. Read the help for C(), briefly describe it’s purpose. Rewrite our new_factor() constructor to include this attribute.

    A:

  5. Q: Read the documentation for utils::as.roman(). How would you write a constructor? Does it need a validator? What would a helper look like?

    A:

10.3 Generics and methods

  1. Q: Read the source code for t() and t.test() and confirm that t.test() is an S3 generic and not an S3 method. What happens if you create an object with class test and call t() with it? Why?

    A: We can see that t.test() is a generic, because it calls UseMethod()

    There are also other (programmatic) possibilities to check this like pryr::ftype(), which checks via its internal pryr:::is_s3_generic, which uses codetools::findGlobals() that t.test() contains a call to UseMethod().

    Interestingly, while digging a bit around in the pryr package, one can also find some dependencies to the tools package, where a list of functions exists, which tells you about some functions that look like methods, but are not.

    However, if we create an object with class test, t(), will dispatch to t.test(). This simply happens, because UseMethod() just looks for functions named paste0("generic", ".", c(class(x), "default")). So t.test() is erroneously treated like a method of t(). Since t.test() is a generic itself and doesn’t find a method called t.test.test(), it dispatches to t.test.default(). Just to proof the latter quickly, we specify a method t.test.test() and see what happens:

  2. Q: Which base generic has the greatest number of defined methods?

    A: print() has clearly the most

  3. Q: The table() function produces output with class “table”. What attributes does this class possess? What generics does it have methods for?

    A:

  4. Q: Carefully read the documentation for UseMethod() and explain why the following code returns the results that it does. What two usual rules of function evaluation does UseMethod() violate?

    A: R looks for the x argument in g()’s calling environment (the global environment), where x is defined as 1. Then g() dispatches to g.default(). The x argument is given to g.default(). y is not defined inside it, so g.default() takes y’s value from the environment where UseMethod() created the call. There y is defined as 10.

    UseMethod() behaves special in many ways, two of them are:

    • it never “returns” (any statement after UseMethod won’t be evaluated)
    • the argument matching can become a bit tricky (generic and methods should have the same order of arguments or you must name them)
  5. Q: What are the arguments to [? Why is this a hard question to answer?

    A:

10.4 Object styles

  1. Q: Categorise the objects returned by lm(), factor(), table(), as.Date(), ecdf(), ordered(), I() into “vector”, “scalar”, and “other”.

    A:

    vector: factor(), table(), as.Date(), ordered()
    scalar: lm()
    other: ecdf(), I()

  2. Q: What would a constructor function for lm objects, new_lm(), look like? Why is a constructor function less useful for linear models? (Think about what functions would call new_lm().)

    A: TODO: 2nd part of the question.

10.5 Inheritance

  1. Q: The ordered class is a subclass of factor, but it’s implemented in a very ad hoc way in base R. Implement it in a principled way by building a constructor and providing vec_restore() method.

    A: TODO: the olad exercise text ended on “an as_ordered generic”. Check the answer if it needs to be updated.

    ordered is a subclass of factor, so we need to do the following

    • for factors: add a subclass argument to the constructor and helper
    • for ordered: add a constructor
    • write an as_ordered() generic with methods ordered, factor and default

    We use the factor constructor from the textbook and add the subclass argument

    We also use the validator for factors from the textbook

    And we add the subclass argument for the helper from the textbook and the exercises

    A constructor for ordered is already implemented in the sloop package:

    The implementation of the generic and the first two methods is straight forward

    For the factor method of as_ordered() we use the factor helper, since it saves us some typing:

    Finally, our new method preserves all levels:

    For a real scenario, we might want to add an as_factor.ordered() method to the as_factor() generic from the textbook.

  2. Q: How does [.Date support subclasses? How does it fail to support subclasses?

    A:

  3. Q: R has two classes for representing date time data, POSIXct and POSIXlt, which both inherit from POSIXt. Which generics have different behaviours for the two classes? Which generics share the same behaviour?

    A: To answer this question, we have to get the regarding generics

    Those generics that have a method for POSIXt are potentially sharing the same behaviour (generics_t). However, those generics that have a specific method for one of the sublcases have to be subtractet:

    The rest is different

  4. Q: What do you expect this code to return? What does it actually return? Why?

    A: TODO: Question text changed from “Explain what is happening in the following code.”…So check, if the answer needs to be updated accordingly. Also set eval to true in the code chunk and check why new_s3_scalar is not found (maybe wrong sloop version?).

    • We supply an object of classes b and a2 to generic2(), so R will look for a methodgeneric2.b()
    • generic2.b() changes the class to a1 and then calls NextMethod()
    • One could think, that R calls nowgeneric2.a1(). But in fact, as mentioned in the textbook, NextMethod()

      doesn’t actually work with the class attribute of the object, but instead uses a special global variable (.Class) to keep track of which method to call next.

    • We can easily verify (for example via print()) that .Class is still c("b", "a2") and so generic2.a2() gets called.

10.6 Dispatch details

  1. Q: Explain the differences in dispatch below:

    A:

  2. Q: What classes have a method for the Math group generic in base R? Read the source code. How do the methods work?

A: The following functions belong to this group (see ?Math):

  • abs, sign, sqrt, floor, ceiling, trunc, round, signif
  • exp, log, expm1, log1p, cos, sin, tan, cospi, sinpi, tanpi, acos, asin, atan, cosh, sinh, tanh, acosh, asinh, atanh
  • lgamma, gamma, digamma, trigamma
  • cumsum, cumprod, cummax, cummin
The following classes have a method for this group generic:


```r
methods("Math")
#> [1] Math,nonStructure-method Math,structure-method   
#> [3] Math.data.frame          Math.Date               
#> [5] Math.difftime            Math.factor             
#> [7] Math.POSIXt              Math.quosure*           
#> see '?methods' for accessing help and source code
```

To read the source code of the S3 classes, we can just enter the name of the method into the console. To get the source code of the S4 classes, we can use `getMethod()`, i. e. `getMethod("Math", "nonStructure")`.

To explain the basic idea, we just overwrite the data frame method:


```r
Math.data.frame <- function(x){"hello"}
```

Now all functions from the math generic group, will return `"hello"`


```r
abs(iris)
#> [1] "hello"
exp(iris)
#> [1] "hello"
lgamma(iris)
#> [1] "hello"
```

So, I hope the idea is clear. However, of course different functions should perform different calculations. Here `.Generic` comes into play, which provides us the calling generic as a string


```r
Math.data.frame <- function(x, ...){
  .Generic
}

abs(iris)
#> [1] "abs"
exp(iris)
#> [1] "exp"
lgamma(iris)
#> [1] "lgamma"

rm(Math.data.frame)
```

`Math.data.frame()` is a good example, how to invoke `.Generic` to build sth. constructive up on `.Generic`. `Math.factor()` is a good example of a method, which is simply defined for better error messages.
  1. Q: Math.difftime() is more complicated than I described. Why?

    A: Math.difftime() needs to exclude other cases than abs, sign, floor, ceiling, trunc, round and signif and supply an according error message.

10.7 Old exercises

  1. Q: Draw a Venn diagram illustrating the relationships between functions, generics, and methods.

    A: Funtions don’t have to be generics or methods, but both the latter are functions. It is also possible that a function is both, a method and a generic, at the same time, which seems to be relatively awkward, so that also the author of the textbook doesn’t recommend it, see ?pryr::ftype

    This function figures out whether the input function is a regular/primitive/internal function, a internal/S3/S4 generic, or a S3/S4/RC method. This is function is slightly simplified as it’s possible for a method from one class to be a generic for another class, but that seems like such a bad idea that hopefully no one has done it.

  2. Q: Write a constructor for difftime objects. What base type are they built on? What attributes do they use? You’ll need to consult the documentation, read some code, and perform some experiments.

    A: Our constructor should be named new_class_name, have one argument for its base type and each attribute and check the base types of these arguments as well.

    However, since the following result prints awkward

    we get a little bit more “inspiration” by the original difftime() function and make the regarding changes. Basically we need to implement logic for the units attribute, in case it is set to "auto" and convert the value of the underlying double from seconds to the regarding unit, as commented in the following