2

I am learning how to use R6 classes (and in general R OO).

In this tutorial I found an interesting way of presenting constructors. In section 6.3 a different kind of constructor is defined, returning a class instance with "new" called inside the function.

That resembles the behavior of initializing a class object with a function that computes some stuff, and it would be useful for my purposes.

I was wondering if this can be done in R6 as well, and, if so, if there are resources where I can learn how to do it properly.

My example in S4 is as follows:

ERes <- setClass("ERes",
              representation = representation(
                  eTable = 'data.table',
                  eList = 'list'
                )
              )

setERes <- function(someData){
    return(new(Class = 'ERes', eTable = table(someData), eList = as.list(someData)))
}

Now, the code that creates eTable and eList would be a bit more complicated, but that is the principle. The user does not need to call $new, but a function that returns a proper object. I thought that I could put the function in the R6 class, but I am not sure about how to call it.

mic
  • 927
  • 8
  • 17

1 Answers1

2

Since R6 classes are actually envoronments, you can use className$constructorName to archieve this result.

library(R6)

ERes <- R6Class(
  "ERes",
  public = list(
    eTable = NULL,
    eList = NULL,
    initialize = function(eTable, eList){
      self$eTable <- eTable
      self$eList <- eList
    }
  )
)

ERes$userConstructor <- function(someData){
  ERes$new(table(someData), as.list(someData))
}

myObject <- ERes$userConstructor(rpois(100, 5))

myObject$eTable
# someData
#  0  1  2  3  4  5  6  7  8 10 
#  3  3  7 16 16 20 14 10  9  2 
Gregor de Cillia
  • 7,397
  • 1
  • 26
  • 43