问题描述
我对 R 中的 switch 语句有点困惑.只需谷歌搜索功能,我得到一个例子如下:
I am a little confused about the switch statement in R.Simply googling the function I get an example as follows:
switch 的一个常见用途是根据函数参数之一的字符值进行分支.
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
然而,这似乎只是为每个 type
However this just seems to be the same as just having a bunch of if
statements designated for each type
这就是 switch()
的全部内容吗?有人能给我更多的例子和更好的应用吗?
Is that all there is to switch()
? Can someone give me further examples and better applications?
推荐答案
好吧,又到了救援的时机.看起来 switch
通常比 if
语句更快.因此,以及使用 switch
语句使代码更短/更整洁的事实倾向于使用 switch
:
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
更新 考虑到 Joshua 的评论,我尝试了其他方法来进行基准测试.微基准似乎是最好的....它显示了类似的时间:
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
最终更新 这里展示了 switch
的多功能性:
Final Update Here's showing how versatile switch
is:
switch(type, case1=1, case2=, case3=2.5, 99)
这将 case2
和 case3
映射到 2.5
并且(未命名)默认为 99
.有关更多信息,请尝试 ?switch
This maps case2
and case3
to 2.5
and the (unnamed) default to 99
. For more information, try ?switch
这篇关于switch() 语句用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!