Get startedGet started for free

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() (docs will print any type of object that doesn't have its own print() (docs) method.

This exercise is part of the course

Object-Oriented Programming with S3 and R6 in R

View Course

Exercise instructions

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

  • Use ls.str() (docs) 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 (docs) dataset and assign the result to the variable n_elements_ability.cov.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# View predefined objects
___

# Create a default method for get_n_elements
___ <- ___




# Call the method on the ability.cov dataset
n_elements_ability.cov <- ___
Edit and Run Code