[R] 'methods' and "[<-"

John Chambers jmc at research.bell-labs.com
Mon Mar 3 15:22:02 CET 2003

Laurent Gautier wrote:
> Dear List,
> I am trying to override the replace method "[<-" for
> objects of class "matrix"... with little success...
> Would anyone know where I am wrong ?

Not wrong at all.  The problem is that "matrix" (and "array") are
implicit classes in R--there is no explicit class attribute, just as
there is not for the basic vector types,  "character", etc.

The effect is that methods for these data types are fixed for primitive
functions.  The internal code that dispatches methods will jump out
right away for these objects.  The argument in favor of not allowing
redefinition is partly efficiency and partly (perhaps the more important
part) that users should really be able to take the definition of
subsetting, arithmetic, and other basic operations as known and fixed
for the basic data types.

The "matrix" and "array" data types are slightly less basic, but in R
they are special and sort of built in.

Anyway,this is either a feature (in which case we'll modify the
setMethod code to throw an error) or something that might be changed.

It's no consolation, but I don't believe you can define S3-style methods
for the same combination of function and data type either.

> > library(methods)
> > setReplaceMethod("[", "matrix", function(x, i, j, ..., value) {cat("I'm here.\n")})
> [1] "[<-"
> > m <- new("matrix", 0, 5, 2)
> > m[1,1] <- 2
> >
> # ..did not use my new method it seems
> Thanks,
> L/
> PS: I am using R-1.6.2
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help

John M. Chambers                  jmc at bell-labs.com
Bell Labs, Lucent Technologies    office: (908)582-2681
700 Mountain Avenue, Room 2C-282  fax:    (908)582-3340
Murray Hill, NJ  07974            web: http://www.cs.bell-labs.com/~jmc

More information about the R-help mailing list