Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mutate and if else function to create new column

It may be a very easy question, but so far I failed.

My dataset looks like this

Duration Unit
1 day
3 month
5 weeks

What I want to do is to create a new column for the number of days depending on the unit. So 3 months should be 90 days, 5 weeks should be 35 days. And in case of unit is day, the value of day should be placed in my new column without any calculation.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So the result should look like this

Duration Unit Duration_calculated
1 day 1
3 month 90
5 weeks 35

Here is the exmaple dataset

Duration <- c(1,3,5)    
Unit <- c("day", "month", "weeks")     
dataset <- data.frame(Duration, Unit)    

I’ve tried a combination of mutate and if else function, but it worked not out for me.

>Solution :

We could use case_when():

library(dplyr)

df %>%
  mutate(Duration_calculated = case_when(
    Unit == "day" ~ Duration,
    Unit == "month" ~ Duration * 30,
    Unit == "weeks" ~ Duration * 7
  ))

  Duration  Unit Duration_calculated
1        1   day                   1
2        3 month                  90
3        5 weeks                  35

Or if you stick on ifelse or if_else we could use nested if_else() statement:

df %>% 
  mutate(Duration_calculated = if_else(
  Unit == "day", Duration,
  if_else(Unit == "month", Duration * 30,
          if_else(Unit == "weeks", Duration * 7, NA_real_)
  )
))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading