0

I want to enumerate over groups in SAS. I have the following data set and have attached 2 possible scenarios that I am looking for. locationnurseunitcodedesc transaction_start_dt_tm transaction_stop_dt_tm THIS IS WHAT I WANT BETTER YET

STATION 1   8/31/16 10:33   10/3/16 9:54    1   1
STATION 2   10/3/16 9:54    10/3/16 9:54    1   1
STATION 3   10/3/16 9:54    10/3/16 9:54    1   0
STATION 3   10/3/16 9:54    10/3/16 9:54    2   0
STATION 3   10/3/16 9:54    10/3/16 12:11   3   1
STATION 4   10/3/16 12:11   10/3/16 18:39   1   1
STATION 3   10/3/16 18:39   10/4/16 12:26   1   0
STATION 3   10/4/16 12:26   10/13/16 10:43  2   0
STATION 3   10/13/16 10:43  10/13/16 10:43  3   0
STATION 3   10/13/16 10:43  10/4/16 12:25   4   1

When I use the following code the seq number never goes above 2

data wantONETWO;
set WANTONE;
RETAIN SEQ 0;
SEQ=1;
PRIOR_UNIT = LAG(locationnurseunitcodedesc);
IF locationnurseunitcodedesc = PRIOR_UNIT THEN DO;
SEQ + 1;
END;
run;

Best

Aaron

Tom
  • 47,574
  • 2
  • 16
  • 29
A. MATULA
  • 31
  • 1
  • 7
  • 2
    https://stats.idre.ucla.edu/sas/faq/how-can-i-create-an-enumeration-variable-by-groups/ – Reeza Jun 18 '18 at 21:14
  • You're always setting SEQ=1 to it'll only ever increment once and then be reset back to one. You need BY processing for this not the LAG approach being used. – Reeza Jun 18 '18 at 21:15
  • Please activate the green check mark if the answer solved your question. – PalimPalim Jul 10 '18 at 14:42

1 Answers1

0

You have your operations backwards. Always increment , but then reset to 1 when starting a new group. I'm not going to type your long variable name. Let's just use STATION instead.

data want ;
  set have ;
  seq+1;
  if station ne lag(station) then seq=1 ;
run;

You could also use BY group processing, but since your groups are not sorted you will need the notsorted keyword on the BY statement.

data want ;
  set have ;
  by station notsorted;
  seq+1;
  if first.station then seq=1 ;
run;
Tom
  • 47,574
  • 2
  • 16
  • 29
  • Thank you Tom, I ran the second piece of code of yours using the By variable and it worked perfectly. Too simple of a solution after looking at it LOL. The notsorted option was the key. – A. MATULA Jun 19 '18 at 15:21