CommencerCommencer gratuitement

Creating a Generic Function

You can create your own S3 functions. The first step is to write the generic. This is typically a single line function that calls UseMethod() (docs), passing its name as a string.

The first argument to an S3 generic is usually called x, though this isn't compulsory. It is also good practice to include a ... ("ellipsis", or "dot-dot-dot") argument, in case arguments need to be passed from one method to another.

Overall, the structure of an S3 generic looks like this.

an_s3_generic <- function(x, maybe = "some", other = "arguments", ...) {
  UseMethod("an_s3_generic")
}

Cet exercice fait partie du cours

Object-Oriented Programming with S3 and R6 in R

Afficher le cours

Instructions

  • Define an S3 generic function to calculate the number of elements in an object x.
    • Assign the function to get_n_elements.
    • It should have arguments x and ....
    • The body of the function should call UseMethod().

Exercice interactif pratique

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

# Create get_n_elements
get_n_elements <- ___(___, ___)
{
  ___("___")
}
Modifier et exécuter le code