使用R中的重复命令切换语句

Jon*_*aus 5 r switch-statement

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

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

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

Mar*_*gan 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"
Run Code Online (Sandbox Code Playgroud)

这在帮助页面上有所描述 ?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'.
Run Code Online (Sandbox Code Playgroud)