Friday, November 11, 2011

retain in SAS

1: keep variable's value from being initialized when reading data in data step
2: assign initial values for variables
3: rearrange the orders of variables

e.g.1:  we want to calculate the cumulative sum of transactions for different type, and then output the cumulative sum at the last observation of type.
In order to calculate the cumulative sum, one way is to use sum statement which will ignore missing values; here we use sum function, so we need to temporarily keep the value of total within each type (e.g., A). When we reach the last obs of type (A), output the data; then set total to 0 to be ready for next type (B) cumulative sum calculation.



data test;
      set sasuser.credit;
      num_trans=input(transaction, 6.2); /* Transfet char to num */
      keep   type num_trans;
run;

proc sort data=test;
      by type;
run;

proc contents data=test;
run;

data sum_by_type;
      set test;
      by type;
      retain total;
      total = sum(total , num_trans);     /* total=total+num_trans doesn't work */
      if last.type then do;
            output;     /* Must output first then set total = 0 */
            total=0/* Otherwise total will be 0 rathen than cummulative sum */
      end;
run;

data sum_by_type;
      set test;
      by type;
      retain total;
      total = sum(total , num_trans);     /* total=total+num_trans doesn't work */
      if last.type then do;
            total=0;     /* If put total = 0 first, the result will be: */
            output;
      end;
run;

e.g.2: re-arrange the order of different variables: for example, there are many variables, we want to re-order them, making categorical variables list together, numeric variables together. Then we can use retain to change their orders:
Look at original variables order in sasuser.admit, they are:

Then we change the order and let char first, numeric variables next; it is:

data neworder;
      retain id actlevel name sex age date fee height weight;
      set sasuser.admit;
run;





No comments:

Post a Comment