18

I have an R6 class and I want to add an S3 method for it. The documentation I found mentioned briefly that in order to use S3 dispatch on R6 you must have class = TRUE, but I couldn't find an example of how it should be done.

I did see empirically that simply writing an S3 method in the form s3generic.r6class worked, but I wanted to know if that is indeed to right way to write an S3 method for R6.

For example, say I have an R6 class that enhances a list

library(R6)

R6list <- R6Class(
  "R6list",
  public = list(
    orig = NULL,
    initialize = function(x) {
      self$orig <- x
    }
  )
)

Question 1

Naturally, I want to provide a method for obtaining the underlying list, so I wanted to add an as.list method. Is it standard to add both an S3 generic AND a as.list public function inside the class? My intuitive answer is to add both.

R6list <- R6Class(
  "R6list",
  public = list(
    orig = NULL,
    initialize = function(x) {
      self$orig <- x
    },
    as.list = function() {
      self$orig
    }
  )
)

as.list.R6list <- function(x, ...) {
  x$as.list()
}

So that now if I have an object mylist <- R6list$new(as.list(letters[1:5])) I can either call as.list(mylist) or mylist$as.list(). Is one of those preferred over the other?

Question 2
Is there anything special about writing an S3 method for R6 classes, or is what I wrote above sufficient and the correct way? I wasn't sure if the S3 method has to be written outside of the class definition, or if R6 somehow provides a way to write S3 methods within it so that all the code relating to the class is localized.

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
DeanAttali
  • 25,268
  • 10
  • 92
  • 118
  • The default for R6Class is `class=TRUE`, so in a sense all of the examples you see are illustrations of such usage. – IRTFM Jan 23 '15 at 22:16
  • Right, `class=TRUE` is the reason my code above works, but I didn't see any examples explicitly showing how to write an S3 method so I'm wondering if this is the recommended way of doing this – DeanAttali Jan 23 '15 at 22:31
  • The official answer (as of right now at least) is that what I'm doing is correct. https://github.com/wch/R6/issues/42 – DeanAttali Feb 05 '15 at 03:40
  • so please write it as an answer, otherwise your question still appears in the unanswered ones. – Karl Forner Apr 16 '15 at 09:36

1 Answers1

8

I asked Winston Chang, the author of R6, about this on Github. According to him, the code provided in Question 1 above is the correct way of writing S3 methods for R6 classes.

DeanAttali
  • 25,268
  • 10
  • 92
  • 118