switch
Evaluate One of Several Expressions
Description
Branches the evaluation, depending on the value of the first argument.
Usage
switch(EXPR, ...)
Arguments
EXPR |
an object that is either character or numeric when it is evaluated.
This object is used to select which of the remaining arguments to evaluate.
An error occurs if the object is of length zero.
|
... |
one of these arguments (at most) is selected, evaluated, and then returned.
|
Details
switch evaluates
EXPR.
- If EXPR is of mode "character", the function looks among the names of the remaining arguments for one that matches the character string exactly (not partially), using only the first element of the value. If there is a match, the corresponding argument is evaluated and returned as the value of switch; otherwise the first unnamed argument is evaluated and returned.
- If EXPR is of mode "character", and the value of EXPR matches a name without an argument, the next non-omitted argument is selected. (See the examples section.)
- If EXPR is not of mode "character", it is coerced to integer. If the integer is in the range 1 to nargs()-1, then the corresponding argument from the ... is evaluated and returned as the value of switch.
Value
the value of the selected expression, or NULL if no expression is
selected.
See Also
Examples
dist <- 'logistic'
switch(dist, cauchy=rcauchy(1), logistic=rlogis(1), norm=rnorm(1))
x <- 2
switch(x, 2+2, print("this one is chosen"), { y <- exp(5); z <- sin(2.1)})
cat('Do you feel lucky? '); answer <- readline()
switch(as.character(answer), y=, yes=, Yes=, YES=1, n=, no=, No=, NO=2, 3)