Search code examples
if-statementsassas-macro

SAS Nested %if %then %do statements


I'm running this as a bigger code and want to make it as automated as possible so I'm trying to set some macro variables. I'd like to have two conditions on setting some macro variables in sas, I've tried placing the %end in etc but keep getting errors so think I'm missing something this is my current code:

   %if &macro_var1. = N %then %do;

%if &run. = model %then %do;

%let x1= 0.4;
%let x2= 0.3;
%let x3= 0.23;
%let x4= 0.07;

%let x_end="01dec2022"d;
%let x1_1= 0.4;
%let x2_1= 0.3;
%let x3_1= 0.23;
%let x4_1= 0.07;

%let x_end2="01jul2023"d;
%let x1_2= 0.4;
%let x2_2= 0.3;
%let x3_3= 0.23;
%let x4_4= 0.07;
%end;

%if &run. = other %then %do;

%let x1= 0.4;
%let x2= 0.22;
%let x3= 0.31;
%let x4= 0.07;


%let x_end="01dec2022"d;
%let x1_1 = 0.4;
%let x2_1 =0.3;
%let x3_1 = 0.23;
%let x4_1 = 0.07;


%let x_end2="01jul2023"d;
%let x1_2 = 0.30;
%let x2_2= 0.20;
%let x3_3 = 0.35;
%let x4_4 = 0.15;
%end;

%if &macro_var1. = Y %then %do;

%if &macro_var2. = b %then %do;

%let x1 = 0.4;
%let x2 0.3;
%let x3 = 0.23;
%let x4 = 0.07;

%let x_end="01dec2022"d;
%let x1_1 = 0.4;
%let x2_1= 0.3;
%let x3_1 = 0.23;
%let x4_1 = 0.07;

%let x_end2="01jul2023"d;
%let x1_2 = 0.4;
%let x2_2= 0.3;
%let x3_3 = 0.23;
%let x4_4= 0.07;
%end;

%if &macro_var2. = s %then %do;
%let x1 = 0;
%let x2= 0;
%let x3 = 0;
%let x4 = 1;


%let x_end="01dec2022"d;
%let x1_1 = 0;
%let x2_1= 0;
%let x3_1 = 0;
%let x4_1 = 1;

%let x_end2="01jul2023"d;
%let x1_2 = 0;
%let x2_2 = 0;
%let x3_3 = 0;
%let x4_4 = 1;
%end;

Solution

  • You cannot nest %IF in open SAS code. But for such simple logic you can just flatten to a series of %IF instead.

    For example take this nested logic

    %IF A %THEN %DO:
       %IF B %THEN %DO;
       < group onw >
       %END:
       %IF C %THEN %DO:
       < group two >
       %END:
    %END;
    

    It can be converted into this flat logic by combining the outer test into the inner test.

    %IF A and B %THEN %DO;
       < group onw >
    %END:
    %IF A and C %THEN %DO:
       < group two >
    %END: