Announcement

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

  • Generate variables created out of two foreach commands

    Good day all,

    I have 8 existing variables A, B, C, D, E, F, G, H.

    For each variable I want to create a new variable for each year between 2000 and 2010, and name it as a combination of the variable name and year. For example A2000 A2001 A2002 etc.

    The below code seems to fail.

    Does anyone know what I'm doing wrong?

    Code:
    foreach varname in A B C D E F G H{
        foreach num of numlist 2000(1)2010{
                gen `varname'+`num'=`varname' if year=`num'
        }
    }

  • #2
    Two things. The + between `varname' and `num' is a syntax error. And you need a double equals sign between year and `num' Thus

    Code:
    foreach varname in A B C D E F G H {
        foreach num of numlist 2000(1)2010 {
            gen `varname'`num' = `varname' if year == `num'
        }
    }

    Comment


    • #3
      Thanks! It's passed 1am here. I'm not at my sharpest for the day.

      Comment


      • #4
        Note that separate will do the inner loop task without a loop.

        Comment


        • #5
          Thanks! I managed

          Comment

          Working...
          X