Это то, что вы ищете?
library(tidyverse)
df <-
tibble(
ID = c(1, 2, 1, 1, 2, 2, 1),
Timestamp = c(1528362158, 1534675468, 1534675492, 1534675748, 1534675939, 1534676003, 1534676067),
Binary = c(0, 1, 1, 0, 0, 1, 1)
)
df %>%
group_by(ID) %>%
mutate(rn = row_number()) %>%
spread(Binary, Timestamp) %>%
fill(`0`, .direction = 'down') %>%
drop_na() %>%
mutate(Duration = `1` - `0`) %>%
summarise(Duration = sum(Duration))
Результат:
ID Duration
<dbl> <dbl>
1 1 6313653
2 2 64