Hi
I am trying to use a simple macro and it does not appear to be doing what i am intending it to do. I would like to write a macro to sort 4 data sets by the same variable, called num. The data set names differ by a numeric value. For example the first data set is called data1, the second data2, the third data3, and the fourth data4. All four data sets are in my work library. Below is the code I tried to use. Any input you have would be very helpful. I know I can use 4 proc sorts to get this done but was attempting to do this through a macro.
%macro srt;
%do i=1 %to 4;
%end;
proc sort
data=data&;
by num;
run;
%mend srt;
You are ending your loop too quickly and didn't specify the macro variable. Try (untested):
%macro srt;
%do i=1 %to 4;
proc sort
data=data&i;
by num;
run;
%end;
%mend srt;
%srt
You are ending your loop too quickly and didn't specify the macro variable. Try (untested):
%macro srt;
%do i=1 %to 4;
proc sort
data=data&i;
by num;
run;
%end;
%mend srt;
%srt
Well, I tried this but now I get an error message of:
File WORK.DATA5.DATA does not exist.
I consider this an improvement as nothing was posting in my log before.
I am new to macros and am curious why you included the %srt at the end.
/* create sample datasets */
data data1 data2 data3 data4;
input num @@;
cards;
2 4 6 4 1 38 9
;
/* define your macro */
%macro srt;
%do i=1 %to 4;
proc sort
data=data&i;
by num;
run;
%end;
%mend srt;
/* using the macro created */
%srt
Oh shoot, thank you both Arthur and Linlin - the code worked - it was <again> human error on my part
The statements from %MACRO to %MEND just define the macro. To actually run it you need call it. That is why Art included the %SRT at the end of the program.
If you are seeing a message about DATA5 after running the macro as defined then it looks like you are trying to reference the macro variable i after the macro has finished. You might want to add a %LOCAL statement to your macro definition so that looping over I does not modify an existing macro variable in an outer scope.
%macro srt;
%local i ;
%do i=1 %to 4;
proc sort data=data&i;
by num;
run;
%end;
%mend srt;
%srt
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.