Reputation: 121
I have the following tibble:
start_dttm chan
<dttm> <dbl>
1 2018-03-27 23:32:22 5
2 2018-03-27 22:41:24 15
3 2018-03-27 22:41:57 15
4 2018-03-27 22:42:02 15
5 2018-03-27 22:42:48 15
6 2018-03-27 22:42:55 15
7 2018-03-27 22:42:41 15
8 2018-03-27 22:43:04 15
9 2018-03-27 22:43:24 15
10 2018-03-27 22:43:38 15
11 2018-03-27 22:44:16 15
12 2018-03-27 22:44:03 15
The goal is to find time intervals between row within each chan
, i.e. for row 1 I want to get NA, for row 2 -- 33 seconds, for row 3 -- 5 seconds etc. I was thinking of adding an extra column using mutate
that will store the next start_dttm value in this group. In a fashion similar to dplyr::first(start_dttm)
. Any suggestions?
Upvotes: 1
Views: 581
Reputation: 215117
You can group_by chan
and then calculate the difference using lead
:
df %>%
group_by(chan) %>%
mutate(time_diff = lead(start_dttm) - start_dttm)
# A tibble: 12 x 3
# Groups: chan [2]
# start_dttm chan time_diff
# <dttm> <chr> <time>
# 1 2018-03-27 23:32:22 5 NA
# 2 2018-03-27 22:41:24 15 33
# 3 2018-03-27 22:41:57 15 5
# 4 2018-03-27 22:42:02 15 46
# 5 2018-03-27 22:42:48 15 7
# 6 2018-03-27 22:42:55 15 -14
# 7 2018-03-27 22:42:41 15 23
# 8 2018-03-27 22:43:04 15 20
# 9 2018-03-27 22:43:24 15 14
#10 2018-03-27 22:43:38 15 38
#11 2018-03-27 22:44:16 15 -13
#12 2018-03-27 22:44:03 15 NA
Upvotes: 2