Guru's Verification engine ensures consistency, confidence, and trust in the knowledge your organization shares. Learn more.

R | Creating generic functions (OO Programming)

It is possible to perform object-oriented programming in R, via generic functions:

  • In a generic function-based OO paradigm, instead of having methods that are grouped via classes, methods are grouped via generic functions.

  • Each generic function can have multiple methods associated with it, each one corresponding to a class.

  • When the generic function is called, the appropriate method will be determined based on the class of the first argument to the function. This allows the same function call to behave differently for each class.

  • This system of picking out different methods to use depending on the class the generic function is called on is called "dispatching".

  • See [1] for more info on the internal mechanics behind the generic function system in this card.

Example:

This is a toy example to demonstrate the process of creating a generic function and its methods.

# define the generic; it's just a function with a single call to `UseMethod`plus2 <- function(x) {  UseMethod("plus2")}# figure out class names for a few example objectsclass(3L) # "integer"class(3.5) # "numeric"class("3") # "character"# define the method for class "integer"; note the dot separator in the function nameplus2.integer <- function(x) {  x + 2}plus2(5L) # 7plus2(5) # wouldn't work because "numeric" method is not defined yet# define method for "numeric"plus2.numeric <- function(x) {  x + 2}plus2(5) # 7.0# define method for "character"plus2.character <- function(x) {  as.numeric(x) + 2}plus2("5") # 7# define default method when no method was found for argument classplus2.default <- function(x) {  print("why would you do this")}plus2(list()) # why would you do this

Note: R actually has multiple OO paradigms; the one described in this card is called S3, and is the most commonly used one. There are 2 others (S4 and R6) that have their own use cases. For more info, refer to [2].

Resources:

You must have Author or Collection Owner permission to create Guru Cards. Contact your team's Guru admins to use this template.