title: How to set flags for difference between dates and another identifier?
body: <p>My data is structured like this:</p>
  
  <pre><code>ID  admission  discharge  loc_num lagdish
  A   08Oct15    12Oct15    0001      -
  A   13Oct15    21Oct15    0002     12Oct15
  A   12Nov15    16Nov15    0003     21Oct15
  A   01Dec15    03Dec15    0004     16Nov15
  B   03Aug15    08Aug15    0001     03Dec15
  B   03Aug15    08Aug15    0007     08Aug15
  C   14Sep15    17Sep15    0003     08Aug15
  C   17Sep15    17Sep15    0003     17Sep15
  </code></pre>
  
  <p>The rule is that if the current admission and previous discharge are 1 day apart or less, they should be rolled-up into one episode but only if the loc_num is the same.  If the loc_num is different, it will still be considered two episodes.  Some IDs have the same admission and discharge, but different loc_nums and this should be considered one episode (so same flag).</p>
  
  <p>So ideally the flagged table would look like this:</p>
  
  <pre><code>ID  admission  discharge  loc_num lagdish         flag
      A   08Oct15    12Oct15    0001      -           1
      A   13Oct15    21Oct15    0002     12Oct15      2 
      A   12Nov15    16Nov15    0003     21Oct15      3
      A   01Dec15    03Dec15    0004     16Nov15      4
      B   03Aug15    08Aug15    0001     03Dec15      1
      B   03Aug15    08Aug15    0007     08Aug15      1
      C   14Sep15    17Sep15    0003     08Aug15      1
      C   17Sep15    17Sep15    0003     17Sep15      1
  </code></pre>
  
  <p>So for ID A, although the difference is 1 day between 12Oct15 to 13Oct15, the loc_num is different, therefore they are distinct episodes.  For ID C, because the difference is 0 days AND the loc_num are the same, it's considered the same episode.  </p>
  
  <pre><code>proc sort data=have; by ID admission; run;
  
  data want;
  set have;
  flag=1;
  do until (last.ID);
  set have_orig;
  by ID admission;
  lagdisch=lag(discharge);
  if first.id=0 then do;
  if admission &gt; lagdisch+1 then admission+1;
  else admission+0;
  end;
  output;
  end;
  run;
  </code></pre>
  
  <p>I used this to flag for combining episodes without considering loc_num, so it would flag any episodes within an ID that were 1 day apart or less between the current admission and previous discharge.  But I haven't figured out how to modify it so that it takes into account slightly different rules to set the flags.</p>
  
  <p>Addition:</p>
  
  <pre><code>ID  admission  discharge  loc_num lagdish  
  F   10Apr15     14Apr15   0003     -
  G   30Apr15     30Apr15   0002     14Apr15
  G   01May15     06May15   0002     30Apr15
  G   08Sep15     12Sep15   0002     06May15
  </code></pre>