if-statementsasretain

SAS retain statement group


I'm having trouble with the SAS statement retain in a group. Suppose I have a data set:

data have_data;
input dev nr amount flag $ ;
cards;
1  1356  30000  S
2  1356  35000  S
3  1356  40000  L
4  1356  35000  S
1  2345  15000  S
2  2345  20000  S
3  2345  20000  S
4  2345  25000  S
5  2345  25000  S
1  3456  39000  S
2  3456  40000  L
3  3456  45000  L
4  3456  35000  S
;
run;

I want to create a column flag2, which keeps 'L' if the amount >= 40000 within the dev and nr group. The output should be like:

data want_data;
input dev nr amount flag $ flag2 $ ;
cards;
1  1356  30000  S   S
2  1356  35000  S   S
3  1356  40000  L   L
4  1356  35000  S   L
1  2345  15000  S   S   
2  2345  20000  S   S
3  2345  20000  S   S
4  2345  25000  S   S
5  2345  25000  S   S
1  3456  39000  S   S
2  3456  40000  L   L
3  3456  45000  L   L
4  3456  35000  S   L
;
run;

I sorted the data first and tried the following as I found a similar post about this, but it is not working..

data new_data; 
set have_data;
by   dev nr;
retain test;
if flag = 'L' then help=1;
 if first.nr then test = help;
flag2 = test;
run;

Please help? Many thanks!!


Solution

  • dev appears to be simply a row counter within group nr and the have seems to be focused on nr group alone.

    Under the presumption that L is already present from a prior step, and the by group is just nr, you can carry forward the flag state L in flag2 by never reassigning flag2 after it is L.

    Example:

    data want;
      set have;
      by nr;
    
      retain flag2;
    
      * flag2 is reset at start of group, or assigned if L state not reached yet;
      if first.nr or flag2 ne 'L' then flag2=flag;
    run;