【发布时间】:2012-12-20 12:50:01
【问题描述】:
我有一个函数,它查看 9 种不同的可能性并相应地选择一个具有以下形式的动作:
我正在做的是查找一个向量并为向量中的每个条目决定
IF the value in the vector is 1 THEN start function B
IF the value in the vector is 2 THEN start function C
IF the value in the vector is 3 THEN start function D
IF the value in the vector is 4 THEN start function E
等等
我想用 R 写这个。我是否只为每个案例都加上“else”?
我已经通过以下方式尝试了switch:
condition<-6
FUN<-function(condition){
switch(condition,
1 = random1(net)
2 = random2(net)
3 = random3(net)
4 = random4(net)
5 = random5(net)
6 = random6(net)
7 = random7(net)
8 = random8(net)
9 = random9(net)
10= random10(net))
}
其中随机 1 到 10 是使用变量 'net' 的函数
switch 命令试图做的是检查 'condition' 的值,如果它在上面的示例中为 6,则它运行函数:random6(net)
【问题讨论】:
-
if/if和if/else if完全不同。先决定你需要哪一个。 -
也看
?switch -
我已经编辑了这个问题,现在可能更清楚了
-
如果vector中的值都是1和2,或者1和3等等,要应用什么函数??
-
@RomainFrancois 有答案。也许 OP 可以尝试
switch并发布他的解决方案作为答案?
标签: r