knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

Multiple dispatch with S3

The goal of this repo is to show a simple way to obtain multiple dispatch with S3 classes and methods in R.

Example

This is a basic example which shows you how to make a function that dispatch on two arguments:

ff <- function(x, y) {
  UseMethod("ff", x)
}

ff.character <- function(x, y){
  UseMethod("ff.character", y)
}

ff.character.numeric <- function(x, y) {
  sprintf("Character '%s' + numeric %s", x, y)
}

ff.character.integer <- function(x, y) {
  sprintf("Character '%s' + integer %s", x, y)
}

ff.character.character <- function(x, y) {
  sprintf("Character '%s' + character '%s'", x, y)
}

ff.numeric <- function(x, y){
  UseMethod("ff.numeric", y)
}

ff.numeric.numeric <- function(x, y) {
  sprintf("Numeric '%s' + numeric %s", x, y)
}

ff.numeric.character <- function(x, y) {
  sprintf("Numeric '%s' + character %s", x, y)
}
# library(s3multimethods)

ff(1, 2)
ff("a", 1)
ff(1, "a")
ff("a", 1L)
ff("a", 'b')


vh-d/s3multimethods documentation built on May 16, 2019, 4:10 a.m.