0

I have a dataframe with two columns departuretime and arrivaltime. I want to compare the arrivatime with the departuretime and in case the arrivaltime is greater than the departuretime, add 1 to it.

departuretime         arrivaltime
<S3: POSIXct>         <S3: POSIXct>
2019-03-04 23:32:00 2019-03-04 03:55:00         
2019-03-05 01:38:00 2019-03-04 05:27:00         
2019-03-04 22:59:00 2019-03-04 06:45:00         
2019-03-04 22:40:00 2019-03-04 00:01:00         
2019-03-04 22:13:00 2019-03-04 00:08:00         
2019-03-04 22:38:00 2019-03-04 00:08:00         
2019-03-05 00:36:00 2019-03-04 04:19:00         
2019-03-04 22:12:00 2019-03-04 00:19:00         
2019-03-04 23:19:00 2019-03-04 02:13:00         
2019-03-04 21:27:00 2019-03-04 00:21:00

I have tried the below code

 mutate(if(departuretime > arrivaltime) {
    arrivaltime = ymd_hms(arrivaltime) + days(1)
  })

But this doesn't seem to make any difference. I'm not sure why.

  • Could you add sample data with `dput`? See [this](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for details. – NelsonGon Jun 17 '20 at 02:06

1 Answers1

0

Use ifelse which is vectorized :

library(dplyr)
library(lubridate)

df %>%
   mutate(arrivaltime = ifelse(departuretime > arrivaltime, 
                           arrivaltime + days(1), arrivaltime))

Or in base R :

transform(df, arrivaltime = ifelse(departuretime > arrivaltime, 
                               arrivaltime + 86400, arrivaltime))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213