Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: something on ado


From   Ulrich Kohler <[email protected]>
To   [email protected]
Subject   Re: st: something on ado
Date   Fri, 24 Oct 2003 13:26:19 +0200

Your syntax is Stata 6 but your output looks more like  Stata 8. Loops in 
Stata 8 are much easier done with  -foreach- and/or -forvalues-.

In Stata 8 your "program" would read:

egen sum = rsum(x*) 
foreach var of varlist x* {
	gen p`var' = `var'/sum
}

Note that there is no need for -program define- here. There may be reasons to 
put the code in an ado-file, where you would need -program define-. However 
your code below seems to be part of a Do-File and therefore the above should 
be enough.

Given the structure of your example I suspect that you might be better of if 
you -reshape- your data to long and using an approach with -by- instead. Here 
is a starting point:

. gen id =  _n
. reshape long x, i(id) j(k)
. by i (k), sort: gen sum = sum(x)
. by i (k): gen p = x/sum[_N]

Hope this helps
uli


ŽÞÀûΰ wrote:
> dear all,
>
> For example, now I have the data like this.
>
> . set obs 5
> . ge x1=1
> . ge x2=2
> . ge x3=3
> . list
>
>      +--------------+
>
>      | x1   x2   x3 |
>      |--------------|
>
>   1. |  1    2    3 |
>   2. |  1    2    3 |
>   3. |  1    2    3 |
>   4. |  1    2    3 |
>   5. |  1    2    3 |
>      +--------------+
>
> I want get each proportion
>
> . ge prop1=x1/(x1+x2+x3)
> . ge prop2=x2/(x1+x2+x3)
> . ge prop3=x3/(x1+x2+x3)
> . list
>
>      +--------------------------------------------+
>
>      | x1   x2   x3      prop1      prop2   prop3 |
>      |--------------------------------------------|
>
>   1. |  1    2    3   .1666667   .3333333      .5 |
>   2. |  1    2    3   .1666667   .3333333      .5 |
>   3. |  1    2    3   .1666667   .3333333      .5 |
>   4. |  1    2    3   .1666667   .3333333      .5 |
>   5. |  1    2    3   .1666667   .3333333      .5 |
>      +--------------------------------------------+
>
>
> In order to make it easy, I wrote the code of ado.
> But it doesn't work, so I want to know how to do it.
> Thanks in advance.
>
> CUI liwei
> *****************************
> capture program drop prop
> program define prop
> syntax [varlist]
> tokenize "`varlist'"
> ge sum=0
> while "`1'" ~="" {
> replace sum=sum+`1'
> mac shift
> }
> local i=1
> while "`1'" ~="" {
> ge p`i'=`1'/sum
> local i=`i'+1
> mac shift
> }
> end
> exit
> ******************************

-- 
[email protected]


*
*   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/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index