Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: generate newvar with the -foreach- command


From   Joseph Coveney <[email protected]>
To   Statalist <[email protected]>
Subject   Re: st: generate newvar with the -foreach- command
Date   Sun, 07 May 2006 09:41:42 +0900

Michael Kalinowski wrote:

I just started to use Stata and I would like how to generate new variables
with the -foreach- command.
However, it's not that easy I thought...

Here is an example:
In order to get the precent values in this dataset (time-series 1990-2004)I
would like to generate  new variables:
c_bb*= a_bb*/b_bb* if *==*, where * is the varname extension:

c_bb01=a_bb01/b_bb01
c_bb03=a_bb03/b_bb03
c_bb10=a_bb10/b_bb10
c_bb11=a_bb11/b_bb11
c_bb20=a_bb20/b_bb20
.
.
.
a_bb995/b_bb995=c_bb995

I tried this, but it does not work. I suppose it's because of  the "*==*"
expression:

. foreach var of newvarlist c_bb* {
2. gen c_bb*=a_bb*/b_bb* if *==*
3. format c_bb* %9,4f
4.}

--------------------------------------------------------------------------------

Try something like the following:  identify only that which changes and then
put it into a local macro to use to identify the variables.  Also, it might
be more efficient to perform the -format- only once, outside of the loop,
after all of the variables have been created.

Joseph Coveney

foreach var of varlist a_bb* {
   local suffix = substr("`var'", 4, .)
   generate float c_bb`suffix' = `var' / b_bb`suffix'
}
format c_bb* %9,4f

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