Announcement

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

  • Stepping (?) Loop.

    Dear Stata Users:

    I am using Stata 15 and having some problems in writing loops that do not loop over the previous value. Specifically, my loop looks like:

    foreach i of numlist 1/10 {
    replace z=1 if x`i'=1 & y=i+1
    }

    In other words, I would like to start to change z to 1 if x1=1 & y=2 ... 11. For the next round, I would like to start from x2=1 & y=3. And so forth. I have also experimented with the following loop:

    foreach i of numlist 1/10 {
    forval j=i+1 {
    replace z=1 if x`i'=1 & y=`j'
    }
    }

    Neither worked. I have searched the forum as well as elsewhere on the Internet, but could not find a solution. Maybe the terminology I used in search was wrong. I have also read Stata programming book, but could not find it. I know this probably could be solved using "while" or macro/micro, but I would like to know how this could be done using just foreach or forvalue.

    Thank you very much in advance.

    Sincerely,
    Muh-Chung Lin


  • #2
    I guess you want


    Code:
    foreach i of numlist 1/10 {
    replace z=1 if x`i'==1 & y==`i'+1
    }
    or more simply

    Code:
    forval  i = 1/10 {
    replace z=1 if x`i'==1 & y==`i'+1
    }
    Your existing code is checking for a variable named i -- not the macro i defined by the loop. Your attempted fix fails for essentially the same reason

    If you really wrote = where == is needed then your code would fail for that reason too.

    Comment


    • #3
      Dear Mr. Cox:

      Yes. That works. It is exactly the lack of "` ' " after the equation that made them not work.

      Thank you VERY MUCH!!

      Sincerely,
      Muh-Chung Lin

      Comment

      Working...
      X