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

Re: st: Problem with foreach loops

From   Richard Williams <>
Subject   Re: st: Problem with foreach loops
Date   Mon, 07 Jun 2004 01:31:39 -0500

At 03:36 PM 6/7/2004 +1000, you wrote:
Dear statalist,

  Can anyone spot the mistake with the following snippet of code.

  It actually works fine, and recodes and labels the variable
  in the way I wish, but in exiting (?) the loops it runs into problems.

  Any advice would be most appreciated.
I believe what is happening is that ajbmspay gets recoded 6 times, creating new variables a_pay, a_security, etc. These 6 vars all have identical values. The outer loop then moves on to ajbmswrk, and tries to recode it into a_pay. Because a_pay already exists, you get an error message. In short, the new vars may have the labels you want, but they don't have the values; all 6 are just recodes of ajbmspay.

In SPSS, I would do this with DO REPEAT commands. My Stata programming isn't as strong, but since I may be one of the few members of the list who happens to be awake right now I'll offer some possible workarounds:

foreach x in pay sec wrk hrs flx all {
recode ajbms`x'(-4 -3 -1=.), gen(a_`x')
la var a_`x' "Satisfaction with `x'"

I think this does the recodes right, but doesn't give you the var names or exact labels that you wanted. Better programmers than I can probably tell you a better solution. On the other hand, it is only 6 variables, so unless you need to do this sort of thing routinely it may be easier just to use brute force to write the handful of lines required to do this without looping.


recode ajbmspay ajbmssec ajbmswrk ajbmshrs ajbmsflx ajbmsall(-4 -3 -1=.), gen(a_pay a_security a_work a_hours a_flexibility a_overall)
foreach y in pay security work hours flexibility overall{
la var a_`y' "Satisfaction with `y'"

Richard Williams, Notre Dame Dept of Sociology
OFFICE: (574)631-6668, (574)631-6463
FAX: (574)288-4373
HOME: (574)289-5227
EMAIL: Richard.A.Williams.5@ND.Edu
WWW (personal):
WWW (department):

* For searches and help try:

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