1. Learn
  2. /
  3. Courses
  4. /
  5. Object-Oriented Programming with S3 and R6 in R

Exercise

Creating an S3 Method (1)

By itself, the generic function doesn't do anything. For that, you need to create methods, which are just regular functions with two conditions:

  1. The name of the method must be of the form generic.class.
  2. The method signature - that is, the arguments that are passed in to the method - must contain the signature of the generic.

The syntax is:

generic.class <- function(some, arguments, ...) {
  # Do something
}

Instructions

100 XP

The generic get_n_elements() function has been defined in your workspace.

  • Type its name (without parentheses) to see how it works.
  • Write an S3 method to calculate the number of elements in a data.frame object.
    • The name of the function should be the name of the generic, then a . then the name of the class of the input.
    • The input arguments should be x and ....
    • The body of the function should be a single line, returning the number of elements (rows times columns) in a data frame.
  • Call get_n_elements on the sleep dataset and assign the result to the variable n_elements_sleep.
  • Print n_elements_sleep to the console to see the result.