I have following dataframe named 'Saty' in R
One_Day | Arrived_Date | Departure_Date |
---|---|---|
Yes | 2022-01-10 | NA |
No | 2021-05-12 | 2021-06-01 |
Yes | 2021-12-01 | 2021-12-01 |
Yes | 2022-03-01 | NA |
I want to modify the dataframe, if the One_Day column value is 'Yes', my 'Arrived_Date' and 'Departure_Date' should be same, like below dataframe.
One_Day | Arrived_Date | Departure_Date |
---|---|---|
Yes | 2022-01-10 | 2022-01-10 |
No | 2021-05-12 | 2021-06-01 |
Yes | 2021-12-01 | 2021-12-01 |
Yes | 2022-03-01 | 2022-03-01 |
How to achieve this by coding in R ?
CodePudding user response:
What you need is an ifelse
statement.
library(dplyr)
Saty %>% mutate(Departure_Date = ifelse(One_Day == "Yes", Arrived_Date, Departure_Date))
One_Day Arrived_Date Departure_Date
1 Yes 2022-01-10 2022-01-10
2 No 2021-05-12 2021-06-01
3 Yes 2021-12-01 2021-12-01
4 Yes 2022-03-01 2022-03-01
CodePudding user response:
With the shown data this also works: coalesce
Nevertheless, I am quite sure for your original data you will need an ifelse
statement as @benson23 1 provided, but this is may be also interesting for you:
libray(dplyr)
df %>%
mutate(Departure_Date = coalesce(Departure_Date, Arrived_Date))
One_Day Arrived_Date Departure_Date
1 Yes 2022-01-10 2022-01-10
2 No 2021-05-12 2021-06-01
3 Yes 2021-12-01 2021-12-01
4 Yes 2022-03-01 2022-03-01