In my previous article, I gave an overview of variables and data types in R along with some simple examples. If you are not aware of variables and data types in R, then I recommend you to read "Variables And Data Types in R". If you are completely new to R language, then please read "Introduction to R and RStudio". This article is about the conditional statement IF-ELSE statement in R.
IF-ELSE Statement
The If-Else statement is used when we need to perform a particular task based on a condition. The If block executes if the condition is true else the Else block is executed.
Let us take a real-life simple example of a mark sheet and its calculations. Suppose that the passing marks are 40 and the student needs to pass in all the papers to pass. Here, the condition is that the marks should be greater than 40 in order to pass. Else, the student fails.
Run the following code snippet and observe the output.
- #s1 is the marks of the student in subject 1
- s1<-45
- if(s1>40){
- print("PASS")
- }else{
- print("FAIL")
- }
Change the value of s1 to some value below 40 and run the code. You must get the output as "FAIL".
Important Note
If you observed this in the code snippet above, the else block starts immediately after the ending bracket of the if block. Try writing the else block from the next line and you will get an error when you execute the code.
If you observed this in the code snippet above, the else block starts immediately after the ending bracket of the if block. Try writing the else block from the next line and you will get an error when you execute the code.
In the above example, I considered marks of only one subject. In the real world, there would be many subjects and the student must get above 40 in all of them to pass. Even if he/she fails in one subject, the final result should be "FAIL".
Suppose there are three subjects and the student must get above 40 in all the 3 subjects to pass. The R script for this scenario will look like below.
- s1<-45
- s2<-80
- s3<-30
- if(s1>40 & s2>40 & s3>40){
- print("PASS")
- }else{
- print("FAIL")
- }
NESTED IF Statement
At times, we will have to write if statements within if statements. If one if block is executed then the if control within it should be evaluated. Such nesting of if within another if is known as a Nested If statement.

Join the conversation! Your thoughts help the community grow.