Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

data.table

r6

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?

like image 669
crf Avatar asked Oct 29 '15 20:10

crf


Video Answer


1 Answers

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
like image 67
eddi Avatar answered Oct 18 '22 09:10

eddi