Looping over a string in SAS

In SAS it is easy to loop a macro between two numbers

%DO I=1 %TO 10;
...
%END;

But if you have a list of non-sequential  numbers or text you want to run your macro over, e.g. a list of towns, it can be a bit trickier. This SUGI paper gives a macro which lets you do just that. A few years ago I looked at that macro and didn't really understand how it worked and not wanting to use code I didn't understand I wrote my own version.

The below code lets you loop a pre-defined macro over any list. This list can be in the form of a string split by spaces, or if your list is already in a dataset you can select the dataset and variable you want to loop over.

The code is all annotated and there are examples at the bottom. I use this macro quite regularly and it seems to work but it is quite simplistic compared to the one in the SUGI paper so it will contain some bugs.

Leave a Reply

Your email address will not be published. Required fields are marked *