Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: st: how to keep labels when using foreach
From 
 
Maarten Buis <[email protected]> 
To 
 
[email protected] 
Subject 
 
Re: st: how to keep labels when using foreach 
Date 
 
Wed, 13 Mar 2013 13:26:59 +0100 
On Wed, Mar 13, 2013 at 12:38 PM, anne broe wrote:
> Im using -foreach- but seem to loose all my value labels when doing so.
> How can I keep the labels in the output from -foreach-?
>
> this is my do file
>
> foreach xx in m_agegr==0 m_agegr==15 m_agegr==20 m_agegr==25
> m_agegr==30 m_agegr==35 m_agegr==40 m_agegr==45 smoking_status==0
> smoking_status==1 smoking_status==2 smoking_status==3    {
>         use Work\Temp4, clear
>         display "`xx'"
>         keep if `xx'
>         gen atc_yes = 1 if ga_atc==1
>         gen atc_no = 1 if ga_atc==0
>         collapse (sum) atc_yes atc_no
>         gen str30 group="`xx'"
>         if "`xx'" != "m_agegr==0" append using Work\Q4
>     save Work\Q4, replace
>     }
The problem does not seem to be -foreach- but -collapse-. The dataset
is just a count of observations with ga_atc equals 1 and ga_atc equals
0. The datasets returned by collapse are so fundamentally different
that it makes sense that value labels are removed except for variables
specified in the -by()- option.
Anyhow, even though -foreach- is not the problem, I would still not
use it in this case. Instead I would reduce that code to two calls to
-collapse- in combination witht he -by()- option:
*------------------ begin example ------------------
clear all
sysuse auto
sum price, detail
gen byte expensive = ( price > r(p75) ) if price < .
gen byte cheap = 1 - expensive
 label define rep78 1 "Poor"      ///
                    2 "Fair"      ///
                    3 "Average"   ///
                    4 "Good"      ///
                    5 "Excellent"
label value rep78 rep78
collapse (sum) expensive cheap, by(rep78)
tempfile temp
save `temp'
sysuse auto
sum price, detail
gen byte expensive = ( price > r(p75) ) if price < .
gen byte cheap = 1 - expensive
collapse (sum) expensive cheap, by(foreign)
append using `temp'
list
*------------------- end example -------------------
* (For more on examples I sent to the Statalist see:
* http://www.maartenbuis.nl/example_faq )
Hope this helps,
Maarten
---------------------------------
Maarten L. Buis
WZB
Reichpietschufer 50
10785 Berlin
Germany
http://www.maartenbuis.nl
---------------------------------
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/