R:如何使switch语句出错
在许多语言中,有一条名为R:如何使switch语句出错,r,switch-statement,fall-through,R,Switch Statement,Fall Through,在许多语言中,有一条名为break的指令,它告诉解释器在当前语句之后退出开关。如果忽略它,则在处理当前案例后,开关将失效: switch (current_step) { case 1: print("Processing the first step..."); # [...] case 2: print("Processing the second step..."); # [...] case 3: print("Processin
break
的指令,它告诉解释器在当前语句之后退出开关。如果忽略它,则在处理当前案例后,开关将失效:
switch (current_step)
{
case 1:
print("Processing the first step...");
# [...]
case 2:
print("Processing the second step...");
# [...]
case 3:
print("Processing the third step...");
# [...]
break;
case 4:
print("All steps have already been processed!");
break;
}
如果您想要经历一系列的可传递条件,那么这样的设计模式非常有用
我理解,如果程序员忘记插入break语句,这可能会由于无意的错误而导致错误,但默认情况下,有几种语言正在中断,并且包含一个错误穿透关键字(例如Perl中的
continue
)
根据设计,R开关在每种情况结束时也会默认断开:
switch(current_step,
{
print("Processing the first step...")
},
{
print("Processing the second step...")
},
{
print("Processing the third step...")
},
{
print("All steps have already been processed!")
}
)
在上述代码中,如果将当前步骤设置为1,则输出将仅为“处理第一步…”
在R中是否有任何方法可以强制开关箱通过以下情况?使用
switch()
似乎不可能出现这种行为。
正如评论中所建议的,最好的选择是实现我自己的版本
因此,我推送了一个对我的
可选包的更新来实现这个特性()
通过此更新,您现在可以在模式匹配函数match_With
中使用故障诊断语句
问题中的设计模式可通过以下方式复制:
library(optional)
a <- 1
match_with(a
1, fallthrough(function() "Processing the first step..."),
2, fallthrough(function() "Processing the second step..."),
3, function() "Processing the third step...",
4, function() "All steps have already been processed!"
)
## [1] "Processing the first step..." "Processing the second step..." "Processing the third step..."
是您能做到的最好的了。@hrbrmstr很接近,但仍然不是真正的失败,这个解决方案只允许一个案例有多个标签。@Lovy-如果您不喜欢Rswitch()
语句的行为,您可以编写自己的版本。@Lovy我知道。我说“你能做到最好”是有原因的。请随意。
library("magrittr")
b <- 4
match_with(a,
. %>% if (. %% 2 == 0).,
fallthrough( function() "This number is even" ),
. %>% if ( sqrt(.) == round(sqrt(.)) ).,
function() "This number is a perfect square"
)
## [1] "This number is even" "This number is a perfect square"