How do you reset a sequential count in R?

Viewed 96

I'm grouping time data and adding a sequential count... so first set of times is 1, second set 2, etc. This works as expected:

df %>%
  group_by(time) %>% 
  mutate(seq = cur_group_id()) %>% 
  ungroup()

I would like to be able to group by date and time, and have the count reset when a new date is reached like this:

tribble(
  ~date, ~time, ~seq,
  "01/01/21",  "11:00", 1,
  "01/01/21",  "11:00", 1,
  "01/01/21",  "12:00", 2,
  "01/01/21",  "12:00", 2,  
  "01/01/21",  "1:00", 3,
  "01/01/21",  "1:00", 3, 
  "02/01/21",  "10:00", 1,
  "02/01/21",  "10:00", 1
)

Thank you.

1 Answers

We can group by 'date' and use match on the unique elements of 'time'

library(dplyr)
df %>%
  group_by(date) %>% 
   mutate(seq = match(time, unique(time))) %>% 
   ungroup()

-output

# A tibble: 8 x 3
#  date     time    seq
#  <chr>    <chr> <int>
#1 01/01/21 11:00     1
#2 01/01/21 11:00     1
#3 01/01/21 12:00     2
#4 01/01/21 12:00     2
#5 01/01/21 1:00      3
#6 01/01/21 1:00      3
#7 02/01/21 10:00     1
#8 02/01/21 10:00     1
Related