title: 'Unordered' by group processing in SAS
body: <p>Is there a way to use by group processing in SAS when the data is grouped together but is out of order?</p>
  
  <pre><code>data sample;
    input x;
    datalines;
  3
  3
  1
  1
  2
  2
  ;
  run;
  </code></pre>
  
  <p>Try to print out the first of each group:</p>
  
  <pre><code>data _null_;
    set sample;
    by x;
    if first.x then do;
      put _all_;
    end;
  run;
  </code></pre>
  
  <p>Results in the below error:</p>
  
  <pre><code>x=3 FIRST.x=1 LAST.x=0 _ERROR_=0 _N_=1
  ERROR: BY variables are not properly sorted on data set WORK.SAMPLE.
  x=3 FIRST.x=1 LAST.x=0 _ERROR_=1 _N_=2
  NOTE: The SAS System stopped processing this step because of errors.
  NOTE: There were 3 observations read from the data set WORK.SAMPLE.
  NOTE: DATA statement used (Total process time):
        real time           0.01 seconds
        cpu time            0.00 seconds
  </code></pre>
  
  <p>And just to reiterate - <strong>I do not want to sort the grouped data first - I need to process it in this order.</strong>  I know I could create a proxy variable to sort on using an intermediary datastep and either a <code>retain</code> statement or the <code>lag()</code> function but I'm really looking for a solution that avoids this step.  Also, I'd like to use the <code>first</code> and <code>last</code> keywords in my by-group processing.</p>