IF-ELSE-IF statement in R
Last Updated :
05 Nov, 2021
if-else-if ladder in R Programming Language is used to perform decision making. This ladder is used to raise multiple conditions to evaluate the expressions and take an output based on it. This can be used to evaluate expressions based on single or multiple conditions connected by comparison or arithmetic operators. It is particularly useful to check a list of conditions within a single loop.
Syntax:
if(outer-condition is true) {
execute this statement
} else if(inner-condition1 is true) {
execute this statement
} .
.
.
.
else {
execute this statement
}
There can be more than one else if statement in the ladder to check for a lot of conditions at the same time, in this case, it works like a switch. The following code snippets indicate the illustration of the if-else-if ladder.
Example: if-else if-else ladder
R
a <- 'A'
if (a % in % c ( 'E' , 'D' )){
print ( "Block if" )
} else if (a % in % c ( 'A' , 'D' ))
{
print ( "Block else-if" )
} else
{
print ( "Block else" )
}
|
Output
[1] "Block else-if"
Example: if-else if-else ladder
R
var1 <- 6
var2 <- 5
if (var1 > 10 || var2 < 5){
print ( "condition1" )
} else if (var1<7 && var2==5){
print ( "condition2" )
}
|
Output
[1] "condition2"
Example: if-else if-else ladder
R
var1 <- 6
var2 <- 5
var3 <- -4
if (var1 > 10 || var2 < 5){
print ( "condition1" )
} else if (var1<7 && var2==5 && var3>0){
print ( "condition2" )
} else if (var1<7 && var2==5 && var3<0){
print ( "condition3" )
} else {
print ( "condition4" )
}
|
Output
[1] "condition3"
Please Login to comment...