[英]Changing specific column values based on conditions in R
I have following dataframe named 'Saty' in R我在 R 中有以下名为“Saty”的数据框
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 列值为“是”,我的“到达日期”和“出发日期”应该相同,如下面的数据框。
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 ?如何通过在 R 中编码来实现这一点?
What you need is an ifelse
statement.你需要的是一个
ifelse
语句。
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
With the shown data this also works: coalesce
使用显示的数据,这也有效:
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:尽管如此,我很确定对于您的原始数据,您将需要@benson23+1 提供的
ifelse
语句,但这对您来说可能也很有趣:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.