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 <>
To   Statalist <>
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:


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

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


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:

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