let's assume the following dataframe:
df <- tibble(ID = c(12, 12, 12, 13, 13, 13),
times = c(as.POSIXct("2021-01-02 10:00:00"),
as.POSIXct("2021-01-02 11:00:00"),
as.POSIXct("2021-01-02 13:00:00"),
as.POSIXct("2021-01-02 13:00:00"),
as.POSIXct("2021-01-02 14:00:00"),
as.POSIXct("2021-01-02 15:00:00")))
ID times
<dbl> <dttm>
1 12 2021-01-02 10:00:00
2 12 2021-01-02 11:00:00
3 12 2021-01-02 13:00:00
4 13 2021-01-02 13:00:00
5 13 2021-01-02 14:00:00
6 13 2021-01-02 15:00:00
What I want is a column, that considers each timestamp of an ID as start value and computes the number of subsequent observation with the next 2h. So this is my goal:
ID times n_obs_within_2h
<dbl> <dttm> <dbl>
1 12 2021-01-02 10:00:00 2
2 12 2021-01-02 11:00:00 2
3 12 2021-01-02 13:00:00 1
4 13 2021-01-02 13:00:00 3
5 13 2021-01-02 14:00:00 2
6 13 2021-01-02 15:00:00 1
I know that this could be easily done with purrr::map by iterating over each row. However, my original dataset it quite big which makes it fairly unefficient to do so. Can you think of another way than iterating over each row to achieve the computing n_obs_within_2h
EDIT: my current attempt:
df %>% group_by(ID) %>%
mutate(n_obs_with_2h = purrr::pmap_dbl(.l = list(ID, times),
.f = function(i, t, data) {
n <- data %>%
filter(ID == i) %>%
filter(between(as.double.difftime(times-t, units = "hours"),
0, 2)) %>%
nrow()
return(n)
}, data = .))