I am trying to make an id column using dplyr's group_by and cur_group_id() functions. This goes nicely, however I would like the cur_group_id() to 'restart' based on one of the grouping variables.
Example data:
df <- data.frame(
X = c(1,1,1,1,1,2),
Y = c(1,1,1,2,2,3),
Z = c(1,1,2,3,3,4)
)
# which looks like this
df
X Y Z
1 1 1
1 1 1
1 1 2
1 2 3
1 2 3
2 3 4
My current code and output:
library(dplyr)
library(magrittr)
df %<>%
group_by(X, Y, Z) %>%
mutate(ID = cur_group_id()) %>%
ungroup()
df
X Y Z ID
1 1 1 1
1 1 1 1
1 1 2 2
1 2 3 3
1 2 3 3
2 3 4 4
However, I would like the ID counter to restart as soon as it hits a new value of X like this:
df
X Y Z ID
1 1 1 1
1 1 1 1
1 1 2 2
1 2 3 3
1 2 3 3
2 3 4 1
Is there a way to solve this nicely? Thank you in advance.