When using the SAS Macro language, we can easily create do loops. The syntax for a SAS Macro do loop is shown below.

%macro example;
    %do i = 1 %to 10;
        /* do stuff here */
    %end;
%mend;

The SAS Macro language is incredibly powerful and allows us to build dynamic programs.

One common piece of code fundamental to all programming languages is the loop. In the SAS Macro language, the main loop is a do loop.

We can use do loops to dynamically create new data and variables in a loop.

The syntax for a SAS macro do loop is shown below.

%macro example;
    %do i = 1 %to 10;
        /* do stuff here */
    %end;
%mend;

One example of using a do loop would be if you have a list of words that you want to loop over. Below is an example of how to loop over a list of words with the sas macro scan function.

%let string = This is a string of words.;

%macro scan_example;
%do i = 1 %to %sysfunc(countw(&string));
    %let current_word = %scan(&string,&i);
    %if ¤t_word = string %then %do;
        /* Do stuff here */
    %end;
%end;
%mend;

SAS Macro Do Loops with Increment

To create a do loop with an increment, all we need to do is add ‘%BY’ and the increment to the first line of the do loop.

Using an increment gives us the ability to go backwards from a starting point to stopping point, or step through the range of numbers with a greater step than just 1.

Below is an example of how to create a SAS macro do loop with an increment.

%macro example;
    %do i = 1 %to 10 %by 2;
        /* do stuff here */
    %end;
%mend;

Do Until Loops in a SAS Macro

Another kind of loop in the SAS Macro language you can use is a do until loop. Just like the name states, you can loop until a certain condition is no longer true.

Note, do until loops check the condition at the END of the iteration – therefore a do until loop will always iterate at least once.

Below is an example of how to create a do until loop in SAS with the SAS Macro language.

%macro example;
    %let i = 1;
    %do %until &i > 10;
        /* do stuff here */ 
        %let i = %eval(&i+1);
    %end;
%mend;

Hopefully this article has been useful for you to learn how to create do loops in your SAS macros.

Categorized in:

SAS,

Last Update: February 26, 2024