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")
}
This exercise is part of the course
Object-Oriented Programming with S3 and R6 in R
Exercise instructions
- Define an S3 generic function to calculate the number of elements in an object
x
.- Assign the
function
toget_n_elements
. - It should have arguments
x
and...
. - The body of the function should call
UseMethod()
.
- Assign the
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create get_n_elements
get_n_elements <- ___(___, ___)
{
___("___")
}