R if…else if…else statement

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

R if…else if…else statement

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

Syntax

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

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.