Dear Stata community members,

I have created a count variable k and p based on the following syntax :
by ID Illness (Year), sort: gen k = _n

by ID Illness Year (k), sort: replace k = k[1]

by ID ClassofIllness (Year), sort: gen p = _n

by ID ClassofIllness Year (p), sort: replace p = p[1]

----------------------- copy starting from the next line -----------------------
Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input str23 ID str10 Illness float(YearofContracting DosageOfAntibiotic ClassofIllness k k1 p p1)
"Patient 1" "Malaria"    2001 100 1 1 1  1 1
"Patient 1" "Typhoid"    2001  15 1 1 1  1 1
"Patient 1" "Typhoid"    2002  26 1 2 2  3 3
"Patient 1" "Common flu" 2003   0 1 1 0  4 0
"Patient 1" "Allergy"    2004  26 1 1 1  5 4
"Patient 1" "Allergy"    2004  10 1 2 2  5 5
"Patient 1" "Allergy"    2005   0 1 3 0  7 0
"Patient 1" "Common flu" 2006   0 1 2 0  8 0
"Patient 1" "Common flu" 2007   0 1 3 0  9 0
"Patient 1" "Common flu" 2008   0 1 4 0 10 0
"Patient 1" "Common flu" 2009   0 1 5 0 11 0
"Patient 1" "Common flu" 2010   0 1 6 0 12 0
"Patient 1" "Allergy"    2012   9 1 4 3 13 6
"Patient 1" "Typhoid"    2013  18 1 3 3 14 7
"Patient 1" "Malaria"    2014  13 1 2 2 15 8
"Patient 1" "Allergy"    2015   0 1 5 0 16 0
"Patient 1" "Common flu" 2016  60 1 7 1 17 9
end
------------------ copy up to and including the previous line ------------------



However, the issue is, I want to have the counter as shown in k1 and p1. That is,
The row where dosageofantibiotics==0 , the counter should put the value as zero. The next time (as per the bysort conditions) the counter should pick from where it left before the zero (as per the bysort conditions).

Please help.
Regards.