我希望创建一个扩展data.table
的参考类。
动机
data.table
使用自定义方法和可变字段问题是我到目前为止失败了。
我试过了:
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
出了什么问题?
答案 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