I am a new SAS user wondering the most efficient way to set up my program. It's made up of about a dozen DATA and PROC SQL steps that do basic transformations to my input data set. The final output is a simple table with summary metrics for that data set. I'd like to run several other data sets through the same script and have the program return summary tables for each one. In R, I would approach this by creating a vector with all my data set names and then use a FOR LOOP to run the program for each of the data sets in the vector. Would this approach work in SAS and if so, what would the code look like?
Thank you in advance for the help!
Try Using SAS Macros, Ex. Considering you have multiple sorting operations on multiple datasets,
%macro srt(idsn=,odsn=,byvar=);
proc sort data=&isdn out=&odsn;
by=&byvar;
run;
%mend;
%srt(idsn=have,odsn=want,byvar=var1);
Try Using SAS Macros, Ex. Considering you have multiple sorting operations on multiple datasets,
%macro srt(idsn=,odsn=,byvar=);
proc sort data=&isdn out=&odsn;
by=&byvar;
run;
%mend;
%srt(idsn=have,odsn=want,byvar=var1);
In SAS, the approach is somewhat similar. Rather than creating a vector, create a long string holding all the input data set names (separated by a blank is fine). Then use macro language to loop through the list, pick out the next name, and apply your series of steps to it. The series of steps could be coded within your macro, or could just be packaged as a separate macro. Here's a paper that might help with the approach:
Unfortunately, writing macros is a much longer subject. Good luck.
Another approach is to place your input dataset names (or library and set0 into a data set.
The values can then be used in a data step using that data to use CALL EXECUTE to create the syntax of the steps you execute.
A real crude example:
data names;
length dsname $ 41;
input dsname;
datalines;
SASHELP.Class
SASHELP.Cars
;
run;
data _null_;
set names;
call Execute("Proc print data="||dsname||";");
call execute("run;");
run;
The data _null_ basically presents the statements from call execute to the compiler.
Any of your invariate code could be in a single Call Execute though I tend to make the lines one a time for later flexibility.
Replace Call Execute with appropriated put statements to see what the code generated looks like. You could use FILE PRINT to send the generated code to program file if desired instead.
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.