[email protected] wrote
> 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.
> *****************************
> 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
I see two issues here:
1. How to do this best. Here is one way:
gen sum = x1 + x2 + x3
or
egen sum = rsum(x1 x2 x3)
forval i = 1/3 {
gen prop`i' = x`i' / sum
}
2. Why your program doesn't work.
Here it is again, presented in
a way that makes the structure
clearer:
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
The problem is that the effect of the first
-while- loop is to blank out all the macros
`1', `2', `3', etc., so that the program
never enters the second -while- loop, because
initially `1' is undefined (empty).
Something like this will work:
program prop
version 8
syntax [varlist]
tempvar sum
ge `sum' = 0
qui foreach v of var `varlist' {
replace `sum' = `sum' + `v'
}
local i = 1
qui foreach v of var `varlist' {
ge p`i++' = `v' / `sum'
}
end
Nick
[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/