R If Else Statement

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

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

R If Else statement Syntax

The basic syntax of the If Else 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 R If else statement code snippet, If the test condition / Boolean expression present in the above syntax is true, then True code executed. If the expression evaluated to false, then False code executed.

R If Else Statement Flow Chart

The following picture show you the flow chart behind the If Else Statement in R Programming is

R Programming If Else Statement Flow Chart
  • From the R 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 executed irrespective of test results. Because it 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 R Programming.

In this R 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 printed. If the age is less than 18, then 3 and 4 printed as output. Outside the If Else block, we placed one print function 5, and irrespective of the expression result, this message 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

R If Else Statement 2

Comments are closed.