Enum-like arguments in R

前端 未结 5 1464
我在风中等你
我在风中等你 2021-01-04 04:47

I\'m new to R and I\'m currently trying to supply the enumeration-like argument to the R function (or the RC/R6 class method), I currently use character vector plus ma

5条回答
  •  孤城傲影
    2021-01-04 05:16

    Update 07/21/2017: I have created a package for enumerations in R:

    https://github.com/aryoda/R_enumerations


    If you want to use self-defined enum-alike data types as arguments of R functions that support

    • automatic translation of enum item names to the corresponding integer values
    • code auto completion (e. g. in RStudio)
    • clear documentation in the function signature which values are allowed as actual function parameters
    • easy validation of the actual function parameter against the allowed (integer) enum item values

    you can define your own match.enum.arg function, e. g.:

    match.enum.arg <- function(arg, choices) {
      if (missing(choices)) {
        formal.args <- formals(sys.function(sys.parent()))
        choices <- eval(formal.args[[as.character(substitute(arg))]])
      }
    
      if(identical(arg, choices))
        arg <- choices[[1]][1]    # choose the first value of the first list item
    
      allowed.values <- sapply(choices,function(item) {item[1]})   # extract the integer values of the enum items
    
      if(!is.element(arg, allowed.values))
        stop(paste("'arg' must be one of the values in the 'choices' list:", paste(allowed.values, collapse = ", ")))
    
      return(arg)
    }
    

    Usage:

    You can then define and use your own enums like this:

    ColorEnum <- list(BLUE = 1L, RED = 2L, BLACK = 3L)
    
    color2code = function(enum = ColorEnum) { 
      i <- match.enum.arg(enum)
      return(i)
    }
    

    Example calls:

    > color2code(ColorEnum$RED) # use a value from the enum (with auto completion support)
    [1] 2
    > color2code()              # takes the first color of the ColorEnum
    [1] 1
    > color2code(3)             # an integer enum value (dirty, just for demonstration)
    [1] 3
    > color2code(4)             # an invalid number
    Error in match.enum.arg(enum) : 
      'arg' must be one of the values in the 'choices' list: 1, 2, 3 
    

提交回复
热议问题