3.2.6 switch 语句

Keywords:

Previous: for,Up: Control structures

3.2.6 switch 语句

技术层面上来说,switch 仅仅是一个函数,但是它的语义学定义和其它程序语句的控制结构类似。

它的语法如下

     switch (statement, list)

其中 list 的元素可能有自己的名字。首先,statement 被求值得到结果value。如果 value 是 1 到 list长度间的一个数字,那么list对应元素将会被求值并返回结果。如果 value 值过大或者过小,NULL 将会被返回。

     > x <- 3

     > switch(x, 2+2, mean(1:10), rnorm(5))

     [1]  2.2903605  2.3271663 -0.7060073  1.3622045 -0.2892720

     > switch(2, 2+2, mean(1:10), rnorm(5))

     [1] 5.5

     > switch(6, 2+2, mean(1:10), rnorm(5))

     NULL

如果 value 是字符向量,那么 ... 的元素中名字和 value 准确匹配的元素会被执行。如果没有匹配的,返回 NULL

     > y <- "fruit"

     > switch(y, fruit = "banana", vegetable = "broccoli", meat = "beef")

     [1] "banana"

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

switch 返回值要么是语句的求值结果要么在没有语句被求值时的NULL

为了从一个已经存在的可选方法列表里面选择一个,switch 可能不是最好的实现方案。通常,用 eval 和 子集操作符 [[ 直接运行 eval(x[[condition]]) 会更好。

Hits:Loading...

special topic