Sentry Page Protection
SAS Macro [1-15]
Text Substitution
You can substitute text in your program using SAS macro variables.
Example
Copy and run the SUBSCRB data set from the yellow box below.
Example
Copy and run the SUBSCRB data set from the yellow box below.
The SUBSCRB data set contains a list of subscribers for a gym membership with the following variables:
- SID: Subscribers ID
- StartDate: the start date of the gym membership
- EndDate: the end date of the gym membership
- Duration: the length of the membership in day(s)
Now, a manager of yours wants to get in touch with those who dropped out of the membership in less than 10 days.
You have written the following program to print the list of subscribers who dropped out early:
Code
title "Subscribers who dropped out in less than 10 days";
proc print data=subscrb;
where duration < 10;
run;
The program prints the list of subscribers whose length of membership is less than 10 days.
It also has the title that describes this list of subscribers.
Now, what if you want to print the subscribers whose duration is less than 20 days?
You just have to write the exact same program but with the new duration:
Example
title "Subscribers who dropped out in less than 20 days";
proc print data=subscrb;
where duration < 20;
run;
You just have to write the exact same program but with the new duration:
Example
title "Subscribers who dropped out in less than 20 days";
proc print data=subscrb;
where duration < 20;
run;
This definitely does the job.
However, if you want to reuse the program for a few more times, changing the duration at the different part of the program could become tedious.
It is difficult to debug and easy to make mistake.
A better way to create a reusable program is to use the SAS macro variable instead:
Example
%let dur = 20;
title "Subscribers who dropped out in less than &dur days";
proc print data=subscrb;
where duration < &dur;
run;
The SAS macro variable (dur) was assigned the value of 20.
It is then inserted into your program where the macro variable was referenced (&dur):
When the program is executed, the macro variable reference (&dur) will be replaced by the value assigned to the macro variable (i.e. 20).
This will be the same as executing the following program instead:
Substituting text with macro variables is fairly easy.
In the next few sessions, you will learn a few more examples of how macro variables can make your program more dynamic and reusable.
Exercise
Reuse the program above and print the list of subscribers whose length of membership is less than 30 days.
Reuse the program above and print the list of subscribers whose length of membership is less than 30 days.
Need some help?
Fill out my online form.