Examples for 'base::switch'


Select One of a List of Alternatives

Aliases: switch

Keywords: programming

### ** Examples

require(stats)
centre <- function(x, type) {
  switch(type,
         mean = mean(x),
         median = median(x),
         trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
centre(x, "mean")
[1] 1.508625
centre(x, "median")
[1] -0.2504369
centre(x, "trimmed")
[1] 0.07039551
ccc <- c("b","QQ","a","A","bb")
# note: cat() produces no output for NULL
for(ch in ccc)
    cat(ch,":", switch(EXPR = ch, a = 1, b = 2:3), "\n")
b : 2 3 
QQ : 
a : 1 
A : 
bb : 
for(ch in ccc)
    cat(ch,":", switch(EXPR = ch, a =, A = 1, b = 2:3, "Otherwise: last"),"\n")
b : 2 3 
QQ : Otherwise: last 
a : 1 
A : 1 
bb : Otherwise: last 
## switch(f, *) with a factor f
ff <- gl(3,1, labels=LETTERS[3:1])
ff[1] # C
[1] C
Levels: C B A
## so one might expect " is C" here, but
switch(ff[1], A = "I am A", B="Bb..", C=" is C")# -> "I am A"
Warning in switch(ff[1], A = "I am A", B = "Bb..", C = " is C"): EXPR is a "factor", treated as integer.
 Consider using 'switch(as.character( * ), ...)' instead.
[1] "I am A"
## so we give a warning

## Numeric EXPR does not allow a default value to be specified
## -- it is always NULL
for(i in c(-1:3, 9))  print(switch(i, 1, 2 , 3, 4))
NULL
NULL
[1] 1
[1] 2
[1] 3
NULL
## visibility
switch(1, invisible(pi), pi)
switch(2, invisible(pi), pi)
[1] 3.141593

[Package base version 4.2.3 Index]