【问题标题】:Save field of an R reference class保存 R 参考类的字段
【发布时间】:2014-08-13 12:08:29
【问题描述】:

我正在尝试保存 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

【问题讨论】:

    标签: r reference-class


    【解决方案1】:

    你可以使用

    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 的变量,而该变量当然不存在。

    【讨论】:

      猜你喜欢
      • 2016-10-31
      • 2012-10-21
      • 2012-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多