SAS Macros¶
A SAS %macro is a discrete piece of code that can be accessed throughout the SAS script by keyword reference. A SAS %macro can take and use arguments. A SAS %macro is useful when you need to execute a similar set of tasks over and over again (for instance, over many years). This is similar to a program or ado in Stata or functions in R and Python. The general syntax is:
A SAS %macro is referenced elsewhere in a SAS script as %name(...). You can think of a SAS %macro as inserting the contained text/statements into the SAS script whenever referenced.
Arguments¶
A SAS %macro has two types of arguments (or none at all): positional and keyword. Keyword arguments are specified with a keyword, equals sign and a default value (which can be null)
or with a null default value
To supply a custom value of 10 we we would would write
Positional arguments are just listed and are assigned the value corresponding to their position in the argument list when the macro is defined:
If I called %name(1, 2, 3) then a = 1, b = 2, c = 3. If no argument is specified in the corresponding position then the positional argument resolves to null.
Arguments are referenced inside of a %macro as macro variables. These concepts are illustrated below.
These macro calls output
Example¶
To motivate the use of %macro functions, suppose you needed to load in two years of data and generate a few variables. You could do something like:
However, you can also do this in a cleaner and more efficient way with a %macro function.
This style of coding is preferred as it keeps our scripts concise, generally reduces errors and makes debugging easier.