Statalist The Stata Listserver


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

Re: st: does stata create an index that can be used in loops?


From   "Sebastian F. B�chte" <[email protected]>
To   [email protected]
Subject   Re: st: does stata create an index that can be used in loops?
Date   Thu, 8 Feb 2007 09:01:05 +0100

Brent,

On 2/8/07, Brent Fulton <[email protected]> wrote:
I am using stata 9 and want to know whether stata creates an index in loops
that I can use to pull from a local macro. For my end result, I would like
the following variables to be created:
var1_county, var2_county, var3_county

I did the following:

local a "var1 var2 var3"
foreach x of local a{
local b "`b' `x'"
}
*the loop above results in the following: local b "var1_zip var2_zip
var3_zip"
In contrast to your described desired content of local b, the local
macro b will not contain what you indicated. It will rather contain
var1 var2�var3. In order to achieve what you wanted the loop should
look the following:

local a "var1 var2 var3"
foreach x of local a{
local b "`b' `x'_zip"
}
di `"`b'"'

sort county
foreach x of local b{
by county: egen `x'_county=total(`x')
}
But this creates the variables: var1_zip_county, var2_zip_county,
var3_zip_county

Is there a way to do this: see*
sort county
foreach x of local b{
by county: egen *grab the appropriate element of local a*_county=total(`x')
}
One way could be to have it both in one loop. Like this:

local a "var1 var2 var3"
foreach x of local a{
    by country: egen `x'_county = total(`x'_zip)
}

To come back to your question whether Stata creates an index when
processing a -foreach- loop. I am not aware of such a feature.
However, you could create your own and use it after tokenizing it with
-tokenize- This could look like the following:

//create a local containing a list of variablen names
local a var1 var2 var3

//create a local containing another list based on the first one
foreach x of local a {
    local b `b' `x'_zip
}

//a third loop which creates some summary statistics from variables in local a.
//This approach relies heavily on the assumption that element order in local a
//and local b are both in such way that it does make sense.
local i=1
tokenize `a'
foreach x of local b {
    by county: gen ``i''_county=total(`x')
    local ++i
}

Compared to the first solution suggested, I would say the latter is a
little more awkward und requires more "programming" than actually
necessary.

hth
Sebastian

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