If statements in R language ( Decision making Statements)

If statement is one of the Decision-making statements in the R programming language. It is one of the easiest decision-making statements.

It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statement is executed otherwise not.

Syntax:

if (expression) {
   #statement to execute if condition is true
}

If the expression is true, the statement gets executed. But if the expression is FALSE, nothing happens. The expression can be logical/numerical vector, but only the first element is taken into consideration.
In the case of numeric vector, zero is taken as FALSE, rest as TRUE.

Lets work on few examples :

  1. IF statement:

In this above example, variable a is assigned a value of 5. The given expression will check if the value of variable a is greater than 0.
If the value of a is greater than zero, the print statement will be executed and the output will be “The Variable a = 5”. If the value of a is less than 0, nothing will happen.

From the above screenshot, out put is printed in Console pane and in environment pane, But in environment pane we are seeing A value and as well as I value , This I value belongs to the Previous Execution Run, To remove the previous Variables Output from Environment pane do like this:

Syntax : rm(i)

#This will remove the out put of Variables in Environment pane, now we can see only a= 5 Value in Environment Pane.

2. Let’s Look at if else statement :

Here Variable a is assigned to -3 , If Block will enter if Variable a is greater than 0, but here our condition fails so it enters into Else part and prints ” The Variable a is less than 0″

3. If Else If ….. (IF else IF Ladder)

if-else-if ladder

It is similar to if-else statement, here the only difference is that an if statement is attached to else. If the condition provided to if block is true then the statement within the if block gets executed, else-if the another condition provided is checked and if true then  the statement within the block gets executed.

Here in this example, Variable a is less than Variable B and Variable B is less than variable c, so If statement checks every condition and reaches to the last if condition, there the condition is met which is true , so it prints the statement “Practicing If else If ladder in R ” in Console Pane.

4. Nested If

From the above screenshot, we Have tried nested If without Curly Braces .

The first if condition is False ,so it went to next if , the next if condition is True hence the Out put printed is “X is Greater Than z” and print statement is used very next to the If condition so Curly Braces are not required. If you want curly braces, we can add curls braces as well like below :