R S4 setMethod '[' distinguish missing argument?

Sorry for the headline, but not sure how else to formulate this question.

If I want to create setMethod in a class, how can I distinguish between the similar cases of mat[i,] and mat[i] ?

I know for the first that I can use:

 setMethod("[", signature(x = "foo", j = "missing", drop = "missing"), function(x,i,j,drop) return(myFunc(x,i)) ) 

How can I set a method to highlight the latter, where I would not want to select rows, but elements, as in the base matrix class?

Looking at the documentation ?[ , I was expecting something like the following to work:

 setMethod("[", signature(x = "foo", i = "numeric"), function(x,i,j,drop) return(myFunc(x,i)) ) 

but it conflicts with any previously defined methods that lack j and drop .

Idea is the same as

 mat <- matrix(seq(9), 3, 3) mat[c(1,3),] 1 4 7 3 6 9 mat[c(1,3)] [1] 1 3 
+6
source share
1 answer

There are many examples in the Matrix package. It uses S4 and implements new classes and methods for matrices. As far as I know, there is no way to declare what you are looking for in a signature. Instead, you need to use the nargs function to distinguish between mat[1] and mat[1, ] . Here is an example of how to do this:

 setClass("foo", slot = c(mat = "matrix")) setMethod( "[", signature(x = "foo", i = "missing", j = "missing", drop = "missing"), function(x, i, j, drop = FALSE) { x } ) setMethod( "[", signature(x = "foo", i = "numeric", j = "missing", drop = "missing"), function(x, i, j, ..., drop) { if (nargs() == 3) x@mat [i, ] else x@mat [i] } ) setMethod( "[", signature(x = "foo", i = "numeric", j = "numeric", drop = "missing"), function(x, i, j, ..., drop) { x@mat [i, j] } ) mat <- new("foo", mat = matrix(seq(9), 3, 3)) mat[] mat[2:5] mat[1:2, ] mat[1:2, 2] 

However, it would be easier if you directly extended the base class 'matrix' (or 'Matrix' from the Matrix package) and do something like

 setClass("Matrix", contains = "matrix") 

since you get these methods for free. Note, for example, that in the above implementation, you still have to take care of the drop argument. And basically you have to redefine what is already there.

+3
source

All Articles