I'm sure this must be a dupe but I just can't get it to work. I want to add an ID col to a data frame, which resets to 1 for each unique value in one column. Best way to describe is by example:
gr1 <- c("A","A","A","B","B","B")
gr2 <- c(1,1,2,3,4,4)
df <- data.frame(gr1, gr2)
Desired output:
id <- c(1,1,2,1,2,2)
df <- cbind(df, id)
The id is marking unique values of gr2 within the each subset of gr1. When gr1 changed from A to B, the id resets to 1. I have read this (Assign an ID based on two columns R) but that is not what I want. I don't want to add a rank function (I think) because by I want my ties all to have the same id within gr1 e.g.
df2 <- df %>% group_by(gr1) %>% mutate(id=rank(gr2, ties.method="max"))
Banging my head against the wall. Any pointers would be a great help.