Skip to content

"Overloading" some non-dispatched S3 methods for new classes

2 messages · Carlos J. Gil Bellosta, Gavin Simpson

#
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?

Best regards,

Carlos J. Gil Bellosta
http://www.datanalytics.com
#
On Sat, 2009-05-09 at 20:50 +0200, Carlos J. Gil Bellosta wrote:
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
    dim(object)[1]
    ## but your code would go in here
}
ncol(mat)

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

http://cran.r-project.org/doc/manuals/R-exts.html#Adding-new-generics

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

HTH

G