The R If Else Statement is an extension to 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 execute the statements only when the given condition is true. If the condition is false, it will not execute any statement.
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 statement executes the statements.
R If Else statement Syntax
The basic syntax of the If Else in R Programming language is:
if (Boolean_Expression) { #If the Boolean_Expression result is TRUE, these statements will be executed True statements } else { #If the Boolean_Expression result is FALSE, these statements will be executed False statements }
From the above If else statement code snippet, If the test condition / Boolean expression present in the above syntax is true, then True statements executed. If the condition is false, then False statements executed.
R If Else Statement Flow Chart
The following picture show you the flow chart behind the If Else Statement in R Programming is
- From the R If else flow chart, If the test condition is true, STATEMENT 1 is executed, followed by STATEMENT N.
- If the condition is False, then STATEMENT 2 is executed, followed by STATEMENT N. Here, STATEMENT N 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 statements. 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 Statement article.
# R IF Else Statement Example my.age <- as.integer(readline(prompt="Please Enter your Age: ")) if (my.age > 18) { print("You are eligible to Vote.") # Statement 1 print("Don't forget to carry Your Voter ID's to Polling booth.") #Statement 2 } else { print("You are NOT eligible to Vote.") #Statement 3 print("We are Sorry") #Statement 4 } print("This Message is from Outside the IF ELSE STATEMENT") #Statement 5
The user enters his/her age. If the age is greater than or equal to 18, Statement 1, Statement 2 printed. If the age is less than 18, then Statement 3 and Statement 4 printed as output. Outside the If Else block, we placed one print statement (Statement 5), and irrespective of condition result, this statement executed.
OUTPUT 1: Let us enter the age of 32. Condition is TRUE
Let us enter age = 17 to fail the condition. Condition is FALSE
Comments are closed.