[R] S4 method dispatch with inheritance

Michael Hahsler michael at hahsler.net
Mon Jul 20 15:57:28 CEST 2009


Hi,

I'm trying to create a new S4 class (myMatrix) which for now just 
extends dgCMatrix (from package Matrix). Then I want to use "[" which is 
defined in Matrix.

Out of the box with "[" (defined in Matrix) I lose the class information 
and the result is an object of class dgCMatrix. If I specify a 
"["-method for myMatrix, it is not used because a signature from Matrix 
seems to fit better. However, the most important part of the signature 
is the class of x (all else have ANY). Is there a way to specify a 
single "["-method do make it work for myClass?

Thanks,
Michael


 > library("Matrix")
Loading required package: lattice

Attaching package: 'Matrix'


	The following object(s) are masked from package:stats :

	 xtabs


	The following object(s) are masked from package:base :

	 rcond

 >
 > setClass("myMatrix",
+     contains="dgCMatrix"
+ )
[1] "myMatrix"
 >
 > my <- as(as(rbind(1:10,1:10,1:10), "dgCMatrix"), "myMatrix")
 >
 > ## here I lose the class "myMatrix"
 > class(my[1:2,])
[1] "dgCMatrix"
attr(,"package")
[1] "Matrix"
 >
 > ## make sure [ keeps the class
 > setMethod("[", signature(x = "myMatrix", i = "ANY", j = "ANY",
+             drop = "ANY"),
+         function(x, i, j, ..., drop) {
+             x<- as(x, "dgCMatrix")[i, j, ..., drop]
+             as(x, "myMatrix")
+         })
[1] "["
 >
 > ## and now it does not use the method defined above.
 > class(my[1:2,])
Note: Method with signature "Matrix#index#missing#missing" chosen for 
function "[",
  target signature "myMatrix#integer#missing#missing".
  "myMatrix#ANY#ANY#ANY" would also be valid
Note: Method with signature "sparseMatrix#index#missing#logical" chosen 
for function "[",
  target signature "myMatrix#integer#missing#logical".
  "myMatrix#ANY#ANY#ANY" would also be valid
[1] "dgCMatrix"
attr(,"package")
[1] "Matrix"


 > sessionInfo()
R version 2.9.1 (2009-06-26)
i486-pc-linux-gnu

locale:
LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=C;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] Matrix_0.999375-29 lattice_0.17-25

loaded via a namespace (and not attached):
[1] grid_2.9.1

-- 
   Michael Hahsler
   email: michael at hahsler.net
   web: http://michael.hahsler.net




More information about the R-help mailing list