Search code examples
sasgroupingsequential

How do I group consecutive integers in sas?


I would like to group consecutive integers in sas.

data h;
input integer temperature;
cards;
1 33
2 33
3 34
5 35
6 37
9 33
10 34
;
run;

I would like my output to look like this

1 33 1
2 33 1
3 34 1
5 35 2
6 37 2
9 33 3
10 34 3

Thanks for your help, in advance.


Solution

  • Look at the DIF and retain function. Note that your criteria and example don't match. You say consecutive but seem to imply increase of 0 OR 1.

    DIF calculates the difference between current and previous observation. RETAIN holds a value across rows until it's explicitly changed.

    Data want;
    Set have;
     Retain group 0;
     Temp_dif = dif(temp);
     If temp_dif > 1 then group + 1;
     Run;
    

    EDIT:

    Data want;
    Set have;
     Retain group 0;
     INT_dif = dif(integer);
     If int_dif > 1 then group + 1;
     Run;