Search code examples
sassas-macro

How can I loop different where statements in the dataset in SAS


I have multiple conditional where statements for the variables such as:

where 1<ColA<3;

where 4<ColB<6;

where 2<ColC<6;
.....
where 5<ColN<8;

I want to subset each of the datasets based on those where statements one by one like:

data newds1;
set original;
where 1<ColA<3;
run;

data newds2;
set original;
where 4<ColB<6;
run;

.....

data newdsn;
set original;
where 5<ColN<8;
run;

How can I do that in a loop in SAS?


Solution

  • Create a macro to do the loop for you. You can pipe-separate all of your where statements and loop through each one.

    %macro subset(data=, conditions=, out=);
        %let n = %sysfunc(countw(&conditions., |) );
    
        %do i = 1 %to &n.;
            %let where = %sysfunc(scan(&conditions., &i., |) );
    
            data &out.&i.;
                set &data.;
                where &where.;
            run;
        %end;
    %mend;
    
    %subset(data=original, conditions=1<ColA<3 | 4<ColB<6 | 2<ColC<6, out=newds);