Enum-like arguments in R

前端 未结 5 1501
我在风中等你
我在风中等你 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:05

    I just faced this exact problem and could only find this SO question. The objectProperties package mention by Paul seems abandoned (it produces several warnings) and has lots of overhead for such a simple (in principle) problem. I came up with the following lightweight solution (depends only on the stringi package), which reproduces the feel of Enums in C languages. Maybe this helps someone.

    EnumTest <- function(colorEnum = ColorEnum$BLUE) {
      enumArg <- as.character(match.call()[2])
      match.arg(enumArg, stringi::stri_c("ColorEnum$", names(ColorEnum)))
      sprintf("%s: %i",enumArg,colorEnum)
    }
    
    ColorEnum <- list(BLUE = 0L, RED = 1L, BLACK = 2L)
    

提交回复
热议问题