R 中带有重复命令的 Switch 语句 [英] Switch Statement with repeated commands in R

查看:35
本文介绍了R 中带有重复命令的 Switch 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In R, is there a way to make a switch statement such that the same block of code is executed for two different cases? Obviously I could copy and paste the whole body of code for both statements, but I was hoping there would be a neater way to do it.

我也可以使用 if-else 块来避免重复大块代码,但 R 中的开关通常更快.

I could also use an if-else block to avoid the repetition of large blocks of code but switches are generally faster in R.

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

It seems unlikely due to the way R parses a switch statement as a function, but I'm hoping that the developers of R took special care in parsing a switch statement to allow for multiple arguments to refer to the same block of code.

推荐答案

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

Provide named arguments without values, they fall through to the next expression with value

> 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'.

这篇关于R 中带有重复命令的 Switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆