Increase from previous value by condition in R [duplicate]
Increase from previous value by condition in R [duplicate] This question already has an answer here: I was searching for an answer to my specific problem, but I didn't find a conclusion. I have a dataframe with data ID a 1 0 2 0 3 1 4 1 5 1 6 1 7 0 8 1 9 1 10 0 11 1 12 0 13 0 Now i want to add "b" column with number increase from previous b if a == 1 Result like this ID a b 1 0 0 2 0 0 3 1 1 4 1 2 5 1 3 6 1 4 7 0 0 8 1 1 9 1 2 10 0 0 11 1 1 12 0 0 13 0 0 14 1 1 15 1 2 16 1 3 17 1 4 Thanks in advance! This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question. 3 Answers 3 Using dplyr an option can be to group on cumsum(a==0) . This will create a group which got a previous row (if available with a=0 for all rows with a=...