Skip to content

S3

S3 Introduction

  • S3 is the simplest and most informal OOP system in R.
  • It does not have a formal definition.
  • It relies on generic functions to dispatch methods based on the class of the object.

Generic Function

  • A generic function is a collection of various functions/methods that are created for different data types.
  • It calls the appropriate function depending on the type of object passed as an argument.
  • Examples: plot(), print(), anova(), and summary()
  • methods(summary)
# Create a generic function
clean_data <- function(x) {
  UseMethod("clean_data")
}

# for numeric class
clean_data.numeric <- function(x) {
  return(x-1)
}

# character class
clean_data.character <- function(x) {
  return(nchar(x))
}

# for list class
clean_data.list <- function(x) {
  return(purrr::reduce(x, paste0))
}

# for self-defined class
clean_data.flu <- function(x){
  temp <- dplyr::mutate(x, date_clean = as.Date(date, format = "%Y%m%d"))
  return(temp)
}

# Test the function
clean_data(1)
clean_data("test")
clean_data(list("1", 2, "a", "b"))

flu_raw <- data.frame(
  id = c("001", "002", "003"),
  date = c("20250101", "20250102", "20250103")
)

class(flu_raw) <- c("flu", class(flu_raw))

clean_data(flu_raw)