[R] Enumeration in R

From: Paul Roebuck <roebuck_at_odin.mdacc.tmc.edu>
Date: Wed 07 Jul 2004 - 09:50:58 EST


I want the equivalent of this 'C' declaration.

    enum StoplightColor {

        green = 3,
        yellow = 5,
        red = 7

    };

This mostly works except the validity checking doesn't seem to occur automatically. What didn't I do to enable it?

setClass("stoplightColor",

         representation(value = "integer"),
         prototype = integer(1))

stoplightColor <- function(value) {

    if (missing(value))

        stop('no value!')
    new("stoplightColor", value)
}

valid.stoplightColor <- function(object) {

    valid <- switch(as(object@value, "character"),

                    "3" = TRUE,
                    "5" = TRUE,
                    "7" = TRUE,
                    FALSE)
    if (valid == FALSE)
        return("Value not in list of valid values [3|5|7]");
    return(TRUE);
}

setValidity("stoplightColor", valid.stoplightColor) initialize.stoplightColor <- function(.Object, value) {

    .Object@value <- as.integer(value)
    .Object

}

setMethod("initialize",

          signature(.Object = "stoplightColor"),
          initialize.stoplightColor)

green <- stoplightColor(3)
yellow <- stoplightColor(5)
red <- stoplightColor(7)

# error: no value argument
noarg <- stoplightColor()

# error: invalid number argument
bad <- stoplightColor(6) # WHY NO WARNING HERE? validObject(bad)



SIGSIG -- signature too long (core dumped)

R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed Jul 07 09:56:22 2004

This archive was generated by hypermail 2.1.8 : Fri 18 Mar 2005 - 09:46:09 EST