From chalabi at phys.ethz.ch  Wed Mar 18 14:47:03 2009
From: chalabi at phys.ethz.ch (Yohan Chalabi)
Date: Wed, 18 Mar 2009 14:47:03 +0100
Subject: [Rd] Why S4 methods of S3 'base' generics are not used in 'base'
 functions ?
Message-ID: <20090318144703.54e02ec1@mimi>

Dear list,

It seems that S4 methods defined for an S3 'base' generic
are not used in 'base' functions.

This can be problematic when 'base' functions start with 
something like 'as.matrix'.


### START R code

setClass("classA", contains = "matrix",
         representation(realData = "numeric"))

setMethod("as.matrix", "classA", function(x) callGeneric(x at realData))

x <- new("classA", diag(1:4), realData = 1:4)

as.matrix(x)

## # as intended
##      [,1]
## [1,]    1
## [2,]    2
## [3,]    3
## [4,]    4

# but as.matrix in 'base' functions dispatches to the default S3
# method rather than to the S4 method defined above.
scale(x)
scale(as.matrix(x))

# Note that S4 methods are well dispatched for functions which are
# not S3 generics.
setMethod("dimnames", "classA",
          function(x) list(NULL, as.character(x at realData)))
dimnames(x)

solve(x) # here row names are properly assigned thanks to the 'dimnames'
         # method defined above.

### END R code

What is your recommended solution to make S4 methods of S3 'base'
generics work in 'base' functions?

A solution could be to overwrite 'as.matrix' in '.Load' and force it to
use the S4 method with S4 objects. But doing so looks to me rather
dangerous because it would lead to conflicts between packages.

Another solution could be to define S3 methods. But, as it has been
already explained on the list, it is a design error.

Thanks in advance for any suggestion!

Best regards,
Yohan


-- 
PhD student
Swiss Federal Institute of Technology
Zurich

www.ethz.ch



[Rd] Why S4 methods of S3 'base' generics are not used in 'base' functions ?
Yohan Chalabi