rgenericsr-s4r-s3

How to overload S4 slot selector `@` to be a generic function


I am trying to turn the @ operator in R into a generic function for the S3 system.

Based on the chapter in Writing R extensions: adding new generic I tried implementing the generic for @ like so:

`@` <- function(object, name) UseMethod("@")
`@.default` <- function(object, name) base::`@`(object, name)

However this doesn't seem to work as it breaks the @ for the S4 methods. I am using Matrix package as an example of S4 instance:

Matrix::Matrix(1:4, nrow=2, ncol=2)@Dim

Error in @.default(Matrix::Matrix(1:4, nrow = 2, ncol = 2), Dim) : no slot of name "name" for this object of class "dgeMatrix"

How to implement a generic @ so it correctly dispatches in the case of S4 classes?


EDIT

Also interested in opinions about why it might not be a good idea?


Solution

  • In R 4.3.0 and newer, the @ operator will be internally S3 generic, as documented in the latest NEWS:

    The @ operator is now an S3 generic. Based on contributions by Tomasz Kalinowski in PR#18482.

    You can test on R-devel if you don't want to wait for the release of R 4.3.0 on April 21:

    .S3method("@", "zzz", function(object, name) "OK")
    structure(0, class = "zzz")@whatever
    ## [1] "OK"