R S3 Basics
An S3 object is a plain value with a class name attached to it. A generic function reads the class name and picks the method that matches it.
Attach a class name
The class assignment attaches the name wallet to the list. class reads the attached name back.
w <- list(balance = 50)
class(w) <- "wallet"
print(class(w))
print(w$balance)A generic picks a method
describe calls UseMethod and R picks describe.wallet for the wallet. A plain number falls through to describe.default.
describe <- function(x, ...) {
UseMethod("describe")
}
describe.wallet <- function(x, ...) {
cat("A wallet holding", x$balance, "coins\n")
}
describe.default <- function(x, ...) {
cat("A plain value\n")
}
w <- list(balance = 50)
class(w) <- "wallet"
describe(w)
describe(42)Build a classed value in one call
structure builds the list and attaches the wallet class in one call. describe then picks the wallet method for the new value.
describe <- function(x, ...) {
UseMethod("describe")
}
describe.wallet <- function(x, ...) {
cat("A wallet holding", x$balance, "coins\n")
}
describe.default <- function(x, ...) {
cat("A plain value\n")
}
w2 <- structure(list(balance = 5), class = "wallet")
print(class(w2))
describe(w2)No method and no default
judge has a wallet method but no default method. A value with class blob matches no method, so the call stops with an error.
judge <- function(x, ...) {
UseMethod("judge")
}
judge.wallet <- function(x, ...) {
cat("wallet\n")
}
blob <- list(size = 1)
class(blob) <- "blob"
judge(blob)Example
describe <- function(x, ...) {
UseMethod("describe")
}
describe.wallet <- function(x, ...) {
cat("A wallet holding", x$balance, "coins\n")
}
describe.default <- function(x, ...) {
cat("A plain value\n")
}
w <- structure(list(balance = 20), class = "wallet")
print(class(w))
describe(w)
describe("hello")Key points
- A class name can be attached to a value with a class assignment.
- structure builds a value and attaches its class name in one call.
- A generic is a function whose block calls UseMethod with the name of the generic.
- A method is a function with a name made from the generic name, a dot, and the class name.
- describe.wallet is the method that describe picks for a value with class wallet.
- A default method catches a value when no method matches its class.
- class reads the attached name back in the same way it reports a plain type.
In this example structure builds a wallet with a balance of 20 and attaches its class in one call. describe picks the wallet method for that value. The text value has no matching method, so the default method answers instead.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
A generic has no default method and a value matches no method. What happens?