Search code examples
rdata.tabler6

How do I tell an R6 class what to do with square brackets?


I have an R6 class that has as an attribute a data.table. Let's say it looks like this:

library(R6)
library(data.table)

foo <- R6Class(
  classname = 'foo',
  public = list(
    dt = NA,
    initialize = function(dt) {
      self$dt <- dt
    }
  )
)

set.seed(123)
dt <- data.table(col1 = rnorm(10), col2 = rnorm(10))

bar <- foo$new(dt)

I would like to make it so that:

bar[<data.table stuff>]

does this:

bar$dt[<data.table stuff>]

Is it possible?


Solution

  • You could use the S3 class for that:

    `[.foo` = function(x, ...) x$dt[...]
    
    bar[col1 > 0]
    #         col1       col2
    #1: 1.55870831  0.4007715
    #2: 0.07050839  0.1106827
    #3: 0.12928774 -0.5558411
    #4: 1.71506499  1.7869131
    #5: 0.46091621  0.4978505