Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: generate variable equal to first non-zero value in row


From   "Eric A. Booth" <[email protected]>
To   [email protected]
Subject   Re: st: generate variable equal to first non-zero value in row
Date   Wed, 21 Aug 2013 10:39:01 -0500

<>
Some possible approaches:

clear
inp id      out1    out2    out3    out4    out5
1       0       0       0       2       2       2
2       0       2       2       0       0       2
3       0       0       0       0       0                             .
4       4       4       4       0       0       4
5       3       0       2       2       2       3
6       0       4       4       4       0       4
end

g first_nonzero = 0

forval v = 1/5 {
replace first_nonzero = out`v' if out`v'!=0 & first_nonzero == 0
}


recode out1-out5 (0=.)
egen first_nonzero2 = rowfirst(out1-out5)
recode out1-out5 first_nonzero2 (.=0)

assert first_nonzero == first_nonzero2


- Eric


On Wed, Aug 21, 2013 at 10:25 AM, D-Ta <[email protected]> wrote:
> Dear Statausers,
>
> I have a dataset with the variables id and and out1-out5 where the "out"
> variables represent sequential outcomes. I would like to generate a variable
> (in the example below named first_nonzero) which indicates the first outcome
> in the sequence row that is non zero. If there are all zeros throughout,
> that indicator variable should be set/remain missing.
>
> The following table illustrateswhat I am trying to do. How do I generate the
> first_nonzero variable? (I was trying to work with the -egenmore- commands,
> but couldnt figure out).
>
> id      out1    out2    out3    out4    out5    first_nonzero
> 1       0       0       0       2       2       2
> 2       0       2       2       0       0       2
> 3       0       0       0       0       0                             .
> 4       4       4       4       0       0       4
> 5       3       0       2       2       2       3
> 6       0       4       4       4       0       4
>
>
> Many thanks,
> Darjusch
> *
> *   For searches and help try:
> *   http://www.stata.com/help.cgi?search
> *   http://www.stata.com/support/faqs/resources/statalist-faq/
> *   http://www.ats.ucla.edu/stat/stata/
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index