1

I am using the R6 package for OO programming in a package I am developing. My R6 object stores a data frame as well as other information. I would like to override the data.frame() function when called on my R6 object so that its stored data frame is returned.

Is this possible?

For example:

library(R6)

myobj <- R6Class("myobj", list(
  df = NULL,
  args = NULL,
  initialize = function(df, args=NULL) {
    self$df <- df
    self$args <- args
  },
  print = function(...) {
    cat("myobj: \n")
    cat("  df: ", nrow(self$df), " x ", ncol(self$df), "\n")
    invisible(self)
  },
  data.frame = function(...) {
    self$df
  }
))

print(myobj) # works
df <- data.frame(myobj) # does not work

I've read the R6 documentation, I guess I'm confused how we can override print but not other functions called on R6 objects.

  • shouldn't you call your `data.frame` method like this `myobj$data.frame()`? – emilliman5 Apr 14 '19 at 17:24
  • Yes, but is it also possible to do data.frame(myobj). My question is about overriding the function. –  Apr 14 '19 at 17:36
  • 1
    You can't override the `data.frame` function. You could define an `as.data.frame.myobj` method, though. When you call `as.data.frame(x)`, R will dispatch it to `as.data.frame.myobj(x)` using the S3 dispatch mechanism. See http://adv-r.had.co.nz/S3.html for more about S3 dispatch. – wch Apr 16 '19 at 13:51

0 Answers0