Skip to content
Prev 179860 / 398506 Next

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

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