gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:09:47 25 4
gpt4 key购买 nike

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

我也可以使用 if-else block 来避免大块代码的重复,但在 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'.

关于r - R中带有重复命令的Switch语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17113598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com