My data looks something like this:
id <- c(1,1,1,1,1,1,1,1,2,2,2,2,2,2)
var1 <- c(1,2,2,3,4,4,4,4,1,1,2,2,2,3)
var2 <- c(1,2,2,2,2,3,4,4,1,1,1,2,2,2)
df <- data.frame(id,var1,var2)
Which would look like this:
id var1 var2
1 1 1
1 2 2
1 2 2
1 3 2
1 4 2
1 4 3
1 4 4
1 4 4
2 1 1
2 1 1
2 2 1
2 2 2
2 2 2
2 3 2
I would like to create a new column which increments by 1 for each change in either var1 or var2 and resets for each id. So my desired output would be:
id var1 var2 var3
1 1 1 1
1 2 2 2
1 2 2 2
1 3 2 3
1 4 2 4
1 4 3 5
1 4 4 6
1 4 4 6
2 1 1 1
2 1 1 1
2 2 1 2
2 2 2 3
2 2 2 3
2 3 2 4
I tried multiple things I found here, but nothing does exactly what I am looking for. For example both:
DT <- as.data.table(df, keep.rownames = T)
DT[, var3 := .GRP, by = list(id, var1, var2)][]
or
indx <- as.character(interaction(df[c("id", "var1", "var2")]))
df$var3<- cumsum(c(TRUE,indx[-1]!=indx[-length(indx)]))
do not reset for a new subject. I appreciate your help.