Announcement

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

  • How to break a foreach/forvalue loop?

    Dear all,

    I would like to rename a set of variables originally in the form : var_1_Y1 and then undefined column names A B C D into the form var_1_Y1 var_1_Y2 (for the name of column A) var_1_Y3 (for the name of column B) var_1_Y4 (for the name of column C) var_1_Y5 (for the name of column D).

    I used the following code:

    Code:
    local x = 1
    forvalue x=2/5 {
    foreach  var of varlist A-D {
    rename `var' (var_1_Y`x')
    local x=`x'+1
    }
    }
    It works fine to rename the variables except I have 9 similar loops with similar structures and I have to run them separately since after each loop is run, stata issues an error 111 "variable A not found".

    I believe this is because the loop has no end and restarts again at the beginning once all the variable names are changed, but I find it odd since I would think the forvalue line should break the loop at 5?

    I thought about using a local macro to store A-D but I don't quite know how to modify the structure to use it.
    I've also tried to use the continue, break function but it doesn't work (it only renames A into var_1_Y2 and stops there).

    Would anybody know how to break the loop please?


  • #2
    Your logic is wrong: you have nested loops, whereas what you need is a single loop that marches both x and A-D forward in parallel:
    Code:
    local x = 2
    foreach v of varlist A-D {
        rename `v' var_1_Y`x'
        local ++x
    }
    Note, in particular, that there is no forvalues loop driving x; there is just one loop over the variables, and x gets explicitly changed within the loop.

    Comment


    • #3
      oh ok I see, thanks a lot!

      Comment

      Working...
      X