Search code examples
roperator-overloadingsubscriptsubscript-operator

Overloading subscript operator "["


I am trying to overload the subscript operator ("[") for a custom class I've created. I am trying to figure out how to deal with the following issues.

  • How can you figure out if the operator is on lhs or rhs ? i.e. a[x] = foo vs foo = a[x]
  • When subscripting the entire dimension like foo = a[,x] how can I identify the first parameter ?
  • When using a[seq(x,y)] it seems to be expanding the entire sequence. Is there an easy way to get the first, step and last values without expanding ?

EDIT: My first point has received multiple answers. In the process I've figured out the answer to the second one. You can use the "missing" function to figure out which parameters are present.

Here is a sample code:

setMethod("[", signature(x="myClass"),
          function(x, i, j, k, l) {
              if (missing(i)) { i = 0 }
              if (missing(j)) { j = 0 }
              if (missing(k)) { k = 0 }
              if (missing(l)) { l = 0 }
          })

I have accepted an answer to this question as point number 3 is of least priority to me.


Solution

  • For the first bullet point there are two functions to overload:

    1. [
    2. [<-

    The first function returns the value and the second sets the value. See the documentation for Extract.data.frame{base}