R If Else

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

if…else statement is an extension of if statement with an else block. So, if the condition provided to the if statement is true, then the statements in the if statement block are executed, else the statements in the else block are executed.

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

R if else

Syntax – R if-else

The syntax of R if else statement is

</>
Copy
if(boolean_expression){
     if_block_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 else block.

Example 1 – R If-Else

In this example, we will write two if-else statements. For the first if-else statement, the condition evaluates to TRUE and therefore if block will be executed. For the second if-else statement, the condition evaluates to FALSE and therefore else block will be executed.

r_if_else_example.R

</>
Copy
# R if..else statement Example

# for TRUE condition
a = 6

if(a==6){
	print ("Condition a==6 is TRUE")
	print ("This is second statement in if block")
} else{
	print ("Condition a==6 is FALSE")
	print ("This is second statement in else block")
} 

# for FALSE condition
b = 7

if(b==6){
	print ("Condition b==6 is TRUE")
	print ("This is second statement in if block")
} else{
	print ("Condition b==6 is FALSE")
	print ("This is second statement in else block")
}

Output

$ Rscript r_if_else_example.R 
[1] "Condition a==6 is TRUE"
[1] "This is second statement in if block"
[1] "Condition b==6 is FALSE"
[1] "This is second statement in else block"

Conclusion

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