【问题标题】:How do I tell an R6 class what to do with square brackets?我如何告诉 R6 班级如何处理方括号?
【发布时间】:2015-10-29 20:43:24
【问题描述】:

我有一个 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>]

有可能吗?

【问题讨论】:

    标签: r data.table r6


    【解决方案1】:

    您可以为此使用 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 不会自动完成列名,但我怀疑是否有任何解决方法。
    • 喜欢,2-3天前才开始用! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2012-06-30
    • 1970-01-01
    • 2019-07-29
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多