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:
- The name of the method must be of the form
generic.class. - 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
}
This exercise is part of the course
Object-Oriented Programming with S3 and R6 in R
Exercise 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.frameobject.- 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
xand.... - The body of the function should be a single line, returning the number of elements (rows times columns) in a data frame.
- The name of the function should be the name of the generic, then a
- Call
get_n_elementson thesleep(docs) dataset and assign the result to the variablen_elements_sleep. - Print
n_elements_sleepto the console to see the result.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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