Else if statement or Nested if-else statement in R:

Multiple conditions can be tested in a single code using the nested if-else statement. The important considerations are:

  • There can be either no “else” statement or one “else” statement associated with an “if “statement.
  • The “else” statement must come after any “else if” statement.
  • “if” statements can have many “else if” statements.
  • The “else if” statements come before the “else” statement.
  • The “else if” statements or “else” statement is tested only till one of the “else if” statement succeeds.

Syntax:

if(boolean_expression 1) {  
   // Execute this code if this condition is true.  
} else if( boolean_expression 2) {  
   // Execute this code if this condition is true.  
} else if( boolean_expression 3) {  
   // Execute this code if this condition is true.  
} else {  
   // Execute this code if all the conditions are false  
}

Example 1:

x <- 1000
y <- 800
 
if (y > x) {
  print("y is greater than x")
} else if (x == y) {
  print("x and y are equal")
} else {
  print("x is greater than y")
}

Output:

[1] "x is greater than y"

Example 2:

age <- 20
if(age<18) { 
    print("Not Eligible")  
}else if(age>30){  
    print("Not Eligible")  
}else { 
    print("Eligible")  
    }

Output:

[1] "Eligible"

Example 3:

Percentage = 55;  
if(Percentage>70){  
    print("First Rank")  
}else if(Percentage>60){  
    print("Second Rank")  
}else if(Percentage>50){  
    print("Third Rank")  
}else{  
    print("Fail")  
}

Output:

[1] "Third Rank"

Example 4:

cat("Choice 1: SUM = 200+300 \n")  
cat("Choice 2: SUBTRACTION = 200-300 \n")    
cat("Choice 3: PRODUCT = 200*300 \n")  
cat("Choice 4: DIVISION = 200/300 \n")
x <- 200
y <- 300 
choice <- 2  
if(choice==1){  
    sum <-(x+y)  
    cat("\nSUM =",sum)  
}else if(choice==2){  
    sub<-(x-y)  
    cat("\nSUBTRACTION =",sub) 
}else if(choice==3){  
    mul<-x*y  
    cat("\nPRODUCT =",mul) 
}else if(choice==4){  
    div<-x/y  
    cat("\nDIVISION =",div)   
}else{  
    cat("Wrong Option!!")  
}

Output:

Choice 1: SUM = 200+300 
Choice 2: SUBTRACTION = 200-300 
Choice 3: PRODUCT = 200*300 
Choice 4: DIVISION = 200/300 
 
SUBTRACTION = -100

Example 5:

num1 = 9  
num2 = 88  
num3 = 303  
num4 = 555  
num5 = 201 
if(num1>num2){  
    if(num1>num3 && num1>num4 && num1>num5){  
        max_num = num1  
    }  
}else if(num2>num3){  
    if(num2>num1 && num2>num4 && num2>num5){  
        max_num = num2  
    }  
}else if(num3>num4){  
    if(num3>num1 && num3>num2 && num3>num5){  
        max_num = num3  
    }  
}else if(num4>num5){  
    if(num4>num1 && num4>num2 && num4>num3){  
        max_num = num4  
    } 
}else{  
    max_num = num5  
}  
cat("The largest number among 9, 88, 303, 555, 201 = ",max_num)

Output:

The largest number among 9, 88, 303, 555, 201 = 555
Content Protection by DMCA.com