R S3 Classes
S3 Classes
S3 is the simplest way to create your own classes in R.
An S3 object is usually a list that has a class name. To create one, make a list, and use class() to give it a class:
Example
player <- list(name = "Liam", points = 30)
class(player) <- "player"
player$name
class(player)
Try it Yourself »
The list has two values, name and points, and you get them with the $ sign, like in a data frame.
Constructor Function
If you need many objects of the same class, write a function that creates them. This is called a constructor:
Example
new_player <- function(name, points) {
p <- list(name = name, points = points)
class(p) <- "player"
p
}
john <- new_player("John", 45)
john$name
john$points
Try it Yourself »
Now every player is created in the same way, and you cannot forget to set the class.
Methods
A method is a version of a generic function that is made for one class.
To make your own version of print() for the player class, write a function called print.player(): the name of the generic function, a period, and the name of the class:
Example
new_player <- function(name, points) {
p <- list(name = name, points = points)
class(p) <- "player"
p
}
print.player <- function(x, ...) {
cat("Player:", x$name, "\n")
cat("Points:", x$points, "\n")
}
john <- new_player("John", 45)
john
Try it Yourself »
When R prints john, it sees that the class is player, so it uses print.player() instead of the normal print().
Create Your Own Generic Function
You can also create your own generic functions. Use UseMethod() to tell R to look for a method that fits the class of the object:
Example
new_player <- function(name, points) {
p <- list(name = name, points = points)
class(p) <- "player"
p
}
describe <- function(obj) {
UseMethod("describe")
}
describe.player <- function(obj) {
paste(obj$name, "has", obj$points, "points")
}
describe.default <- function(obj) {
"Unknown object"
}
john <- new_player("John", 45)
describe(john)
describe(10)
Try it Yourself »
describe(john)usesdescribe.player(), becausejohnhas the classplayer.describe(10)usesdescribe.default(), because there is no method for numbers. Thedefaultmethod is used when no other method fits.
Inheritance
An object can have more than one class. R tries the classes in order, and uses the first method it finds.
Here, jenny is both a captain and a player. She gets her own describe() method, but she is still a player, with a name and points:
Example
new_player <- function(name, points) {
p <- list(name = name, points = points)
class(p) <- "player"
p
}
describe <- function(obj) {
UseMethod("describe")
}
describe.player <- function(obj) {
paste(obj$name, "has", obj$points, "points")
}
describe.captain <- function(obj) {
paste(obj$name, "is the team captain")
}
john <- new_player("John", 45)
jenny <- new_player("Jenny", 60)
class(jenny) <- c("captain", "player")
describe(john)
describe(jenny)
jenny$points
Try it Yourself »
This is called inheritance: the captain class inherits from the player class.