switch() statement usage

后端 未结 2 1736
傲寒
傲寒 2020-12-04 07:42

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 t

相关标签:
2条回答
  • 2020-12-04 08:31

    Well, timing to the rescue again. It seems switch is generally faster than if statements. So that, and the fact that the code is shorter/neater with a switch statement leans in favor of switch:

    # Simplified to only measure the overhead of switch vs if
    
    test1 <- function(type) {
     switch(type,
            mean = 1,
            median = 2,
            trimmed = 3)
    }
    
    test2 <- function(type) {
     if (type == "mean") 1
     else if (type == "median") 2
     else if (type == "trimmed") 3
    }
    
    system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
    system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
    system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
    system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs
    

    Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:

    > library(microbenchmark)
    > microbenchmark(test1('mean'), test2('mean'), times=1e6)
    Unit: nanoseconds
               expr  min   lq median   uq      max
    1 test1("mean")  709  771    864  951 16122411
    2 test2("mean") 1007 1073   1147 1223  8012202
    
    > microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
    Unit: nanoseconds
                  expr  min   lq median   uq      max
    1 test1("trimmed")  733  792    843  944 60440833
    2 test2("trimmed") 2022 2133   2203 2309 60814430
    

    Final Update Here's showing how versatile switch is:

    switch(type, case1=1, case2=, case3=2.5, 99)
    

    This maps case2 and case3 to 2.5 and the (unnamed) default to 99. For more information, try ?switch

    0 讨论(0)
  • 2020-12-04 08:35

    In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:

    http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/

    Personally, when I have 3 or more cases, I usually just go with case/switch.

    0 讨论(0)
提交回复
热议问题