SAS Macro : A Dynamic Loop

Deepanshu Bhalla 2 Comments

Suppose you need to pass a variable within a loop based on the input defined in a SAS macro using the %DO statement.

The following code defines a macro named "report" that calculates summary statistics using the PROC MEANS procedure for each variable specified in the var parameter and groups them by the variable specified in the "class" parameter. It then outputs the statistics to separate datasets. The names of the output datasets are dynamically generated based on the loop index.

%macro report (input=, var = , class=);
%let n=%sysfunc(countw(&var));
%do i=1 %to &n;
%let val = %scan(&var,&i);
proc means data = &input noprint nway;
class &class;
vars &val;
output out=out&i mean= median= / autoname;
run;
%end;
%mend;

options mprint;
%report(input= test, var = b c, class=a);

When you execute the above sas program, it generates the following output :

proc means data = &input noprint nway;
class a;
vars b;
output out=out1 mean= median= / autoname;
run;

proc means data = input noprint nway;
class a;
vars c;
output out=out2 mean= median= / autoname;
run;
Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

2 Responses to "SAS Macro : A Dynamic Loop"
  1. Hi deepanshu

    What does sysfunc do????..does it convert into character value??

    ReplyDelete
    Replies
    1. Sysfunc is used to apply functions within macro. You can use all functions of data steps by using sysfunc

      Delete
Next → ← Prev