If-else statement in R

Another type of decision-making statement is an if-else statement. If-else statement in R is the if statement followed by an else statement. Else statement will be executed when the Boolean expression will false. In short, if a Boolean expression comes true, then the, if segment gets executed otherwise the else block, will get executed.

Any non-zero and non-null values in R programming are treated as true. Whilst the value is either zero or null, then it will be treated as false.

The generic syntax of the if-else statement in R is as follow:

Flow Chart of If-else statement in R

Flow Chart of If-else statement in R
Flow Chart of If-else statement in R

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

The following example will check the first condition if it is true it will print the message and if the condition is false it will run else block.

num <- 22
cat("The value of num is", num , "\n")  

if(num<10){  
 
cat("num is less than 10")  
}else{  

cat("num is greater than 10")  
}  

Output:

ie1 2

The following example will check the first condition if it is true it will print the message and if the condition is false it will run else blocks. the same process will be done with the second condition.

a<- 22
cat("The value of a is", a , "\n") 

if(a<50){  
cat("a is less than 50")  
if(a%%2==0){  
cat(" and even\n")  
}  
else{  
cat(" but not even\n")  
}  
}else{  
cat("a is greater than 50")  
if(a%%2==0){  
cat(" and even\n")  
}  
else{  
cat(" but not even\n")  
}  
}  

Output:

ie2 1

The following example will check the first condition if it is true it means a character is a vowel and if the condition is false it will run else that character is a constant.

a<- 'E'  
if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u'||a=='A'||a=='E'||a=='I'||a=='O'||a=='U'){  
cat("character is a vowel\n")     
}else{  
cat("character is a constant")  
}  
cat("character is =",a)  

Output:

ie4 1