“User” constructor for R6 class in R

为君一笑 提交于 2019-12-20 02:58:24

问题


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.


回答1:


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 


来源:https://stackoverflow.com/questions/35881234/user-constructor-for-r6-class-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!