R. R.
R. R.

Reputation: 33

Find time difference in minutes in data frame and add is as a column

First, I want to find the time difference between tm2 and tm1 in minutes in the following data frame (sometimes overnight as in row 2).

dat1 <- data.frame(id=1:2, tm1=c("01:00","23:00"), tm2=c("05:00","03:00"))

Data frame

Second, I will add it to the data frame "dat1" as an extra column called time_diff.

Upvotes: 0

Views: 90

Answers (3)

G. Grothendieck
G. Grothendieck

Reputation: 269441

Convert the times to POSIXct, subtract them, convert that to doubles as minutes and take it modulo 24 * 60 since we presume that the unstated assumption is that tm2 always comes after tm1. No packages are used. Alternately we could use hm from lubridate in place of to_ct.

to_ct <- function(x) as.POSIXct(x, format = "%H:%M")
transform(dat1, time_diff = as.double(to_ct(tm2) - to_ct(tm1), "mins") %% (24 * 60))

giving:

  id   tm1   tm2 time_diff
1  1 01:00 05:00       240
2  2 23:00 03:00       240

Upvotes: 1

Elk
Elk

Reputation: 532

If your times might be from different days, then there is no way that R can know this without also supplying a date.

library(dplyr)
library(lubridate)

dat1  <- data.frame(tm3 = parse_date_time(c("2020-05-15 01:00",
                                        "2020-05-15 23:00"), 
                                      '%Y-%m-%d %H:%M'),
                    tm4 = parse_date_time(c("2020-05-15 05:00",
                                        "2020-05-16 03:00"), 
                                      '%Y-%m-%d %H:%M'))

Give you:

> dat1
                  tm3                 tm4 time_diff
1 2020-05-15 01:00:00 2020-05-15 05:00:00  240 mins
2 2020-05-15 23:00:00 2020-05-16 03:00:00  240 mins

Upvotes: 0

Yingjie
Yingjie

Reputation: 48

here you go

library(dplyr)

dat2 <- dat1 %>% 
  mutate(
    tm1 = as.POSIXlt(tm3, format="%H:%M"),
    tm2 = as.POSIXlt(tm4, format="%H:%M"),
    time_diff = difftime(tm2, tm1, units='mins'))

Upvotes: 0

Related Questions