chessosapiens
chessosapiens

Reputation: 3419

Time difference of successive rows in hours in r

I have the following data frame

      id        day total_amount      new
   (int)     (fctr)        (int)   (dfft)
1      1 2015-07-09         1000 105 days
2      1 2015-10-22          100  21 days
3      1 2015-11-12          200  15 days
4      1 2015-11-27         2392  19 days
5      1 2015-12-16          123  NA days
6      6 2015-07-09          200  NA days
7      7 2015-07-09         1000  49 days
8      7 2015-08-27       100018  90 days
9      7 2015-11-25         1000  NA days
10     8 2015-08-27         1000 102 days
11     8 2015-12-07        10000  42 days
12     8 2016-01-18          796  73 days
13     8 2016-03-31        10000  NA days
14    15 2015-09-10         1500  20 days
15    15 2015-09-30         1000  NA days

Following line calculates time difference of successive rows for each group of data:

library(dplyr)
group_by(df, id) %>% mutate(new = as.Date(lead(day)) - as.Date(day))

but it returns the time difference in Day not Hour. How can i change above code to calculate the difference in hours? or any suggestion for new solution.

Upvotes: 0

Views: 197

Answers (1)

Zahiro Mor
Zahiro Mor

Reputation: 1718

try:

mutate(new = as.numeric(difftime(time1 = as.Date(lead(day)),
time2 = as.Date(day), units = 'hours')))

Upvotes: 1

Related Questions