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

RE: Re[3]: st: Problem with foreach loops


From   "Nick Cox" <n.j.cox@durham.ac.uk>
To   <statalist@hsphsun2.harvard.edu>
Subject   RE: Re[3]: st: Problem with foreach loops
Date   Mon, 7 Jun 2004 13:48:38 +0100

In two cases here a``i'' should be a_``i'' 

Nick 
n.j.cox@durham.ac.uk 

> -----Original Message-----
> From: Nick Cox 
> Sent: 07 June 2004 11:30
> To: 'statalist@hsphsun2.harvard.edu'
> Subject: RE: Re[3]: st: Problem with foreach loops
> 
> 
> I think you just have your source and target confused. 
> 
> local i=1
> foreach v in ajbmspay ajbmssec ajbmswrk ajbmshrs ajbmsflx ajbmsall {
>    local n : word `i' of pay security work hours flexibility overall
>    recode `v' (-4 -3 -1 =.), gen(a_`n')
>    la var a_`n' "Satisfaction with `n'"
>    local i=`i'+1
> } 
> 
> Note that this is just one answer. 
> 
> If you know -tokenize-, you can 
> 
> tokenize pay security work hours flexibility overall
> local i=1
> foreach v in ajbmspay ajbmssec ajbmswrk ajbmshrs ajbmsflx ajbmsall {
>    recode `v' (-4 -3 -1 =.), gen(a_``i'')
>    la var a``i'' "Satisfaction with ``i''" 
>    local i=`i'+1
> } 
> 
> and the incrementation can also be done this way 
> 
> tokenize pay security work hours flexibility overall
> local i=1
> foreach v in ajbmspay ajbmssec ajbmswrk ajbmshrs ajbmsflx ajbmsall {
>    recode `v' (-4 -3 -1 =.), gen(a_``i'')
>    la var a``i'' "Satisfaction with ``i++''" 
> } 
> 
> In this instance, I think this last version 
> is not as clear as the previous one. 
> 
> Nick 
> n.j.cox@durham.ac.uk 
> 
> Ian Watson
>  
> > As a follow up to my last email, I've found the answer to 
> this problem
> > using -foreach-. Courtesy of Nick Cox's article in State 
> Journal 3(2)
> > 2003, the trick is to step through a non-numerical list using "word
> > [num] of".
> > 
> > Here is the code that works:
> > 
> > 
> > local i=1
> > foreach v in ajbmspay ajbmssec ajbmswrk ajbmshrs ajbmsflx ajbmsall {
> >   local n : word `i' of pay security work hours flexibility overall
> >   recode `v' (-4 -3 -1 =.), gen(a_`n')
> >   la var `v' "Satisfaction with `n'"
> >   local i=`i'+1
> > }  
> > 
> > 
> > There remains, however, still one bug. The label variables 
> command is
> > not being executed, and the recode command's own variable 
> > label remains
> > attached to the new variables. Does anyone have any thoughts?
> 

*
*   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–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index