Hi,

I got a bit of a puzzle problem for one specific application, but I feel an appropriate solution could be useful for other applications.

I have a Dummy-variable, D1, which has, sometimes, several consecutive 1s. D1 depends on the value of var1, and takes value 1 whenever var1 is greater than 0.

I want to generate a second dummy variable, D2, which takes value 1 every time D1 has 5 or more consecutive 1s. So, I want D2 to have value 1, at the start of a D1 succession of 1 values.

Code:
gen D1 = . //gen dummy var
replace D1=1 if var1[_n]>0 // define that D1 is 1, whenever var1 is larger than 0
replace D1=0 if D1== .
replace D1=0 if var1==. // stata places 1s where var1=., so we need to correct
this first part of my code creates something like this

Code:
D2 D1
0    0
0    0
0    0
0    0
0    0
1    1
1    1
1    1
1    1
1    1
1    1
1    1
1    1
1    1
1    1
1    1
0    1
0    1
0    1
0    1
0    0
0    0
0    0
0    0
then, in the second part of my code I want to delete all 1s that are not at the beginning of a succession of D1 1s.

Code:
gen D2 = 0
replace D2=1 if (D1[_n]+D1[_n+1] + D1ndic[_n+2] + D1[_n+3] + D1[_n+4])==5
replace D2=0 if D2[_n-1]==1
However, the code above creates the problem you can see below, where D2 does not just take the value 1 at the beginning of the succession.

Code:
D2   D1
0    0
0    0
0    0
0    0
0    0
1    1
0    1
1    1 // here D2 should have value 0
0    1
1    1 // here D2 should have value 0
0    1
1    1 // here D2 should have value 0
0    1
1    1 // here D2 should have value 0
0    1
1    1 // here D2 should have value 0
0    1
0    1
0    1
0    1
0    0
0    0
0    0
0    0

any suggestions on how to solve this issue?

many thanks!
Christian