如何使用Reference Classes扩展data.table?

时间:2014-08-05 11:25:56

标签: r data.table reference-class

问题:

我希望创建一个扩展data.table的参考类。

动机

  1. 想要data.table使用自定义方法和可变字段
  2. 仍希望所有现有语法(例如索引,子集,合并等)按预期工作
  3. 问题是我到目前为止失败了。

    尝试:

    我试过了:

    MyDataTable <- setRefClass("MyDataTable",
        methods = list(
            clearCell = function(i, j) {        # A trivial custom method - sets a cell to NA
                .self[i, (j) := NA]
            }
        ),
        contains = "data.table"
    )
    
    MyDataTable(a = 1:26, b = letters)$clearCell(1, 1)
    

    但得到了错误:

    Error in envRefSetField(.Object, field, classDef, selfEnv, elements[[field]]) : 
      ‘a’ is not a field in class “MyDataTable”
    

    然而,我期待的是:

         a b
     1: NA a
     2:  2 b
     3:  3 c
     4:  4 d
     5:  5 e
     6:  ... etc etc 
    

    出了什么问题?

1 个答案:

答案 0 :(得分:1)

您未正确初始化参考类对象。我不知道contains应该如何工作,但是一个简单的字段可以工作:

MyDataTable <- setRefClass("MyDataTable",
                   fields  = list(.dt = 'data.table'),
                   methods = list(initialize = function(...){
                                    .self$.dt <- data.table(...)
                                  },
                                  clearCell  = function(i, j){
                                    .self$.dt[i, (j) := NA]
                                  },
                                  bracket    = function(...){
                                    .self$.dt[...]
                                  }
                                  ))

MyDataTable(a = 1:5, b = letters[1:5])$clearCell(1,1)
#    a b
#1: NA a
#2:  2 b
#3:  3 c
#4:  4 d
#5:  5 e

MyDataTable(a = 1:5, b = letters[1:5])$bracket(b == 'c', a := 10)
#    a b
#1:  1 a
#2:  2 b
#3: 10 c
#4:  4 d
#5:  5 e