I'd like to create a variable (counter) which counts non-missing values of another variable (firmage0) in every year. My code looks like this:
sort year
quietly by year: gen counter = _n if firmage0 != .
Unfortunately, Stata starts counting with 1 even if there are missing values. But I'd like to start counting when there is a non-missing value. In addition the second nonmissing value should have the value "2", the third "3" and so on. There is one important restriction. Don't use preserve and restore! After creating the variable counter, my dataset looks like this (this is only a small part of it). Free space means missing value!
year firmage0 counter
1975
1975
1975
1975
1975 21 5
1975
1975 60 7
1975
1975
1975
1975
1975
1975
1975
1975
1975
1975
1975
1975
1975 115 20
1975
1975
1975
But the dataset should look like this:
year firmage0 counter
1975
1975
1975
1975
1975 21 1
1975
1975 60 2
1975
1975
1975
1975
1975
1975
1975
1975
1975
1975
1975
1975
1975 115 3
1975
1975
1975