Exercise

Creating an S3 method (2)

If no suitable method is found for a generic, then an error is thrown. For example, at the moment, get_n_elements() only has a method available for data.frames. If you pass a matrix to get_n_elements() instead, you'll see an error.

> get_n_elements(matrix())
Error: no applicable method for 'get_n_elements' applied to an object of class "c('matrix', 'array', 'logical')"

Rather than having to write dozens of methods for every kind of input, you can create a method that handles all types that don't have a specific method. This is called the default method; it always has the name generic.default. For example, print.default() will print any type of object that doesn't have its own print() method.

Instructions

100 XP

The generic get_n_elements() function and a method for data.frames have been defined in your workspace.

  • Use ls.str() to explore your workspace.
  • Write a S3 default method for get_n_elements().
    • The name of the function should be the name of the generic, then a . then default.
    • The input arguments should be x and ....
    • The body of the function should be a single line, returning the number of elements in an arbitrary object. Use the same technique as with the chess game in the Make it Classy (1) exercise.
  • Call your method on the ability.cov dataset and assign the result to the variable n_elements_ability.cov.