| |
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]
st: re: first non-zero observation within a variable
Thomas said
I am trying to tag the first non-zero, non-missing observation within a
variable by group. The goal is to drop anything BEFORE the expression
is measured within a group. For example:
group time expression
1 1 0
1 2 0
1 3 3.2
1 4 4.1
1 5 0
1 6 2.5
2 1 0
2 2 .
2 3 0
2 4 3.7
2 5 4.0
..
My goal is to obtain this:
group time expression
1 3 3.2
1 4 4.1
1 5 0
1 6 2.5
2 4 3.7
2 5 4.0
tsset group time
tsspell var3,cond((var3>0 | var3[_n-1]>0) & var3<. & var3[_n-1]<.)
keep if _spell
This works on the example given. It might have problems with a run of
embedded zeros, but it would be possible to deal with that case by
testing whether a spell was detected before that point (running sum
of _spell > 0). For instance if the data are
+---------------------+
| group time var3 |
|---------------------|
1. | 1 1 0 |
2. | 1 2 0 |
3. | 1 3 3.2 |
4. | 1 4 4.1 |
5. | 1 5 0 |
|---------------------|
6. | 1 6 0 |
7. | 1 7 0 |
8. | 1 8 2.5 |
9. | 2 1 0 |
10. | 2 2 . |
|---------------------|
11. | 2 3 0 |
12. | 2 4 3.7 |
13. | 2 5 4 |
+---------------------+
tsset group time
tsspell var3,cond((var3>0 | var3[_n-1]>0) & var3<. & var3[_n-1]<.)
by group: gen sumspell=sum(_spell)
keep if _spell | sumspell>0
produces
+-------------------------------------------------------+
| group time var3 _seq _spell _end sumspell |
|-------------------------------------------------------|
1. | 1 3 3.2 1 1 0 1 |
2. | 1 4 4.1 2 1 0 2 |
3. | 1 5 0 3 1 1 3 |
4. | 1 6 0 0 0 0 3 |
5. | 1 7 0 0 0 0 3 |
|-------------------------------------------------------|
6. | 1 8 2.5 1 2 1 5 |
7. | 2 4 3.7 1 1 0 1 |
8. | 2 5 4 2 1 1 2 |
+-------------------------------------------------------+
taking account of the run of zeros in group1 after a spell has started.
tsspell is available from SSC.
Kit Baum, Boston College Economics
http://ideas.repec.org/e/pba1.html
An Introduction to Modern Econometrics Using Stata:
http://www.stata-press.com/books/imeus.html
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/