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

Re: st: simple program


From   Phil Schumm <[email protected]>
To   [email protected]
Subject   Re: st: simple program
Date   Tue, 21 Jun 2005 10:00:56 -0500

At 9:43 AM -0400 6/21/05, Seyda G Wentworth wrote:
I have a long list of exported goods and their annual values (y_1999; y_2000; y_2001...). I want to compute the growth rate for each of these products between 1999-2000 called gro2000; between 2000-2001 called gro2001; and so on till 2003-2004. So I need to create 5 variables. I'm trying to write a simple program of the following sort:

program define growth
local i=1999
while (`i'<=2004) {
gen gro`i'+1=(y_`i'+1-y_`i')/y_`i'
local i=`i'+1
}
end

But it doesn't work, I suspect because of syntax error. Could you correct?

Your immediate problem is with the line:


gen gro`i'+1=(y_`i'+1-y_`i')/y_`i'


in two places. For example, consider the portion on the left; after macro expansion (during the first iteration), this becomes:


gen gro1999+1=


which, as I'm sure you will recognize, is not valid Stata syntax. One way to get around this is with the macro expansion operator `=exp' which provides inline access to Stata's expression evaluator (see [P] macro for details). Thus, you could replace your original line with the following:


gen gro`=`i'+1'=(y_`=`i'+1'-y_`i')/y_`i'


which, after macro expansion, becomes:


gen gro2000=(y_2000-y_1999)/y_1999


As you can see each instance of `=`i'+1' is replaced, first by `=1999+1', and then by 2000.

Finally, note that you can simplify things a bit here by using the -forvalues- command:


forv i = 2000/2005 {
gen gro`i' = (y_`i' - y_`=`i'-1') / y_`=`i'-1'
}


-- Phil

P.S. You haven't indicated why you need an actual program here (as opposed to using the loop directly within the context where you need to generate the variables). If you do, it is most likely because you want to perform this calculation repeatedly and/or in other contexts, and if so, you probably want to code it a bit more generally (i.e., so that it doesn't rely on specific variable names).
*
* 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