Skip to main content

24  Methods of base generics

implement() declares methods of the generics of base R and of other packages, as it does for a generic from generic(). The generic is written as its name, and the method’s arguments begin with the generic’s. A generic that checks or returns something before it dispatches, such as as.data.frame(), sort(), or dplyr::filter(), takes methods in the same way.

24.1 S3 generics

A method of an S3 generic, such as summary(), toString(), or predict(), is an S3 method for the type’s qualified class, demo::Resampler:

implement(summary, Resampler) <- function(object, ...) {
  sprintf("%s, %d resamples", r8variant(object), object$n_resamples)
}

summary(cv)
[1] "KFold, 10 resamples"

24.2 Generics of standard traits

Some generics of base R are methods of R8’s standard traits, which R8 uses for every value. implement() with one of them declares an impl of the trait:

Generic Standard trait Used by
format Display format(), and print() for a type without a print method
print Print print() (Printing)
str Debug str()
dim Shape dim(), nrow(), ncol()
r8partial_cmp PartialOrd <, <=, >, >=

dim() of a Resamples value gives its cases and resamples:

implement(dim, Resamples) <- function(x) {
  c(x$n_cases, length(x$train))
}

draws <- resample(cv, n_cases = 20L)
dim(draws)
[1] 20 10
ncol(draws)
[1] 10

r8partial_cmp(x, y) returns -1L, 0L, or 1L as x sorts before, with, or after y, or NA when the two are not ordered, from which the four comparison operators follow; they return FALSE for values that are not ordered:

implement(r8partial_cmp, Resamples) <- function(x, y) {
  sign(length(x$train) - length(y$train))
}

leave_one_out <- resample(Resampler@KFold(n_resamples = 20L), n_cases = 20L)
draws < leave_one_out
[1] TRUE

24.3 Generics R8 reserves

R8 reads, changes, and compares values through $, [[, @, as.list, their replacement forms, ==, and !=, so that every value is validated and its equality agrees with its hash. implement() with one of these, or with an operator, is an error that names the reason:

implement(`$`, Resampler) <- function(x, name) NULL
Error:
! implement() does not declare this method: R8 reads the fields of a value through it.
implement(`<`, Resampler) <- function(e1, e2) TRUE
Error:
! implement() does not declare this method: comparisons use the PartialOrd trait; implement(r8partial_cmp, Resampler) <- function(x, y) ... defines the order.
© 2026 E.D. Gennatas