我对R中的switch语句有点困惑.只需在googling函数中我得到一个例子,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
然而,这似乎只是if
为每个指定了一堆语句type
这就是全部switch()
吗?有人可以给我更多的例子和更好的应用吗?
我有一系列嵌套if..else
语句,我想用 case 语句替换它们。现在 R 有一个简单的 switch 运算符,如下所示:
switch (i) {
case 1:
// action 1
break;
case 2:
// action 2
break;
case 3:
// action 3
break;
default:
// action 4
break;
}
Run Code Online (Sandbox Code Playgroud)
然而,我的情况是更复杂的条件,而不是简单的文字值。
我需要类似的东西
switch {
case i %in% someList:
// action 1
break;
case i %in% someOtherList:
// action 2
break;
case i > 42:
// action 3
break;
default:
// action 4
break;
}
Run Code Online (Sandbox Code Playgroud)
有谁知道R中是否可以实现这样的事情?这将使我正在编写的代码更易于阅读。
据我所知,这个问题没有在这里得到解答:How to use the switch statements …