Skip to main content

26  Methods for R classes

A generic from generic() takes methods for classes that R8 did not declare, as well as for R8 types: data frames, matrices, NULL, and the S3 and S4 classes of other packages. A function whose input is ordinary R data, such as a data frame or a sparse matrix, then dispatches on it as it does on R8 values.

26.1 A method for an R class

A string names an S3 class, or an implicit class such as "matrix", "integer", "numeric", or "NULL":

n_rows <- generic("n_rows", params(x))

implement(n_rows, "data.frame") <- function(x) nrow(x)
implement(n_rows, "matrix") <- function(x) nrow(x)
implement(n_rows, "NULL") <- function(x) 0L

n_rows(iris)
[1] 150
n_rows(diag(3))
[1] 3
n_rows(NULL)
[1] 0

A method applies to an object whose class vector contains its class. R reports that vector with .class2(): an object’s class attribute, or, without one, the implicit classes of its shape and storage:

.class2(diag(3))
[1] "matrix"  "array"   "double"  "numeric"
.class2(1:3)
[1] "integer" "numeric"

The class nearer the front of the vector is more specific, so for a tibble, whose classes are c("tbl_df", "tbl", "data.frame"), a method for "tbl" runs before one for "data.frame", and r8next_impl() continues to the next:

implement(n_rows, "tbl") <- function(x) {
  paste("a tibble of", r8next_impl(), "rows")
}

tbl <- structure(list(a = 1:4), class = c("tbl_df", "tbl", "data.frame"), row.names = 1:4)
n_rows(tbl)
[1] "a tibble of 4 rows"

26.2 Several arguments

R classes take part in dispatch on several arguments beside R8 types and any. drop_cols() removes columns of a data frame given by name, by number, or by a selection type:

Selection <- new_struct("Selection", fields = list(cols = vec(type_character())))

drop_cols <- generic("drop_cols", params(x, cols), dispatch = c("x", "cols"))

implement(drop_cols, "data.frame", "character") <- function(x, cols) {
  x[, setdiff(names(x), cols), drop = FALSE]
}

implement(drop_cols, "data.frame", "numeric") <- function(x, cols) {
  x[, -cols, drop = FALSE]
}

implement(drop_cols, "data.frame", Selection) <- function(x, cols) {
  x[, setdiff(names(x), cols$cols), drop = FALSE]
}

df <- data.frame(a = 1, b = 2, c = 3)
names(drop_cols(df, "b"))
[1] "a" "c"
names(drop_cols(df, 1L))
[1] "b" "c"
names(drop_cols(df, Selection(cols = c("a", "c"))))
[1] "b"

"numeric" matches integers and doubles, whose implicit classes both end in "numeric".

26.3 S4 classes

An S4 class is named with its package, by host_class() or by its class object. A method for a superclass applies to its subclasses, which .class2() lists:

n_nonzero <- generic("n_nonzero", params(x))

implement(n_nonzero, host_class("CsparseMatrix", package = "Matrix", system = "s4")) <- function(x) {
  length(x@x)
}

m <- Matrix::sparseMatrix(i = c(1, 3), j = c(2, 3), x = c(4, 5))
class(m)
[1] "dgCMatrix"
attr(,"package")
[1] "Matrix"
n_nonzero(m)
[1] 2

26.4 R values and R8 values

An R8 value matches the methods of its type and its ancestors, and an R object the methods of its classes. A method for "list" does not apply to an R8 value, and an object whose class names an R8 type is not a value of that type.

A dyn() field holds R8 values only. An R object enters one through a conversion to an R8 type that implements the trait, r8convert() with a From impl (Conversion).

A field of type option(host_class(class)) holds an R object of that class, such as a fitted lm model. The object is host-only: R holds it, a document writes the field as null, and the content hash leaves it out. A context field of this type is filled by r8resolve():

Regression <- new_struct(
  "Regression",
  fields = list(
    formula = type_character(),
    model = field(option(host_class("lm")), context = TRUE)
  )
)

regression <- r8resolve(
  Regression(formula = "dist ~ speed"),
  context = list(model = lm(dist ~ speed, data = cars))
)
class(regression$model)
[1] "lm"
cat(r8to_json(regression))
{"$type":"demo::Regression","$types":{"demo::Regression":1},"$declarations":{"demo::Regression":"sha256:17ff7ca21cb680b85b30a1713a3097b4902a7879f8a22af9b016dd4e4d9befac"},"formula":"dist ~ speed","model":null}

26.5 Existing methods

A trait method named after an existing S3 generic, such as summary, is a method of that generic (Traits). For a class that already has a method of it, such as summary.data.frame in base R, the impl takes that method and leaves it out; an impl that supplies one is an error, since registering it would replace the method for every caller:

Describe <- new_trait(
  "Describe",
  methods = list(
    summary = trait_method(params(object, "...")),
    kind = trait_method(params(x))
  )
)

impl(Describe, "data.frame", methods = list(kind = function(x) "a data frame"))

Describe@kind(iris)
[1] "a data frame"
impl(Describe, "data.frame", methods = list(
  summary = function(object, ...) "mine",
  kind = function(x) "a data frame"
))
Error:
! `data.frame` has a method of `summary` in 'base'; the impl of `demo::Describe` for `data.frame` omits `summary` and takes that method, since registering another would replace it for every caller [host_method_exists].

26.6 Who declares a method

A method for an R class is declared by the package of the generic or trait, or by the package that defines the class. host_class("Frame", package = "mypkg") names a class of the declaring package, which may implement another package’s trait for it.

© 2026 E.D. Gennatas