I am a little confused about the switch statement in R.
Simply googling the function I get an example as follows:
A common use of switch is to branch according to the character value of one of the arguments to a function.
> centre <- function(x, type) {
+ switch(type,
+ mean = mean(x),
+ median = median(x),
+ trimmed = mean(x, trim = .1))
+ }
> x <- rcauchy(10)
> centre(x, "mean")
[1] 0.8760325
> centre(x, "median")
[1] 0.5360891
> centre(x, "trimmed")
[1] 0.6086504
However this just seems to be the same as just having a bunch of if
statements designated for each type
Is that all there is to switch()
? Can someone give me further examples and better applications?
Best Solution
Well, timing to the rescue again. It seems
switch
is generally faster thanif
statements. So that, and the fact that the code is shorter/neater with aswitch
statement leans in favor ofswitch
:Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:
Final Update Here's showing how versatile
switch
is:This maps
case2
andcase3
to2.5
and the (unnamed) default to99
. For more information, try?switch