Dear Listers,

I have a dataset which looks like

id es1 es2 es3 es4 es5 es6 es7 es8 es9
1 1 1 1 1 1 1 1 0 0
2 1 0 0 1 1 1 0 0 0
3 1 1 0 0 1 0 0 0 0

id is each individual.
es1-9 indicate the employment status in each year (from year 1 to year 9). It is 1 if this individual is employed, 0 otherwise.

I want to count the number of years in each unemployment spell for each individual.
For example, individual 1 (id=1) has one unemployment spell, which has 2 years (es8 and es9).
Individual 2 (id=2) has two unemployment spells, which are 2 years (es2, es3) and 3 years (es7,8,9) respectively.

Here is my code

input id
es1 es2 es3 es4 es5 es6 es7 es8 es9
1 1 1 1 1 1 1 1 0 0
2 1 0 0 1 1 1 0 0 0
3 1 1 0 0 1 0 0 0 0
end

*keep if id==2

foreach x of numlist 1/8{
local X = `x'+1
gen dif`x'=var`X'-var`x'
}
gen dif9=.

foreach x of numlist 1/8{
gen count`x'=1
if dif`x'~=-1{
replace count`x'=.
}
else if dif`x'==-1{
local X =`x'+1
while dif`X'==0{
replace count`x'=count`x'+(dif`X'==0)
local X = `X'+1
}
}
}

The variables "count1-8" give me the number of years in each unemployment spell. The problem is that my code works only when I keep one observation. For example, I have to write "keep if id==2" before running the code, then variables count1-8 give me the right results for individual#2. Similarly, if I want to look at individual#3, I need to write
"keep if id==3".
Could you please tell me how to make the loop to work for all individuals? I have 20000 individuals in my dataset. It is impossible to run the code for each of them, and record the results one by one.

Thank you!