<- function(x) {
combine UseMethod("combine")
}
S3 Methods
A minimal example of creating and calling S3 methods
Below is a sort of minimal example of S3 methods, including how to define them for various classes.
Define a Generic
Define and Instantiate Some Classes
# constructor for a new instance of 'my_class'
<- function(x, y) {
new_my_class stopifnot(is.character(x) & is.character(y))
structure(
list(x = x, y = y),
class = "my_class"
)
}
# constructor for a new instance of 'your_class'
<- function(x, y) {
new_your_class stopifnot(is.numeric(x) & is.numeric(y))
structure(
list(x = x, y = y),
class = "your_class"
)
}
<- new_my_class("aaa", "bbb")
a <- new_your_class(1, 2) b
Define Combine Methods for Each Class
<- function(x) {
combine.my_class paste0(
::field(x, "x"),
vctrs::field(x, "y")
vctrs
)
}
<- function(x) {
combine.your_class <- vctrs::field(x, "x")
a <- vctrs::field(x, "y")
b
+ b
a }
Call Methods
combine(a)
[1] "aaabbb"
combine(b)
[1] 3
huzzah!