Search code examples
rreference-class

Multiple acceptable classes in reference class field list


For example:

Mycls = setRefClass(
    "Mycls",
    fields = list(
    # this is just a mock up
    colorvec = "numeric" | "factor" | "matrix"
    )
)

In this example, I want to allow colorvec to be numeric or factor or matrix. Is there a way to do this?


Solution

  • Three possibilities.

    1. Use the ANY type.

      m2 = setRefClass("m2",
        fields = list(x="ANY")
      )
      

      which, as the name, suggests allows you to have any type.

    2. Create another class that only accepts numerics/factors/matrices:

      setClass("mult", representation(x="ANY"))
      setValidity("mult",
              function(object) 
                   is.numeric(object@x) || is.factor(object@x) || is.matrix(object@x)
               )
      
      m3 = setRefClass("m3", fields = list(x="mult"))
      

      So

      bit = new("mult", x=10)
      m3$new(x=bit)
      
    3. Have a function as your input and check the types. Notice that the x field doesn't actually store any data, it just checks and returns the internal value. You could create a simple show method to hide the internal field.

      m4 = setRefClass("m4",  
                   fields=list(x = function(y){
                     if(!missing(y) && !is.null(y)) {
                       if(!(is.numeric(y))){
                         stop("Wrong type")
                       }  
                       internal <<- y
                     } else internal}
                     , 
                   internal="ANY"
                   ))
      
      m4$new(x=10)
      m4$new(x="10")