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.