R If Else Statement

The R If Else Statement is an extension of the If Statement. Let us see how to use this IF Else Statement in real-time with an example. We know that the If Statement executes the code only when the given condition is true. If the condition is false, it will not execute any code block.

It would be nice to execute something in the real world when the condition fails. To do so, we can use this If else. Here, When the condition fails, the Else block executes the code.

If Else Syntax

The basic syntax of the If Else statement in R Programming language is:

if (Boolean_Expression)  {
     # The Boolean_Expression result is TRUE, these will be executed
     True code
} else  {
     # The Boolean_Expression result is FALSE, these will be executed
     False code
}

From the above If else statement code snippet, If the test condition / Boolean expression present in the above syntax is true, then the True code is executed. If the expression is evaluated as false, then a False code is executed.

R If Else Statement Flow Chart

The following picture shows you the flow chart behind the If Else Statement is

Flow Chart
  • From the If else flow chart, If the test condition is true, STATEMENT1 is executed, followed by STATEMENTN.
  • If the condition is False, then STATEMENT2 is executed, followed by STATEMENTN. Here, STATEMENTN is executed irrespective of test results. Because it is placed outside of the If Else condition block, it has nothing to do with the condition result.

R If Else Statement Example

This program allows the user to enter their age, and it checks whether they are eligible to vote or not using the if else statement in this Programming.

In this if else statement program, we are going to place 4 different print messages. If the condition is true, we will print two different statements. If the condition is false, we will print another two statements. Please refer to the If condition article.

my.age <- as.integer(readline(prompt="Please Enter your Age: "))

if (my.age > 18) {
  print("You are eligible to Vote.") # 1
  print("Don't forget to carry Your Voter ID's to Polling booth.") # 2
} else {
  print("You are NOT eligible to Vote.") # 3
  print("We are Sorry") # 4
}
print("This Message is from Outside") # 5

The user enters his/her age. If the age is greater than or equal to 18, 1 and 2 are printed. If the age is less than 18, then 3 and 4 are printed as output. Outside the If Else block, we placed one print function 5, and irrespective of the expression result, this message was executed.

OUTPUT 1: Let us enter the age of 32. expression result is TRUE

R If Else Statement 1

Let us enter age = 17 to fail the condition. So, it is FALSE.

If Else example 2

Comments are closed.