Rodrigo
Rodrigo

Reputation: 69

Stata: looping over observations

My data set looks like this

x1
1  
0
0
1
0
0
1
1

In this data set the values following 1 belongs to the same group. For example the first 2 zero belong to group 1 and the second 2 zeros belong to the second group an so on. And I would like to get a final output similar to this. Note that the delta between the two 1's is arbitrary:

x1 x2
1  1
0  1
0  1
1  2
0  2
0  2
1  3
1  4

I think I need to write a loop that goes over the observations. But I cannot figure out the logical statements that will accomplish this.

Upvotes: 0

Views: 2163

Answers (1)

Nick Cox
Nick Cox

Reputation: 37208

Either

gen x2 = sum(x1) 

or

gen x2 = sum(x1 == 1) 

is sufficient. There is a loop over observations tacit as usual there, but you don't need an explicit loop.

In detail, sum() here is a cumulative or running sum. In your case, the first solution is simple and adequate. The reason for mentioning the second solution is because it's more general: we can tag the first observation in each block or spell with 1 and then create a running sum to form blocks of 1s, 2s, and so forth.

Upvotes: 1

Related Questions