Search code examples
sassas-macro

SAS macro to create variable ratios


I am trying to create a SAS macro that I can call for calculating ratio of variables. Here is how I have defined the ratio and used in a SAS dataset. I am getting error. What I am doing wrong? Thanks.

%macro ratio(num, den, ratio);
%if &den = . %then &ratio = -999999;
%else %if &den = 0 %then &ratio = -999998;
%else %if &num = . %then &ratio = -999997;
%else &ratio = &num/&den;
%mend ratio; 

data model_data;
set mysas.model_data;
 call %ratio(var1,var2,ratio_var1_to_var2);
run;

Solution

  • To explain the purpose of the Macro language: SAS Macro is (mostly) used to create SAS Code (it writes text). This SAS Code is then subsequently executed, eg to perform calculations.

    So in this case we need to use the macro to write the datastep (SAS) code - "if / then", not "%if / %then".

    Try:

    options mprint;
    %macro ratio(num, den, ratio);
       if &den = . then &ratio = -999999;
       else if &den = 0 then &ratio = -999998;
       else if &num = . then &ratio = -999997;
       else &ratio = &num/&den;
    %mend ratio; 
    
    data model_data;
    set mysas.model_data;
       %ratio(var1,var2,ratio_var1_to_var2)
    run;
    

    I've added the options mprint so you can see the result of the macro execution in your log..