title: how to create a loop for a macro in stata?
body: <p>I have a very large dataset but to cut it short I demonstrated the data with the following example:</p>
  <pre><code>* Example generated by -dataex-. To install: ssc install dataex
  clear
  input float(patid death dateofdeath)
   1 0     .
   2 0     .
   3 0     .
   4 0     .
   5 1 15007
   6 0     .
   7 0     .
   8 1 15526
   9 0     .
  10 0     .
  end
  format %d dateofdeath
  </code></pre>
  <p>I am trying to sample for a case-control study based on date of death. At this stage, I need to first create a variable with each date of death repeated for all the participants (hence we end up with a dataset with 20 participants) and a <code>pairid</code> equivalent to the patient id <code>patid</code> of the corresponding case.</p>
  <p>I created a macro for one case (which works) but I am finding it difficult to have it repeated for all cases (where <code>death==1</code>) in a loop.</p>
  <p>The successful macro is as follows:</p>
  <pre><code>local i &quot;5&quot; //patient id who died 
       
  gen pairid= `i'
  gen matchedindexdate = dateofdeath
  replace matchedindexdate=0 if pairid != patid
  gsort matchedindexdate
  replace matchedindexdate= matchedindexdate[_N]
  format matchedindexdate %d
  save temp`i'
  </code></pre>
  <p>and the loop I attempted is:</p>
  <pre><code>* (min and max patid id)     
  forval j = 1/10  {
      count if patid == `j' &amp; death==1
      if r(N)=1 {
          gen pairid= `j'
          gen matchedindexdate = dateofdeath
          replace matchedindexdate=0 if pairid != patid
          gsort matchedindexdate
          replace matchedindexdate= matchedindexdate[_N]
          save temp/matched`j'
      }
  }
  
  use temp/matched1, clear
  forval i=2/10 {
      capture append using temp/matched`i'
      save matched, replace
  }
  </code></pre>
  <p>but I get:</p>
  <pre><code>invalid syntax
  </code></pre>
  <p>How can I do the loop?</p>