Search code examples
sasretain

How can I do retain operation during deleting an observation in SAS?


The problem, that if the else is executing, increment of S will not accomplish. Any idea?

data osszes_folyositas;
 set osszes_tabla;
 retain old_xname;
 retain s 0;

 if xname ne old_xname  then
 do;
  old_xname = xname; 
  s = 0;
 end;
 else
 do; 
  s = s + Foly_s_tott_t_rgyh_ban_HUF;
  delete;
 end;
run;

Solution

  • Not sure what you are trying to do. But if you have your records ordered by "xname", and for each group of "xname" just want to sum across a value, you could try the following.

    data sample;
    
        input xname$1-6 myvalue;
    
    datalines;    
    name01 5
    name01 1
    name02 3
    name02 8
    name02 4
    name03 7
    ;
    
    data result;
        set sample;
        by xname;
    
        retain s 0;
    
        if first.xname then s=0;
        s=s+myvalue;
        if last.xname then output;
    run;
    
    proc print data=result;
    run;
    

    This resets "s" for each group of "xname" and outputs the last record with "s" set to the sum of "myvalue" across the group. The result looks like this:

    Obs    xname     myvalue     s
    
     1     name01       1        6
     2     name02       4       15
     3     name03       7        7