R 中带有重复命令的 Switch 语句

2024-01-08

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

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

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


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

> 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'.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R 中带有重复命令的 Switch 语句 的相关文章

随机推荐