5

在 R 中,有没有办法制作一个 switch 语句,以便为两种不同的情况执行相同的代码块?显然,我可以复制并粘贴两个语句的整个代码,但我希望有一种更简洁的方法来做到这一点。

我也可以使用 if-else 块来避免大块代码的重复,但在 R 中切换通常更快。

由于 R 将 switch 语句解析为函数的方式,这似乎不太可能,但我希望 R 的开发人员在解析 switch 语句时特别小心,以允许多个参数引用同一代码块。

4

1 回答 1

7

提供没有值的命名参数,它们会落入下一个有值的表达式

> switch("A", A=, B=, C="A OR B OR C", "Other")
[1] "A OR B OR C"
> switch("C", A=, B=, C="A OR B OR C", "Other")
[1] "A OR B OR C"
> switch("D", A=, B=, C="A OR B OR C", "Other")
[1] "Other"

这在帮助页面上有所描述?switch

 If 'EXPR' evaluates to a character string then that string is
 matched (exactly)to the names of the elements in '...'.  If there
 is a match then that element is evaluated unless it is missing, in
 which case the next non-missing element is evaluated, so for
 example 'switch("cc", a = 1, cc =, cd =, d = 2)' evaluates to '2'.
于 2013-06-14T17:05:25.103 回答