2

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.

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.

zx8754
  • 52,746
  • 12
  • 114
  • 209
USER12345
  • 45
  • 5

2 Answers2

3

Make a lookup vector, then match:

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

lookup <- setNames(c(1, 7, 30.437), c("day", "week", "month"))

dataset$Duration_calculated <- dataset$Duration * lookup[ dataset$Unit ]

dataset
#   Duration  Unit Duration_calculated
# 1        1   day               1.000
# 2        3 month              91.311
# 3        5  week              35.000
zx8754
  • 52,746
  • 12
  • 114
  • 209
1

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_)
  )
))
TarJae
  • 72,363
  • 6
  • 19
  • 66