Announcement

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

  • Nested foreach loop with different variables and conditions

    Hello,


    I am trying to create a foreach loop that would achieve replacing some variables (eg x,y,z etc.) based on similar conditions

    replace x = 1 if x1 == 1 & x2 == 0
    replace x = 2 if x1 == 0 & x2 == 1
    replace x = 3 if x1 == 1 & x2 == 1

    the issue is that i have other variables, such as y x and so on, which I need to run through the same process e.g.:

    replace y = 1 if y1 == 1 & y2 == 0
    replace y = 2 if y1 == 0 & y2 ==1
    replace y = 3 if y1 ==1 & y2 == 1

    What is a good approach for this problem?

    Thanks a lot !




  • #2
    Your examples are matched by e.g.

    Code:
    replace y = y1 + 2 * y2 
    but only you can say whether that matches your general rule. Turn and turn about, tell us the general rule and you should get advice on how to implement it in Stata.

    Pushing that further, your total code could be replaced with

    Code:
    foreach v in x y { 
         replace `v' = `v'1 + 2 * `v'2 
    }


    and similar comments apply to that loop.

    Comment

    Working...
    X