Wednesday, December 10, 2014

SAS: piece of code to generate codes by SAS PUT statement

The question is from a colleague: there are 50 states and it requires to assign code to each state from a data set. In the original code there are 50 of if conditions like "if ... then ...; else if ... then ......".

What will happen if there are 500 states? Write 500 "if ... else ..." statements?

It is not a good to do in this hard coding way. If these "if" statements are necessary are necessary in the code, then the best way is to let SAS generate these codes with PUT statement.

An example is given. the following data set i is from 1 to 10, and the corresponding x and y value are given. suppose I wanna get the x and y by the value of i. The method of using SAS to generate the "if ... else ..." statement is:

data a;
    do i = 1 to 10;
        x = i + 5;
        y = i * 3;
        output;
    end;
run;

data _null_;
    set a end = last;
    if _n_ = 1 then put / "if i = " i "then x = " x "and y = "";";
    else            put /"else if i = " i " then x = " x "and y = "";";
    if last then    put /"else x = " x "and y = " y ";";
run;

The generated code is like:
if i = 1 then x = 6 and y = 3 ;
else if i = 2  then x = 7 and y = 6 ;
else if i = 3  then x = 8 and y = 9 ;
else if i = 4  then x = 9 and y = 12 ;
else if i = 5  then x = 10 and y = 15 ;
else if i = 6  then x = 11 and y = 18 ;
else if i = 7  then x = 12 and y = 21 ;
else if i = 8  then x = 13 and y = 24 ;
else if i = 9  then x = 14 and y = 27 ;
else if i = 10  then x = 15 and y = 30 ;
else x = 15 and y = 30 ;

So you don't need to hard code these in your script.


By the way, the best way to do this is not by the "if ... else ..." statements. The best way should use FORMAT in sas.

Another way is to use PROC SQL to join to get the corresponding value.