๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

R S4 Classes

An S4 class is a formal class definition with named slots. Each slot has a fixed type that R checks when an object is built.

Define a class and build an object

setClass defines Wallet with a numeric balance slot and a character owner slot. new builds one Wallet and print shows the prototype values in the slot dump.

setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
w <- new("Wallet")
print(w)

Fill slots at build time

Named values in the new call fill the matching slots. The @ symbol then reads each slot back on its own.

setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
w <- new("Wallet", balance = 40, owner = "Bo")
print(w)
print(w@balance)
print(w@owner)

Write a slot with @

The assignment writes 25 into the balance slot. The print calls show the new value on its own and inside the full slot dump.

setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
w <- new("Wallet")
w@balance <- 25
print(w@balance)
print(w)

List the slot names

slotNames reports the two slot names in definition order. is confirms the object belongs to the Wallet class.

setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
w <- new("Wallet", balance = 15, owner = "Cy")
print(slotNames(w))
print(is(w, "Wallet"))

A wrong slot type fails

The balance slot is numeric and the value here is text. new stops and the error names the slot and the two types.

setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
w <- new("Wallet", balance = "rich")

Example

setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
w <- new("Wallet", balance = 30, owner = "Dee")
w@balance <- w@balance + 12
print(slotNames(w))
print(w@owner)
print(w@balance)
print(w)

Key points

  • setClass defines a class with a slots value that pairs each slot name with a type name.
  • prototype gives the starting value for each slot.
  • new builds an object of the class and fills slots from named values.
  • The @ symbol reads or writes one slot of an S4 object.
  • slotNames lists the slot names of an object.
  • print shows an S4 object as a dump of its slots.
  • A value of the wrong type for a slot stops new with an error.

In this example, the wallet starts with a balance of 30 for Dee and the @ assignment adds 12 to the slot. The prints show the slot names, the owner, the new balance of 42 and the full slot dump.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

How does code read the balance slot of an S4 object w?