R if else if

In this tutorial, we shall learn about R if…else if…else statement, its Syntax and the Execution Flow in and around the if…else if…else statement with an R Example Script.

if…else if…else statement is an extension of R if…else block. So, if the condition provided to the if statement is true, then the statements in the if statement block are executed, else another R if…else statement is evaluated. You may append as many number of if…else statement one to each other.

Following is a flow diagram depicting the flow of execution around and in an if..else if…else statement.

R if...else if...else statement
ADVERTISEMENT

Syntax – If – Else If

The syntax of if-else-if statement is

if(boolean_expression){
     if_block_statements
 } else if(boolean_expression_1) {
     if_block_1_statements
 } else if(boolean_expression_1) {
     if_block_2_statements
 }
 .
 .
 else {
     else_block_statements
 }

The boolean_expression is any expression that evaluates to a boolean value. And if the boolean value = TRUE, execution flow enters the if block, else execution flow enters the next R if…else block.

Last else block is optional. But if you want any default code to be run in case any of the above if blocks do not execute, else block would serve as default block.

Example 1 – R If Else If

In this example, we will write an if-else-if statement. If block whose condition becomes true will be executed.

r_if_else_if_else_example.R

# R if...else if...else statement Example

b = 7

if(b==6){
	print ("Condition b==6 is TRUE")
} else if(b==7){
	print ("Condition b==7 is TRUE")
} else if(b==8){
	print ("Condition b==8 is TRUE")
} else{
	print ("No if condition is TRUE for b")
}

Output

$ Rscript r_if_else_if_else_example.R 
[1] "Condition b==7 is TRUE"

Conclusion

In this R Tutorial, we learnt about R if…else if…else statement, its Syntax and the Execution Flow in and around the if…else statement with an R Example Script.