Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Help with Recoding with Multiple Loops

    Hello, I have a series of variables that looks like job[i]_sched[y]. [i] varies from 1 to 6. [y] varies from 1997 to 2017, but the last three waves of data are collected biannually, so the years are 2010 2011 2013 2015 2017.

    I wanted to recode the data using:

    Code:
    local yvars 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 ///
    2011 2013 2015 2017
    foreach i in 1 2 3 4 5 6 {
    local y: word `i' of `yvars' //job number
    recode job`i'_sched`y' (-6/-1=.) (2/6 8 = 0)(1 7 9 = 1),gen(job`i'_schedx`y')
    }

    However, when I run this code, it recodes only 6 variables:

    Code:
    (8734 differences between job1_sched1997 and job1_schedx1997)
    (8742 differences between job2_sched1998 and job2_schedx1998)
    (8865 differences between job3_sched1999 and job3_schedx1999)
    (8913 differences between job4_sched2000 and job4_schedx2000)
    (8960 differences between job5_sched2001 and job5_schedx2001)
    (8979 differences between job6_sched2002 and job6_schedx2002)
    How do I get the loop to run through every combination of [i] and [y]?

    Please let me know if there is anything I should clarify in this post. I looked to see if I could find a similar post, but I did not.

  • #2
    You have constructed parallel looping: you have forced y to increase by 1 each time i increases by 1--and since there are only 6 values of i to iterate over, you get precisely the 6 results you see: note that year and job numbers go up in parallel in the output. What you need is nested loops:

    Code:
    foreach y of numlist 1997/2010 2011(2)2017 {
            foreach i in 1 2 3 4 5 6 {
            recode job`i'_sched`y' (-6/-1=.) (2/6 8 = 0)(1 7 9 = 1),gen(job`i'_schedx`y')
        }
    }
    Added: Just as I simplified your local macro yvars to a loop over a numlist, your foreach loop over i can be simplified to -forvalues i = 1/6-, though in this case it will make less difference in the amount of typing and no noticeable effect on execution time.

    Comment


    • #3
      Hi Clyde, thanks so much for the speedy reply and solution!

      Comment

      Working...
      X