[Rd] "[" operator and indexing ambiguity

Seth Falcon sfalcon at fhcrc.org
Tue Jan 30 23:07:59 CET 2007


Oleg Sklyar <osklyar at ebi.ac.uk> writes:
> As Tony correctly writes one can generally use nargs() to get the number 
> of arguments, and this works for "["(x,i,j,...,drop) method as well. The 
> problem I had with the EBImage where I could not distinguish between 
> x[index] and x[index,,] is that somehow particularly for the "[" method 
> and particularly for 3 dimensions nargs in both cases gave me the same 
> number of arguments! This behavior was not present when the number of 
> dimension was 2 or 4, i.e. for x[index,] or x[index,,,] -- these could 
> be easily distinguished from x[index]. Anyway, maybe R changed since and 
> I just did not notice that :)

I too find R's behavior surprising when trying to define "[" methods
for S4 classes.  Here's an example where callNextMethod doesn't seem
to work for subclasses of array:

    setClass("MyArray", representation(name="character"),
             contains="array")
    
    setMethod("[", signature(x="MyArray"),
              function(x, i, j, ..., drop=FALSE) {
                  cat("num args: ", nargs(), "\n")
                  callNextMethod()
              })

    v <- array(1:10000, dim=c(10, 10, 10))
    mya <- new("MyArray", name="sam", v)

      > dim(mya)
      [1] 10 10 10

    # this works:
      > mya[3]
      num args:  2 
      [1] 3

    # but this does not:

      > mya[3, , ]
      num args:  4 
      Error in x[i = i, j = , , ...] : incorrect number of dimensions
      Error in callNextMethod() : error in evaluating a 'primitive' next method


+ seth



More information about the R-devel mailing list