Hello,

I am trying to perform an operation which in Excel or Python would be very easy. However, I have tried different approaches but can't figure out how to do it in Stata.

This is the pattern of my data looks, in reality with many more groups and observations:
Group Counter Deduct Desired Auxiliary Variable Desired Output
A 1 0 0 1
A 2 0 0 2
A 3 1 1 2
A 4 0 1 3
A 5 0 1 4
A 6 0 1 5
A 7 0 1 6
A 8 1 2 6
A 9 0 2 7
A 10 0 2 8
A 11 0 2 9
A 12 1 3 9
B 1 1 1 0
B 2 0 1 1
B 3 0 1 2
B 4 1 2 2
B 5 0 2 3
... ... ... ... ...
The three columns on the left are what I have, the fourth column is a kind of cumulative index which I tried to create in order to reach my desired output as in the fifth column. The fifth column is simply the second minus the fourth column.

My first thought was to write
Code:
gen desired_aux_variable = 0,
replace desired_aux_variable = desired_aux_variable + 1 if deduct ==1 else desired_aux_variable = desired_aux_variable[_n-1]
but then I learned about the difference between if commands and if qualifiers and saw that the latter don't allow for an else statement. I then looked for a way to process the observations line by line but I read that such an approach is very untypical for Stata.

Which other approach can I use in this situation?