S3 Methods

A minimal example of creating and calling S3 methods

Author
Published

August 3, 2023

Below is a sort of minimal example of S3 methods, including how to define them for various classes.

Define a Generic

combine <- function(x) {
    UseMethod("combine")
} 

Define and Instantiate Some Classes

# constructor for a new instance of 'my_class'
new_my_class <- function(x, y) {
    stopifnot(is.character(x) & is.character(y))

    structure(
        list(x = x, y = y),
        class = "my_class"
    )
} 

# constructor for a new instance of 'your_class'
new_your_class <- function(x, y) {
    stopifnot(is.numeric(x) & is.numeric(y))

    structure(
        list(x = x, y = y),
        class = "your_class"
    )
}

a <- new_my_class("aaa", "bbb")
b <- new_your_class(1, 2)

Define Combine Methods for Each Class

combine.my_class <- function(x) {
    paste0(
        vctrs::field(x, "x"),
        vctrs::field(x, "y")
    )
} 

combine.your_class <- function(x) {
    a <- vctrs::field(x, "x")
    b <- vctrs::field(x, "y")

    a + b
}

Call Methods

combine(a) 
[1] "aaabbb"
combine(b) 
[1] 3

huzzah!