Reference Class with custom field classes in R?

后端 未结 2 1724
孤城傲影
孤城傲影 2021-02-06 14:45

I would like to use a custom reference class inside another reference class, but this code fails:

nameClass <- setRefClass(\"nameClass\", fields = list(first         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 15:10

    It seems that this is because you do not have a default constructor for your "nameClass":

    nameClass$new()
    Error in strsplit(char, "\\.") : 
      argument "char" is missing, with no default
    

    If you modify your nameClass like this:

    nameClass <- setRefClass("nameClass", fields = list(first = "character",
                                                        last = "character"),
                             methods = list(
                               initialize = function(s = NULL) {
                                 if (!is.null(s) && nzchar(s)) {
                                   chunks <- strsplit(s,"\\.")
                                   first <<- chunks[[1]][1]
                                   last <<- chunks[[1]][2]
                                 }
                               },
                               show = function(){
                                 cat("Special Name Class \n:")
                                 cat("First Name:")
                                 methods::show(first)
                                 cat("Last Name:")
                                 methods::show(last)
                               }
                             ))
    

    Then:

    nameClass$new()
    Special Name Class 
    :First Name:character(0)
    Last Name:character(0)
    

    and your personClass is now functional (yet the initialize method is quite odd):

    personClass$new("tyler.durden")
    Reference class object of class "personClass"
    Field "fullname":
    Special Name Class 
    :First Name:[1] "\"tyler"
    Last Name:[1] "durden\""
    Field "occupation":
    [1] "tyler.durden"
    

提交回复
热议问题