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

Exercise

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

Instructions

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