R S4 Show Method
A show method controls how an S4 object prints. print() runs the show method in place of the plain slot dump.
A show method takes over print
The first print shows the plain slot dump. After the show method is written, the same print shows one short line.
setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
w <- new("Wallet", balance = 10, owner = "Ana")
print(w)
setMethod("show", "Wallet", function(object) cat(object@owner, "wallet:", object@balance, "coins\n"))
print(w)getSlots lists the slot classes
getSlots() takes the class name. The result pairs each slot name with the class of that slot.
setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
print(getSlots("Wallet"))The show method reads each object
Two Wallet objects hold different values. Each print shows the values stored in that object.
setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
setMethod("show", "Wallet", function(object) cat(object@owner, "wallet:", object@balance, "coins\n"))
w <- new("Wallet", balance = 25, owner = "Bo")
print(w)
w2 <- new("Wallet", balance = 8, owner = "Cy")
print(w2)getSlots includes inherited slots
Savings builds on Wallet, so its slot list has three entries. The rate slot comes first, ahead of the two inherited slots.
setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
setClass("Savings", contains = "Wallet", slots = c(rate = "numeric"), prototype = list(rate = 2))
print(getSlots("Savings"))Example
setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
setMethod("show", "Wallet", function(object) cat(object@owner, "wallet:", object@balance, "coins\n"))
w <- new("Wallet", balance = 42, owner = "Dee")
print(w)
print(getSlots("Wallet"))Key points
- setMethod() with the name "show" writes the show method for a class.
- The show method takes the object as its argument.
- The method reads the slots with @ and prints them with cat().
- print() runs the show method without any extra call.
- getSlots() returns a named character vector that pairs each slot name with its class.
- For a subclass, getSlots() lists the inherited slots as well as its own slots.
In this example, the show method prints Dee with a balance of 42 in one short line. getSlots() then lists balance as numeric and owner as character.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does getSlots("Wallet") return?