简体   繁体   English

if - else if - else 语句和括号

[英]if - else if - else statement and brackets

I understand the usual way to write an "if - else if" statement is as follow:我理解编写“if - else if”语句的常用方法如下:

if (2==1) {
  print("1")
} else if (2==2) {
  print("2")
} else {
  print("3")
}

or或者

if (2==1) {print("1") 
} else if (2==2) {print("2")
} else print("3")

On the contrary, If I write in this way相反,如果我这样写

if (2==1) {
  print("1")
} 
else if (2==2) {
  print("2")
}
else (print("3"))

or this way:或者这样:

if (2==1) print("1") 
else if (2==2) print("2")
else print("3")

the statement does NOT work.该声明不起作用。 Can you explain me why } must precede else or else if in the same line?你能解释一下为什么}必须在elseelse if在同一行之前吗? Are there any other way of writing the if-else if-else statement in R, especially without brackets?有没有其他方法可以在 R 中编写 if-else if-else 语句,尤其是没有括号?

R reads these commands line by line, so it thinks you're done after executing the expression after the if statement. R 逐行读取这些命令,因此在执行 if 语句之后的表达式后,它认为您已完成。 Remember, you can use if without adding else .请记住,您可以使用if而不添加else

Your third example will work in a function, because the whole function is defined before being executed, so R knows it wasn't done yet (after if() do ).您的第三个示例将在函数中工作,因为整个函数在执行之前已定义,因此 R知道它还没有完成(在if() do )。

In R, also we have ifelse() function:在 R 中,我们也有ifelse()函数:

ifelse(1 < 0, "hello", "hi")

Output:输出:

# [1] "hi"

As hrbrmstr has mentioned:正如hrbrmstr所提到的:

When the initial if is followed by a compound expression (indicated by the {} pair) the parser by default is going to expect the expression followed by else to be compound as well.当初始 if 后跟复合表达式(由 {} 对表示)时,解析器默认会期望后跟 else 的表达式也是复合表达式。 The only defined use of else is with compound expressions. else 的唯一定义用途是与复合表达式一起使用。

In the statement if(cond) cons.expr else alt.expr , the else needs to be put after and in same line with the end `cons.expr' compound.if(cond) cons.expr else alt.exprelse需要放在最后的 cons.expr 复合词之后并在同一行。

So if you want to have your code a better look without brackets, apply this way:所以如果你想让你的代码在没有括号的情况下更好看,可以这样应用:

if (2==1) print("1") else 
   if (2==2) print("2") else 
      print("3")

ifelse 具有树参数、第一个条件、第二个真结果和最后一个假结果。

y_pred = ifelse(prob_predict > 0.5,1,0)

It's good idea to use braces when there are nested ifs. 当有嵌套ifs时,最好使用大括号。 For example, in 例如,在

if(n>0)
    if(a>b)
        z=a;
    else
        z=b;

the else goes with inner if not with if(n>0). 如果不是if(n> 0),则else与内部相关。 If that isn't what you want, braces must be used to force proper association: 如果这不是您想要的,必须使用大括号来强制正确关联:

if(n>0){
    if(a>b)
        z=a;
}
else
    z=b;

For more detail, see a very good complete tutorial: Conditional statements: if-else, else-if and switch in C ! 有关更多详细信息,请参阅一个非常好的完整教程: 条件语句:if-else,else-if和切换C! Hope this helps you! 希望这对你有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM