Announcement

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

  • Trying to use foreach and if to define a local

    Hi Stata users

    I now have three days of experience with Stata and I really like the program so far. I have now run into a problem that I can't figure out how to solve, and I'm hoping one of you can help me.

    I am trying to combine "foreach" and "if" to define a local value using the below code.
    I get the error: "num not found"

    I cant figure if I´m wrong on "foreach" or "if" or both.

    Can you see what I am doing wrong? Or help me find an alternative solution?

    Thank you for reading this.

    Code:
    foreach num of numlist 1/5 {
    if num == 1 local Jname Squat
    if num == 2 local Jname Squat_Jumps
    if num == 3 local Jname Drop
    if num == 4 local Jname Drop_Vertical_Jump
    if num == 5 local Jname Static_Broad_Jump
    use "`Jname'.dta"
    .......
    }

  • #2
    Code:
     
     if num == 1 local Jname Squat
    should be

    Code:
     
     if `num' == 1 local Jname Squat
    and so forth.

    There are several ways to do that more quickly, including


    Code:
     
     foreach f in Squat Squat_Jumps Drop Drop_Vertical_Jump Static_Broad_Jump {      use `f' }

    Comment


    • #3
      The code at the end of post #2 cannot be executed as shown.
      Code:
      . foreach f in Squat Squat_Jumps Drop Drop_Vertical_Jump Static_Broad_Jump {      use `f' }
      program error:  code follows on the same line as open brace
      r(198);
      It should be
      Code:
      foreach f in Squat Squat_Jumps Drop Drop_Vertical_Jump Static_Broad_Jump {
        use `f'
      }

      Comment


      • #4
        Friedrich: Correct. I should have spotted that.

        Comment


        • #5
          Thank you very much both of you. The codes work like a charm

          Comment

          Working...
          X