CommencerCommencer gratuitement

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
}

Cet exercice fait partie du cours

Object-Oriented Programming with S3 and R6 in R

Afficher le cours

Instructions

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 (docs) dataset and assign the result to the variable n_elements_sleep.
  • Print n_elements_sleep to the console to see the result.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# View get_n_elements
get_n_elements

# Create a data.frame method for get_n_elements
___ <- ___




# Call the method on the sleep dataset
n_elements_sleep <- ___

# View the result
n_elements_sleep
Modifier et exécuter le code