Search code examples
rreference-class

Save field of an R reference class


I am trying to save a field of an R reference class:

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
    }
)

Apparently it doesn't work:

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 

Then I tried to attach .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
    }
)

Got another error:

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

Solution

  • You can use

    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")
      }
    )
    

    or

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

    save uses as.character(substitute(list(...)))[-1L] so it literally looks for a variable named .self$x which of course doesnt exist.