Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if - else if - else statement and brackets

Tags:

r

if-statement

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("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? Are there any other way of writing the if-else if-else statement in R, especially without brackets?

like image 917
MasterJedi Avatar asked Sep 17 '14 08:09

MasterJedi


People also ask

Do you need brackets for if else statements?

If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.

Can IF statement have 2 conditions?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

Do you need curly braces for if statements in C?

Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces. But it is Highly Recommended to use curly braces. Because if the user (or someone else) ever expands the statement it will be required.

What is if else statement with example?

The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.


1 Answers

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).

like image 176
Berry Boessenkool Avatar answered Sep 26 '22 08:09

Berry Boessenkool