我如何告诉 R6 class 如何处理方括号?

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

我有一个 R6 class,其属性为 data.table。假设它看起来像这样:

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)

我想这样做:

bar[<data.table stuff>]

这样做:

bar$dt[<data.table stuff>]

可能吗?

您可以使用 S3 class:

`[.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