Object Oriented Programming (OOP) in R

2026-04-02

Outline

  • What is Object Oriented Programming?

  • OOP models in R

Object Oriented Programming

Idea of object oriented programming is that the user can define abstract objects (classes, e.g. a linear model object) that contains named ‘pieces’ (fields, e.g. the data, the parameter estimates, residuals, …) and associated ‘methods’ (functions, e.g. predict)

Polymorphism allows us to ‘over-write’ existing methods and implement specialized functionality that way

Methods have the form class.methodname - at the core of R and lazy evaluation: e.g. summary, print, …

OOP models in R

In chronological order:

  • base

  • S3

  • S4

  • R6

Check any object in R for its class/type with typeof or sloop::otype

OOP models used in R

typeof(1:10)
[1] "integer"
sloop::otype(1:10)
[1] "base"

ggplot2 is a based on grid and uses S3:

gg <- diamonds |> ggplot(aes(x = carat, y = price)) + geom_point()
sloop::otype(gg)
[1] "S3"

shiny uses R6

lme4, stats4 use S4

S3

make an S3 object: give an object a class:

data <- matrix()
class(data) <- "simMatrix"

sloop::otype(data)
[1] "S3"
data <- structure(matrix(), class = "simMatrix")

sloop::otype(data)
[1] "S3"

Constructor and validator

Good practice, but not required: constructor new_classname

new_simMatrix <- function(size = NULL) {
  if (is.null(size)) size <- 0
  structure(matrix(numeric(length= size*size), nrow=size, ncol=size), class = "simMatrix")
}

Validator: check that object is ‘right’

validate_simMatrix <- function(x) {
  dims <- dim(x) 
  stopifnot(dims[1]==dims[2]) # matrix is supposed to be square
  values <- unclass(x)
  stopifnot(is.numeric(values)) 
  x
}