Conditional statements in R

Filed Under: R Programming

To advance with programming, we need to be able to control the flow of the program execution. This controlling happens based upon certain logical conditions. When a condition is met, we expect the program to behave in a certain way, and when a condition is not met, we steer the program in a different way. This is established by means of if else statements in R like several other programming languages.

If Statement in R

R supports several variants of conditional statements like stand-alone if, if with else, nested if and switch. We will explore one by one in this tutorial. The basic structure of an if block is as follows.

if (condition) {
#Code to execute if condition is met
} #This code only works if the condition is true.

Let us illustrate this with a simple example.

if (a<=5) {
print(a^2)
}

The above code simply checks if a value is less than or equal to 5, and if the condition holds good, it prints the squared value of the number. Let us execute this with a value of 3.

[1] 9

If Else Statements in R

When you run this code with a value 6 or 7, you will observe that nothing will be printed at all. This is because we haven’t handled the case where the condition could be false. This is exactly why else blocks are used.

Let us try the above if code snippet with an else block now. Do not forget adding a space between else keyword and the opening brace {.

if(a<=5){
print(a^2)
}
else {
print(a*2)
}

For a value 5, the above program runs the code within the if-block and gives an output 25. However, when a value greater than 5 is given to a, say for example 9, a is multiplied by 2 as specified in the else block.

Ifelse Statement in R

R also has a special construct named ifelse. When you wish to evaluate a condition against every element of the vector, ifelse construct gives a lot of flexibility. We will explore R vectors in detail later, but for now, we will simply define a small vector of 6 numbers as follows.

myvector=c(4,1,6,7,0,4)

Now we wish to divide 100 by each element of the vector and display a result. However, we know that division by 0 gives an error, so we want to handle it in our code. If we write a simple conditional statement using if, the problem is that we don’t know which position in the vector has a zero. The ifelse construct proves very useful in this case.

The division can be achieved as follows.

division <- ifelse(test=myvector==0,yes=NA,no=100/myvector)

This piece of code tests a condition of whether the particular element of myvector is a 0. If it is, the result is populated with an NA value. Else the division is carried out. Let us now check the division result.

> division
[1]  25.00000 100.00000  16.66667  14.28571        NA  25.00000

Nested If Else Statements in R

R also supports nesting of if statements within another block. When we wish to check multiple conditions hierarchically dependent on each other, this construct helps.

We want to check is a number is less than 10 first, then check if it is an even number. Look at the following code that aims to do this.

if(a<10){
print("A is less than 10")
   if(a%%2==0){
   print("A is even")
   }
   else {
   print("A is odd")
   }
}

When a is supplied with a value 4, the following result is produced.

[1] "A is less than 10"
[1] "A is even"

Stacked If Else Blocks

We can also stack if-else blocks in the following manner to handle complex logical scenarios.

if(a<5){
print("Grade is C")
}else if(a>=5&a<10){
print("Grade is B")
}else if(a>=10&a<20){
print("Grade is A")
}else {
print("Invalid marks")
}

Switch Statement in R

Finally, we have a special case of conditional statement called switch. If we need to produce an output that is specific to a single variable, switch will prove useful. Without switch we need to write a complicated stack of if blocks.

Consider an example where we need to fill out a code based upon the “favoritesport” column in the dataset. Cricket gets CR, Football gets FB, Hockey gets HK, Badminton gets BD and Tennis gets TN. This can be easily handled by a switch statement below.

code = switch(EXPR=fx,Cricket='CR',Football='FB',Hockey='HK',Badminton='BD',Tennis='TN')

Let us set fs to “Cricket” and see what out code displays for us.

fs <- 'Cricket'
code = switch(EXPR=fx,Cricket='CR',Football='FB',Hockey='HK',Badminton='BD',Tennis='TN',NA)
code
[1] "CR"

Look how the switch statement converts the given value to the corresponding code easily. The EXPR here stands for the variable that we wish to switch. Also, NA given as the final option in the switch block is for handling invalid inputs.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages