I have a data frame like this named \'a\'.
ID V1
1 -1
1 0
1 1
1 1000
1 0
1 1
This should work:
a %>% group_by(ID) %>% mutate(V2 = ifelse(row_number() == 1, 1, 0) +
ifelse(row_number() > 1 & V1 <= 1000, 1, 0) +
cumsum(ifelse(V1 >= 1000, 1, 0)))
Update: Changed second ifelse logic statement from row_number() > 1 & V1 < 1000 to that shown above. This alteration should give the results as requested in the comments.