[R] Enumeration in R
Paul Roebuck
roebuck at odin.mdacc.tmc.edu
Wed Jul 7 01:50:58 CEST 2004
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 at 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 at 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)
More information about the R-help
mailing list