Predictive Hacks

R: How To Assign Values Based On Multiple Conditions Of Different Columns


In the previous post, we showed how we can assign values in Pandas Data Frames based on multiple conditions of different columns.

Again we will work with the famous titanic dataset and our scenario is the following:

  • If the Age is NAand Pclass=1 then the Age=40
  • If the Age is NAand Pclass=2 then the Age=30
  • If the Age is NAand Pclass=3 then the Age=25
  • Else the Age will remain as is

Load the Data


url = ''

df = read.csv(url, sep="\t")

Use of case_when function of dplyr

For this task, we will use the case_when function of dplyr as follows:

df<-df%>%mutate(New_Column = case_when( & Pclass==1 ~ 40, & Pclass==2 ~ 30, & Pclass==3 ~ 25,

Let’s have a look at the Age, Pclass and the New_Column that we created.

df%>%select(Age, Pclass, New_Column)
      Age Pclass New_Column
1   22.00      3      22.00
2   38.00      1      38.00
3   26.00      3      26.00
4   35.00      1      35.00
5   35.00      3      35.00
6      NA      3      25.00

As we can see we get the expected results 🙂

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Document Splitting with LangChain

In this tutorial, we will talk about different ways of how to split the loaded documents into smaller chunks using