Enum-like arguments in R

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

    Here is a simple method which supports enums with assigned values or which use the name as the value by default:

    makeEnum <- function(inputList) {
      myEnum <- as.list(inputList)
      enumNames <- names(myEnum)
      if (is.null(enumNames)) {
        names(myEnum) <- myEnum
      } else if ("" %in% enumNames) {
        stop("The inputList has some but not all names assigned. They must be all assigned or none assigned")
      }
      return(myEnum)
    }
    

    If you are simply trying to make a defined list of names and don't care about the values you can use like this:

    colors <- makeEnum(c("red", "green", "blue"))
    

    If you wish, you can specify the values:

    hexColors <- makeEnum(c(red="#FF0000", green="#00FF00", blue="#0000FF"))
    

    In either case it is easy to access the enum names because of code completion:

    > hexColors$green
    [1] "#00FF00"
    

    To check if a variable is a value in your enum you can check like this:

    > param <- hexColors$green
    > param %in% hexColors
    

提交回复
热议问题