I have the below dataframe:
For Country = Hong Kong or Macau, I need to add 6 hours.
Input
number | indate | country |
---|---|---|
1 | 2020-05-05 7:41:28.277 | Hong Kong |
2 | 2020-05-05 17:41:28.277 | China |
3 | 2020-05-05 19:41:28.277 | Macau |
4 | 2020-05-05 17:41:28.277 | China |
5 | 2020-05-05 17:41:28.277 | USA |
6 | 2020-05-05 22:41:28.277 | Hong Kong |
Desired output:
number | indate | country | indate1 |
---|---|---|---|
1 | 2020-05-05 7:41:28.277 | Hong Kong | 2020-05-05 13:41:28.277 |
2 | 2020-05-15 17:41:28.277 | China | 2020-05-15 17:41:28.277 |
3 | 2020-05-12 19:41:28.277 | Macau | 2020-05-13 01:41:28.277 |
4 | 2020-05-25 17:41:28.277 | China | 2020-05-25 17:41:28.277 |
5 | 2020-05-05 17:41:28.277 | USA | 2020-05-05 17:41:28.277 |
6 | 2020-05-13 22:41:28.277 | Hong Kong | 2020-05-14 04:41:28.277 |
Below is the code I have written:
library(lubridate)
hour_addition = function(dataf) {
country = dataf[3]
date= dataf[2]
if (country == 'Hong Kong' | country = 'Macau'){
date=as_datetime(date)
date1 = date+dhours(6)
date1 = as.character(date1)
} else {
date1 = date
}
return (date1)
}
new_date = apply(df,1,hour_addition)
df$indate1=new_date
I am not getting the desired results, Thanks in Advance. :)