Thursday, January 31, 2013

inputn and putn to convert between date and number

%let num2date=%sysfunc(putn(10238, date9.));

%put &num2date;


%let date=%sysfunc(inputn(31jan2013, date9.));

%put &date;

Friday, January 11, 2013

SAS: use CALL EXECUTE or MACRO Variables to score data


For some SAS procedures, like proc fmm, it will not score the data so need to do it manually with score formula.

Here we show two methods to do this. For the first, we can use CALL EXECUTE to generate score code; For the second, we can use macro variables for each coefficient.


*** coefficients for the variables  ***;
data coef;
input coef1 coef2 coef3;
cards;
.1 .26 .58
;
run;

*** data to be scored  ***;
data test;
array a_iv{*} x1 x2 x3;
do j=1 to 100;
        do i=1 to 3;
                a_iv[i]=rand('normal',i);
        end;
        output;
end;
run;


*** First: use call execute to generate the score code  ***;

data _null_;
        set coef end=last;
        if _n_=1 then call execute(' data score(drop=i j); set test; key=_n_; score= 1 + x1 * '|| coef1 || '+x2 * '|| coef2 || '+x3 * ' || coef3 || ';' );
run;

SAS will generate codes like this in the log file, which is our score code;


proc print data=score;
run;




*** Second: if coef is in one column like below, we can store each into a macro variable, and then score use sas macro  ***;

proc transpose data=coef out=coef1;
run;

***  generate macro variables for each coefficient in PROC SQL, by using THROUGH  ***;
proc sql;
        select col1 into: m_coef1 through : m_coef3 from coef1;
quit;

%put &m_coef1 &m_coef2 &m_coef3;

data score2(keep=key score2);
        set test;
        key=_n_;
        score2=1+x1*&m_coef1 + x2*&m_coef2 + x3*&m_coef3;
           *** if there are many variables, we can use loop to concatenate the formular ***;
run;

***  score and score2 should be the same  ***;
data merged;
        merge score score2;
        by key;
run;

proc print data=merged;
run;

The output is like: