保存R引用类的字段

时间:2014-08-13 12:08:29

标签: r reference-class

我正在尝试保存R引用类的字段:

myclass = setRefClass("myclass",
                       fields = list(
                           x = "numeric",
                           y = "numeric"
                       ))


myclass$methods(
    dfunc = function(i) {
        message("In dfunc, I save x and y...")
        base::save(.self$x, .self$y, file="/tmp/xy.rda")
    }
    )


myclass$methods(
    initialize = function(x, y) {
        x <<- x
        y <<- y
    }
)

显然它不起作用:

x = myclass(5, 6)
x$afunc(1)
x$dfunc()

Error in base::save(.self$x, .self$y, file = "/tmp/xy.rda") : 
  objects ‘.self$x’, ‘.self$y’ not found 

然后我试着附上.self:

myclasr = setRefClass("myclass",
                       fields = list(
                           x = "numeric",
                           y = "numeric"
                       ))


myclass$methods(
    dfunc = function(i) {
        message("In dfunc, I save x and y...")
        attach(.self)
        base::save(x, y, file="/tmp/xy.rda")
        detach(.self)
    }
    )


myclass$methods(
    initialize = function(x, y) {
        x <<- x
        y <<- y
    }
)

得到了另一个错误:

Error in attach(.self) : 
  'attach' only works for lists, data frames and environments

1 个答案:

答案 0 :(得分:2)

您可以使用

myclass$methods(
  dfunc = function(i) {
    message("In dfunc, I save x and y...")
    tempx <- .self$x
    tempy <- .self$y
    base::save(tempx, tempy, file="xy.rda")
  }
)

myclass$methods(
  dfunc = function(i) {
    message("In dfunc, I save x and y...")
    base::save(x, y, file="xy.rda")
  }
)

save使用as.character(substitute(list(...)))[-1L],因此它实际上会查找名为.self$x的变量,该变量当然不存在。