Too Much Class

Object-Oriented Programming with S3 and R6 in R

Richie Cotton

Data Evangelist at DataCamp

x <- c(1, 3, 6, 10, 15)

class(x) <- c( "triangular_numbers", "natural_numbers", "numeric" )
Object-Oriented Programming with S3 and R6 in R
is.numeric(x)
TRUE
is.triangular_numbers(x)
Error: could not find function "is.triangular_numbers"
Object-Oriented Programming with S3 and R6 in R
inherits(x, "triangular_numbers")
TRUE
inherits(x, "natural_numbers")
TRUE
inherits(x, "numeric")
TRUE
Object-Oriented Programming with S3 and R6 in R
what_am_i <- function(x, ...) {
  UseMethod("what_am_i")
}
Object-Oriented Programming with S3 and R6 in R
what_am_i.triangular_numbers <- function(x, ...) {
  message("I'm triangular numbers")
  NextMethod("what_am_i")
}
what_am_i.natural_numbers <- function(x, ...) {
  message("I'm natural numbers")
  NextMethod("what_am_i")
}
what_am_i.numeric <- function(x, ...) {
  message("I'm numeric")
}
Object-Oriented Programming with S3 and R6 in R
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.017.png

Object-Oriented Programming with S3 and R6 in R
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.018.png

Object-Oriented Programming with S3 and R6 in R
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.019.png

Object-Oriented Programming with S3 and R6 in R
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.020.png

Object-Oriented Programming with S3 and R6 in R

Summary

  • Multiple classes are allowed
  • Use inherits() to test for arbitrary classes
  • Use NextMethod() to chain method calls
Object-Oriented Programming with S3 and R6 in R

Let's practice!

Object-Oriented Programming with S3 and R6 in R

Preparing Video For Download...