如何告诉R6类如何处理方括号?

9

我有一个R6类,其中包含一个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>]

这是可能的吗?

1个回答

8
您可以使用S3类来实现这个功能:
`[.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

完美运行。除了 Rstudio 不会自动完成列名,但我怀疑没有任何方法可以避免这种情况。 - crf
我喜欢它,我只是2-3天前开始使用它! :) - jangorecki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接