LoslegenKostenlos loslegen

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")
}

Diese Übung ist Teil des Kurses

Object-Oriented Programming with S3 and R6 in R

Kurs anzeigen

Anleitung zur Übung

  • 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().

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

# Create get_n_elements
get_n_elements <- ___(___, ___)
{
  ___("___")
}
Code bearbeiten und ausführen