Skip to content
S3 Classes
step 1/5

Reading — step 1 of 5

Learn

~1 min readObjects and Stats

R has multiple object systems. S3 is the simplest and most common — used by summary(), print(), etc.

An S3 object is just a list (or vector) with a class attribute:

person <- function(name, age) {
    obj <- list(name = name, age = age)
    class(obj) <- "person"
    obj
}

ada <- person("Ada", 36)
class(ada)        # "person"

Generic functions dispatch on the first argument's class:

# Define a generic (or use built-in like print, summary)
print.person <- function(x, ...) {
    cat(x$name, "is", x$age, "years old\n")
}

print(ada)        # "Ada is 36 years old"

When you call print(ada), R looks for print.person first, then falls back to print.default.

Inheritance — class can be a vector:

student <- function(name, age, school) {
    obj <- person(name, age)
    obj$school <- school
    class(obj) <- c("student", "person")   # student inherits from person
    obj
}

Now print(student_obj) looks for print.student first, then print.person, then print.default.

Built-in generics to override:

  • print, summary, format
  • plot (visualization)
  • Arithmetic: +, -, * (via Ops group)
  • [, [[, $ (subsetting)

S3 vs S4 vs R5/R6:

  • S3: light, conventions-based, what most CRAN packages use
  • S4: formal, slot-based, used in Bioconductor
  • R6: reference semantics, OO programmers feel at home

For most analysis code, S3 is the right tool.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…