Enum-like arguments in R

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

    I like to use environments as replacement for enums because you can lock them to prevent any changes after creation. I define my creation function like this:

    Enum <- function(...) {
    
      ## EDIT: use solution provided in comments to capture the arguments
      values <- sapply(match.call(expand.dots = TRUE)[-1L], deparse)
    
      stopifnot(identical(unique(values), values))
    
      res <- setNames(seq_along(values), values)
      res <- as.environment(as.list(res))
      lockEnvironment(res, bindings = TRUE)
      res
    }
    

    Create a new enum like this:

    FRUITS <- Enum(APPLE, BANANA, MELON)
    

    We can the access the values:

    FRUITS$APPLE
    

    But we cannot modify them or create new ones:

    FRUITS$APPLE <- 99  # gives error
    FRUITS$NEW <- 88  # gives error
    

提交回复
热议问题