I am having the following dataset:
DT <- data.drame(v1 = c(0,0,0,1,0,0,1))
From that I just wanted to create an ID cumulatively stopped at a value of 1.
The ID should be
ID<-c(1,2,3,4,1,2,3)
You can simply use ave in base R:
with(DT, ave(v1, c(0, cumsum(v1)[-length(v1)]), FUN = seq_along))
#[1] 1 2 3 4 1 2 3
Or if you want in dplyr also you can use the lag() and with that just create groups and you can assign row numbers in each and every group:
library(dplyr)
DT %>% group_by(gr = lag(cumsum(v1), default = 0)) %>% mutate(ID = row_number())