Constructor "User" for class R6 in R

I am learning how to use the R6 classes (and generally R OO).

In this tutorial, I found an interesting way to introduce constructors. Section 6.3 defines a different type of constructor, returning an instance of the class with a "new" call inside the function.

This is similar to the initialization behavior of a class object using a function that evaluates some things, and this would be useful for my purposes.

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

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 the eTable and eList will be a little more complicated, but that's the principle. The user does not need to call $ new, but a function that returns the correct object. I thought I could put a function in the R6 class, but I'm not sure what to call it.

+2
source share
1 answer

Since R6 classes are actually envoronments, you can use className$constructorName to archive 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 
+1
source

Source: https://habr.com/ru/post/1241560/


All Articles