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.
>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_)
)
))