How can I increment a column when there is a change within a group?
Example data.table:
library(data.table)
dt = data.table(id = c(1,1,1,1,2,2), loc = c(1,1,1,2,1,1), var = c("N","Y","N","N","N","N"))
id loc var
1: 1 1 N
2: 1 1 Y
3: 1 1 N
4: 1 2 N
5: 2 1 N
6: 2 1 N
I would like to group by id and loc and whenever the column var changes I would like to add 1 to a new column.
Desired output:
id loc var V2
1: 1 1 N 1
2: 1 1 Y 2
3: 1 1 N 3
4: 1 2 N 1
5: 2 1 N 1
6: 2 1 N 1