Question

I would like to write a [. method for my ReferenceClass. So far, I have something like this:

DT <- data.table(Index=1:5)

MySeries <- setRefClass("MySeries", fields = list(data="data.table"))

setMethod("[","MySeries",function(x, i,j,drop) {
  ii <- substitute(i)
  x$data <- x$data[eval(ii)]
  return(x)
})

S <- MySeries(data=DT)

... but it throws an error when I finally call S[Index>3]. How to fix the above to get this expected result?

  Index
4:  4
5:  5
Was it helpful?

Solution

This is really about the use of eval(substitute()) as much as about S4 methods. Here is the generic that you are interested in

> getGeneric("[")
standardGeneric for "[" defined from package "base"

function (x, i, j, ..., drop = TRUE)
standardGeneric("[", .Primitive("["))
<bytecode: 0x42f4fe0>
<environment: 0x3214270>
Methods may be defined for arguments: x, i, j, drop
Use  showMethods("[")  for currently available ones.

Your method signature differs from the generic (no '...' and no default for 'drop') so the method has a nested '.local' function

> getMethod("[", "MySeries")
Method Definition:

function (x, i, j, ..., drop = TRUE) 
{
    .local <- function (x, i, j, drop) 
    {
        ii <- substitute(i)
        x$data <- x$data[eval(ii)]
        return(x)
    }
    .local(x, i, j, ..., drop)
}

Signatures:
        x         
target  "MySeries"
defined "MySeries"

and subsitute(i) is not what you think it is. Instead, write a method matching the generic signature

setMethod("[", "MySeries", function(x, i, j, ..., drop=TRUE) {
    x$data <- x$data[eval(substitute(i))]
    x
})

nested functions are a general problem with the eval(substitute()) paradigm, not just definition of S4 methods; see this question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top