• Ekta Aggarwal

IF ELSE in R

Let us say you plan to meet a friend (That friend who usually cancels the plan at the end moment; Yes! That traitor who ditches you at the very last moment!) You always keep a second option with you:

  • Option 1: Meet that friend.

  • Option 2: If the friend doesn't turn up then you will play a video game

  • Option 3: If your friend does not turn up and you don't feel like playing a video game then you will go to sleep.


These what if scenarios are represented by IF-ELSE statements in R.


In R, you can create variables as well as datasets when certain conditions apply.


For this tutorial we shall be leveraging R's mtcars dataset.

View(mtcars)

Using ifelse( ) function:

In R, if you want to create new variable in an already existing dataset then you can simply use ifelse( ) function.


Syntax:

ifelse( Condition to be evaluated, Value if the condition is TRUE, Value if the condition is FALSE)


Let us say I want to create a new variable named 'status' where a car has status = "High Mileage" if that car's mileage(mpg) is more than the average mileage of all the cars.

mtcars$Status = ifelse(mtcars$mpg > mean(mtcars$mpg),"High mileage","Low mileage")


Using Nested ifelse( ):

Suppose you need to have more than 2 conditions to be checked, then we try to have multiple ifelse statements in one single line of code. This is known as nested if-else.


This can be better explained with the help of an example:

Suppose, Status = "High mileage" if a car's mpg is greater than 67th quantile mileage of all the cars,

Status = "Medium mileage" if a car's mpg is between 34th and 67th quantile mileage of all the cars,

Otherwise Status = "Low mileage"

mtcars$Status = ifelse(mtcars$mpg > quantile(mtcars$mpg,0.67),"High mileage",
ifelse(mtcars$mpg > quantile(mtcars$mpg,0.33),"Medium mileage","Low mileage"))

Syntax:

ifelse(Condition 1 , Value when condition 1 is TRUE,

ifelse(Condition 2, Value when condition is FALSE but condition 2 is TRUE, value when both condition 1 and 2 are FALSE))


Basically, you are replacing the part (Value if the condition is FALSE) by an ifelse( ) function.


Note: ifelse( ) function is only used to create variables in only existing dataset or new variables , it is NOT AT ALL USED FOR CREATING NEW DATAFRAMES.


Using if else chunk...


You can create variables and datasets using if-else chunks:


Syntax:

if (condition 1){

### Do something when condition 1 is TRUE

} else{

### Do something when condition 1 is FALSE }


It is not necessary that you always have the else( ) chunk.


In the next set of code, we are creating a status variable using the if-else chunk( ) and for loop.

for(i in 1:nrow(mtcars)){  
if(mtcars$mpg[i] > mean(mtcars$mpg)){  
mtcars$status[i] = "High"  }else{  
mtcars$status[i] = "Low"  }
}

Note: NEVER write it in this way (Following is an incorrect way):

if(condition 1){
#### Do something when condition 1 is TRUE
}
else{
### Do something when condition 1 is FALSE
}

This is because after the '}' of if condition R looks for a else ( ) or else if ( ) keyword in the same line, but providing 'else ( )' in the next line is telling R that there is no else( ) statement.



Creating new datasets using if-else( ) chunk.


Let us say I am doing some computations, I want that when i =1 then the data should be stored in consolidated_data , and in successive iterations the output should get appended by rows in the consolidated_data.

for(i in 1:4){
if(i == 1){
consolidated_data = mtcars} else{
consolidated_data = rbind(consolidated_data ,mtcars) 
}
}


Using Nested ifelse chunk:


When you have multiple conditions to be checked you can use the if - else if- else chunk .


Syntax: if (condition 1){ ### Do something when condition 1 is TRUE } else if(condition 2) { ### Do something when condition 1 is FALSE but condition 2 is TRUE } else { ### Do something when conditions 1 and 2 are FALSE } For eg. The following code will print "Roses smell sweet" because fav_flower has been initialized to "Rose"

fav_flower= "Rose"

if(fav_flower == "Lily"){
  print("Lilies are beautiful")
}else if (fav_flower == "Rose"){
    print("Roses smell sweet")
}else{
    print("You don't have a good taste! :P")
  }

Note: In for loops and if-else ( ) chunks, if you want to print something then you need to mention print( ) keyword explicitly.

Tags: