Else if statement in R

To test the different conditions this statement is used in single if….. Else if statement in R. This statement is followed by an optional else if…. Else. This is a conditional programming statement also known as a nested if-else statement. There are some points that are mandatory to understand when we are using the if…..else if…..else statement.

These points are mentioned below:

  • if statement can have either zero or one else statement and it must come after any else if’s statement.
  • if statement can have many else if’s statement and they come before the else statement.
  • Once an else if statement succeeds, none of the remaining else if’s or else’s will be tested.

The generic syntax of the else if statement in R is mentioned below:

Flow Chart of Else if statement in R

Else if statement in R
Flow Chart of Else if statement in R

Following are some examples of else if statements working and performing a particular task in R.

The following example will decide the position of students using the marks.

m=76;  
if(m>75){  
    print("Excellent")  
}else if(m>65){  
    print("Good")  
}else if(m>55){  
    print("Average")  
}else{  
    print("Fail")  
}  

Output:

else1 1

The following example will check the largest number based on condition.

n1=4  
n2=87  
n3=43  
n4=74  
if(n1>n2){  
    if(n1>n3&&n1>n4){  
        largest=n1  
    }  
}else if(n2>n3){  
    if(n2>n1&&n2>n4){  
        largest=n2  
    }  
}else if(n3>n4){  
    if(n3>n1&&n3>n2){  
        largest=n3  
    }  
}else{  
    largest=n4  
}  
cat("Largest number is =",largest)  

Output:

else4