Hi I’m trying to find a solution so that I can achieve the outcome below with a new column that counts the number of occurrences of each group within each id where the first occurrence is the earliest date, and second occurrence is next date of that group, within that id etc. And each group occurrence is specific to each id so each new group within each id should start at 1. I’ve tried several different ways of arrange, group_by, sequence, etc with no luck. Thank you for your help.
dat <- data.frame(
id = c(1, 1, 1, 1, 2, 2, 2, 2),
date = c(
"2020-12-24",
"2020-12-24",
"2020-12-25",
"2020-12-26",
"2020-12-24",
"2020-12-24",
"2020-12-25",
"2020-12-27"
),
group = c("A", "B", "A", "C", "C", "A", "C", "C")
)
dat
id date group
<dbl> <fct> <fct>
1 2020-12-24 A
1 2020-12-24 B
1 2020-12-25 A
1 2020-12-26 C
2 2020-12-24 C
2 2020-12-24 A
2 2020-12-25 C
2 2020-12-27 C
answer <- dat %>%
mutate(order_count = c(1, 1, 2, 1, 1, 1, 2, 3))
answer
id date group order_count
<dbl> <fct> <fct> <dbl>
1 2020-12-24 A 1
1 2020-12-24 B 1
1 2020-12-25 A 2
1 2020-12-26 C 1
2 2020-12-24 C 1
2 2020-12-24 A 1
2 2020-12-25 C 2
2 2020-12-27 C 3