[R] "Overloading" some non-dispatched S3 methods for new classes

Gavin Simpson gavin.simpson at ucl.ac.uk
Sun May 10 12:07:00 CEST 2009

On Sat, 2009-05-09 at 20:50 +0200, Carlos J. Gil Bellosta wrote:
> Hello,
> I am building a package that creates a new kind of object not unlike a
> dataframe. However, it is not an extension of a dataframe, as the data
> themselves reside elsewhere. It only contains "metadata".
> I would like to be able to retrieve data from my objects such as the
> number of rows, the number of columns, the colnames, etc.
> I --quite naively-- thought that ncol, nrow, colnames, etc. would be
> dispatched, so I would only need to create a, say, ncol.myclassname
> function so as to be able to invoke "ncol" directly and transparently.
> However, it is not the case. The only alternative I can think about is
> to create decorated versions of ncol, nrow, etc. to avoid naming
> conflicts. But I would still prefer my package users to be able to use
> the undecorated function names.
> Do I have a chance?

Yes, if I understand you correctly. nrow, ncol are not S3 generics. You
can make them generic in your package and assign to the default method
the function definition in the R base package. For example:

ncol <- function(object, ...) UseMethod("ncol")
ncol.default <- base::ncol

mat <- matrix(0, ncol = 10, nrow = 5)
class(mat) <- "myclass"

ncol.myclass <- function(object, ...) {
    ## as example, perversely, swap rows and cols
    ## but your code would go in here

This is covered in the Writing R Extensions manual, section 7.1


Also, this is probably not the right list for such questions. R-Devel
would have been more appropriate.



> Best regards,
> Carlos J. Gil Bellosta
> http://www.datanalytics.com
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk

More information about the R-help mailing list