Hi,
I am trying to write a do loop outside a data step. For example, assume my data has 15 variables named var1, var2, ...var15. My main question is how to feed "i" into the macro.
%macro m1 (var_use);
proc freq data=data1;
tables var&var_use;
*other commands;
run;
%mend m1;
do i = 1 to 15;
%m1 (&i);
end;
run;
Thanks,
Brent Fulton
UC Berkeley
You can use %DO to loop in macro language.
Say you want the macro to loop over the variables specified in the input parameter.
%macro m1 (varlist);
%local i next ;
%let i=1;
%do i=1 %to %sysfunc(countw(&varlist));
%let next=%scan(&varlist,&i);
proc freq data=data1;
tables &next;
run;
*other commands;
%end;
%mend m1;
%m1(age sex race);
Why don't you just list all VARn variables on the TABLES statement...
TABLES VAR1-VAR15;
or perhaps.
TABLES VAR:;
I could do that, but my macro is more complex. Is there any way to feed "i" into the macro?
You can use %DO to loop in macro language.
Say you want the macro to loop over the variables specified in the input parameter.
%macro m1 (varlist);
%local i next ;
%let i=1;
%do i=1 %to %sysfunc(countw(&varlist));
%let next=%scan(&varlist,&i);
proc freq data=data1;
tables &next;
run;
*other commands;
%end;
%mend m1;
%m1(age sex race);
Thank you Tom this was helpful, because it could be applied to variables in general...
You could use call execute to call your macro. E.g.:
*create some test data;
data data1;
set sashelp.class (rename=(
sex=var1
age=var2
height=var3
weight=var4));
run;
%macro m1 (var_use);
proc freq data=data1;
tables var&var_use;
*other commands;
run;
%mend m1;
data _null_;
do i = 1 to 4;
x = cats( '%m1(',i,')' ) ;
call execute ( x ) ;
end;
run;
Thank you Art, your answer is correct and helpful as well, but Sas only allows one correct answer...
Brent, Tom was clearly first, deserved the correct answer tag, and I have more than enough points as it is. I was simply offering a way to accomplish the task of passing values from one's code to a macro as that question gets asked repeatedly. Regardless, thanks for the recognition.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.