if - else if - else statement and brackets

后端 未结 4 622
名媛妹妹
名媛妹妹 2020-11-29 04:11

I understand the usual way to write an \"if - else if\" statement is as follow:

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


        
相关标签:
4条回答
  • 2020-11-29 04:28

    In R, also we have ifelse() function:

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

    Output:

    # [1] "hi"
    
    0 讨论(0)
  • 2020-11-29 04:38

    As hrbrmstr has mentioned:

    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. The only defined use of else is with compound expressions.

    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.

    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")
    
    0 讨论(0)
  • 2020-11-29 04:39

    ifelse has tree parametes, first conditon, second true result and last false result.

    y_pred = ifelse(prob_predict > 0.5,1,0)
    
    0 讨论(0)
  • 2020-11-29 04:47

    R reads these commands line by line, so it thinks you're done after executing the expression after the if statement. Remember, you can use if without adding 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).

    0 讨论(0)
提交回复
热议问题