title: SAS-To identify consecutive observations
body: <p>I attempt to identify events occurred in at latest four consecutive years. Assuming I have the following sample.</p>
  
  <pre><code>Rungroup Year
  1   2003
  1   2004
  1   2005
  1   2006
  1   2008
  1   2009
  2   2003
  2   2004
  2   2005
  2   2007
  2   2008
  2   2009
  3   2003
  3   2004
  </code></pre>
  
  <p>Based on following code, I want to remove the years that are not consecutive for at least four years. This method has two step. The first step is to give serial number to the consecutive years. The second step is based on look ahead method. </p>
  
  <pre><code>data have;
  set have;
  by rungroup;
  lyear=lag(year);
  if first.rungroup then lyear=.;
  
  if year =1+ lyear then group1+1;
  else group1=0;
  run;
  
  
  data have3;
  set have2;
  by rungroup;
  
    set have2 ( firstobs = 2 keep = group1 rename = (group1 = next2) )
  
        have2 (      obs = 1                       );
    next2 = ifn(  last.rungroup, (.), next2 );
  
  
    set have2 ( firstobs = 3 keep = group1 rename = (group1 = next3) )
  
        have2 (      obs = 2                        );
  
    next3 = ifn(  last.rungroup, (.), next3 );
  
    set have2 ( firstobs = 4 keep = group1 rename = (group1 = next4) )
  
        have2 (      obs = 3                       );
  
    next4 = ifn(  last.rungroup, (.), next4);
   if next4&gt;=3 or next3&gt;=3 or next2&gt;=3 or group1&gt;=3 then output;
  run;
  </code></pre>
  
  <p>Is this an efficient want way to identify consecutive observations? Any comments would be greatly appreciated.</p>