r - switch() 语句用法

标签 r switch-statement

我对 R 中的 switch 语句有点困惑。 只需谷歌搜索该函数,我就会得到如下示例:

switch 的常见用途是根据函数参数之一的字符值进行分支。

 > 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 指定一堆 if 语句相同

这就是 switch() 的全部内容吗?有人可以给我更多的例子和更好的应用程序吗?

最佳答案

好吧,又到了救援的时机了。看起来 switch 通常比 if 语句更快。 因此,使用 switch 语句使代码更短/更简洁的事实倾向于使用 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 的评论,我尝试了其他基准测试方法。微基准似乎是最好的。 ...它显示了相似的时间:

> 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 的多功能性:

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

这会将 case2case3 映射到 2.5,并将(未命名)默认值映射到 99。有关更多信息,请尝试 ?switch

关于r - switch() 语句用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7825501/

相关文章:

r - 迭代 rvest 抓取函数给出 : "Error in open.connection(x, "rb") : Timeout was reached"

r - 在 FactoExtra 包中的 fviz_pca 函数中自定义点形状

r - 强制 roc 函数(R 中的 pROC 包)中的 "direction"参数输入究竟有什么作用?

C++ 用户输入关闭程序调试

java - switch 语句不兼容类型

r - 确定 R data.frame 列中值的变化位置

r - 聚集在前两行

android - 如何添加取决于 ListView 中 TextView 文本的 ImageView

Android按钮打开xml布局

java - 将 String 与 Switch 语句一起使用?