Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

R S4 Classes


Share

S4 Classes

In the S3 chapter, you could put anything in an object. If you made a typo in a name, or stored text where a number should be, R did not tell you.

S4 classes are more strict. You describe the class first: which values it has, and the type of each value. These values are called slots.

Use setClass() to describe the class, and new() to create an object. Use the @ sign to get the value of a slot:

Example

setClass("Player", slots = c(name = "character", points = "numeric"))

john <- new("Player", name = "John", points = 45)

john@name
john@points
Try it Yourself »

You can also change the value of a slot:

Example

setClass("Player", slots = c(name = "character", points = "numeric"))

john <- new("Player", name = "John", points = 45)

john@points <- 50

john@points
Try it Yourself »

Type Checking

The points slot must be numeric. If you try to store text in it, R gives an error:

Example

setClass("Player", slots = c(name = "character", points = "numeric"))

john <- new("Player", name = "John", points = "many")

Result:

Error in validObject(.Object) : 
  invalid class “Player” object: invalid object for slot "points" in class "Player": got class "character", should be or extend class "numeric"
Calls: new -> initialize -> initialize -> validObject
Try it Yourself »

Validity

You can also add your own rules with the validity argument. It is a function that returns TRUE if the object is OK, or an error message if it is not:

Example

setClass("Player",
  slots = c(name = "character", points = "numeric"),
  validity = function(object) {
    if (object@points < 0) {
      "points cannot be negative"
    } else {
      TRUE
    }
  }
)

liam <- new("Player", name = "Liam", points = -5)

Result:

Error in validObject(.Object) : 
  invalid class “Player” object: points cannot be negative
Calls: new -> initialize -> initialize -> validObject
Try it Yourself »


Methods

In S4, you create a generic function with setGeneric(), and a method for a class with setMethod():

Example

setClass("Player", slots = c(name = "character", points = "numeric"))

setGeneric("describe", function(obj) standardGeneric("describe"))

setMethod("describe", "Player", function(obj) {
  paste(obj@name, "has", obj@points, "points")
})

john <- new("Player", name = "John", points = 45)
describe(john)
Try it Yourself »

setGeneric() prints the name of the new generic function, [1] "describe".

To change how an object is printed, create a method for the show() generic function. This is the S4 version of print():

Example

setClass("Player", slots = c(name = "character", points = "numeric"))

setMethod("show", "Player", function(object) {
  cat("Player:", object@name, "\n")
  cat("Points:", object@points, "\n")
})

john <- new("Player", name = "John", points = 45)
john
Try it Yourself »

Inheritance

Use the contains argument to create a class that inherits from another class. A Captain is a Player with one extra slot, team:

Example

setClass("Player", slots = c(name = "character", points = "numeric"))

setClass("Captain", contains = "Player", slots = c(team = "character"))

setGeneric("describe", function(obj) standardGeneric("describe"))

setMethod("describe", "Player", function(obj) {
  paste(obj@name, "has", obj@points, "points")
})

jenny <- new("Captain", name = "Jenny", points = 60, team = "Red")

describe(jenny)
jenny@team
Try it Yourself »

There is no describe() method for Captain, so R uses the one for Player.


S3 or S4?

S3 S4
Create a classclass(x) <- "player"setClass()
Create an objectA list, or a constructor functionnew()
Get a valuex$namex@name
Type checkingNoYes
Create a methodprint.player()setMethod()

Use S3 when you want something quick and simple. Use S4 when your objects must follow strict rules.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.