SAS Macro Programming: SAS Macro & Creating a Macro Program
sas macro, sas macros, macro program, creating a macro program, sas macro programming, sas macro language, macro language, macro program, sas macro programming for beginners
Macros refer to Macro programs. Macro programs are very useful if you perform repetitive tasks. Macro programs can be identified because they start with a %MACRO and end with %MEND. After you start the macro with a %MACRO, just like with the data step, you give your macro program a name. Macros can then take in both positional parameters and keyword parameters. In the body of the SAS macro, you can use SAS data-sets, variables, statements, macro variables, macro functions, or any combination of these things and other components.
Here is an example:
option MCOMPILENOTE=all; //Macros can run even when they have errors. By using the MCOMPILENOTE option, it will tell us if our macro has compiled without any errors.
%MACRO reg(predictors); //reg is the name of the macro. predictors are the input variables and is our positional parameter.
proc reg data=stats; //reg is the regression procedure we are using. stats is the name of our data-set.
model anxietylevel=&predictors; //anxiety level is the dependent variable..and it is dependent on the predictors (ie age and sex). The ampersand before the predictors is VERY important and a key feature of macro programs.
run; //we are telling the program to run.
%mend; //we are ending the macro program.
%reg(age); //we are invoking the macro, since we are referencing the name of the macro, and we are telling it that we want to run the regression on the age predictor.
So, what is so special about this macro program? The ampersand in the macro program above is what makes the macro program special. The ampersand before the word predictors (&predictors, 4th line) is going to allow us to run/invoke whichever predictor we want. Notice in the last step/line of code when we invoke the macro (%reg), we were able to pass in the argument we wanted. Age was the only predictor passed as an argument. There were two predictors in our example, age and sex, but we did not have to pass both arguments. Now imagine that your job often required you to run a whole bunch of predictors, and allowed you to select whichever combination of predictors you wanted to run. This would make your job much simpler and easier. After you save the macro, you can re-use it whenever you want.
But this is just the beginning. What if you had to calculate the average salary for 20 years? What if you had to print a specific report depending on the day? These, and many more situations, are easily solved by Macros. If you are interested in learning more about the Macro facility, my advanced SAS course goes into it. Advanced SAS: Macro Facility and Indices