SAS Macros - Part 3 - Loops and Conditions in Macros

Do Loop, If-Else- conditions in SAS Macros

We have already covered Global and Local Macro variables and Macros along with sample usages in our previous articles. Let's now learn looping and conditional executions in Macros.

A little complex though, but we have tried to keep it as simple as possible.

 Link to the previous articles of the series:

SAS Macros - Part 1 - Global Macro Variables

SAS Macros - Part 2 - Macro and Local Macro Variables

Useful options and tips whiles writing SAS Macros

Do Loop in SAS macros :

  •  We write %Do , %to and %End while using Do Loop in Macro.
  •  In a macro body Do Loop can be used both inside and outside the Data Step.
  •  It is used to do any task repetitively
  •  Helps in writing a code in shorter form

Let's understand "DO" with an example. We have a data set :

Data Class;
infile datalines ;
Input Name $ Subject $ full_marks Marks_secured;
Rajat Maths 100 52
Vinod Maths 100 64
Rakesh Maths 100 57
Geeta Maths 100 58
Bharat Maths 100 86
Rajesh Maths 100 81
Monal Maths 100 67
Aarya Maths 100 88
Ritesh Maths 100 68
Neha Maths 100 88
Rajat English 150 53
Vinod English 150 69
Rakesh English 150 52
Geeta English 150 59
Bharat English 150 88
Rajesh English 150 59
Monal English 150 71
Aarya English 150 66
Ritesh English 150 68
Neha English 150 77

We first generate a counter, that would give each student a unique numeric ID (Count)

Proc sort data = class ; by subject name; run;
Data class ;
set class ;
count +1 ;
by subject ;
if first.subject then count = 1;

Proc sort data = class ; by Count ;  Run;

We would now exploit this count variable for breaking the data into 10 parts :

%Macro Break_the_data;

%Do i = 1 %to 10;

Data Student_&i.;
Set Class;
Where count = &i.;




The macro above, initializes a local macro variable "i", which changes its value from 1 to 10 with unit increment. it is then being used in the data step and hence subset datasets  Data_1, Data_2 ..... Data_10 get created. You can visualize, how the macro coding saved us from writing 10 data steps.

Can you please help me append these datasets back .... 

Don't you worry, it wont take much efforts. Use the following macro to do so :

%Macro Append_the_data;

Data Appended;
%Do i = 1 %to 10 ;



Basically the above macro would write the following code in background :

Data appended;
Set  Student_1    Student_2    Student_3    Student_4   Student_5
       Student_6    Student_7    Student_8    Student_9    Student_10 ;

As I said in Part 1 of the article, Macro is an indirect way of writing code, you can see it, how the macro helps us KISSS the code.

* KISSS - Keep it short, simple and sweet

Let us now understand conditional execution in Macros

Enjoy reading our other articles and stay tuned with ...

Kindly do provide your feedback in the 'Comments' Section and share as much as possible.