Some ways we might want to use macro variables

Macro variable references adjacent to leading and/or trailing text:

text&variable

&variabletext

text&variabletext

Adjacent macro variable references:

&variable&variable

text&variable

Phase 1 of the Nhanes3 data is saved in files according to the month the data was collected

The file for a particular month is named

nh3p1XXX Where XXX is the three letter abbreviation of the month it was collect.

a program without macro variables

In [ ]:
proc format;
   value mf 1="Male" 2="Female";
   value race 1="White" 2="Black" 3="Other";
run;

proc sgplot data=mac1.nh3p1jan;
   histogram age;
run;
proc freq data=mac1.nh3p1jan;
   tables race*gender/nocol nopercent chisq;
   format gender mf. race race.;
run;

With macro variable

In [ ]:
proc format;
   value mf 1="Male" 2="Female";
   value race 1="White" 2="Black" 3="Other";
run;
%let month=feb;
proc sgplot data=mac1.nh3p1&month;
   histogram age;
run;
proc freq data=mac1.nh3p1&month;
   tables race*gender/nocol nopercent chisq;
   format gender mf. race race.;
run;

Adjacent macro variable references:

&variable&variable

Data sets are stored in a SAS data library with a naming convention of nh3pXmon.

X can be 1 or 2.

mon can be JAN, FEB, MAR, and so on.

Write an application that uses macro variables to build SAS data set names and other tokens.

a program with macro variables

In [ ]:
proc format;
   value mf 1="Male" 2="Female";
   value race 1="White" 2="Black" 3="Other";
run;
%let month=jan;
%let phase=1;
proc sgplot data=mac1.nh3p&phase&month;
   histogram age;
run;
proc freq data=mac1.nh3p&phase&month;
   tables race*gender/nocol nopercent chisq;
   format gender mf. race race.;
run;

You can place text immediately after a macro variable reference if it does not change the reference. The word scanner recognizes the end of a macro variable reference when it encounters a character that cannot be part of the reference.

In [ ]:
%let month=jan;
%let phase=1;
%let var=race;
proc sgplot data=mac1.nh3p&phase&month;
   histogram age;
run;
proc freq data=mac1.nh3p&phase&month;
   tables &var*gender/nocol nopercent chisq;
   format gender mf. race race.;
run;

The word scanner recognizes the end of a macro variable reference when it encounters a character that cannot be part of the reference. A period (.) is a special delimiter that ends a macro variable reference. The period does not appear as text when the macro variable is resolved.

This causes problems when you actually want a period after a macro variable reference.

In [ ]:
%let month=jan;
%let phase=1;
%let var=age;
%let lib=mac1;
proc sgplot data=&lib.nh3p&phase&month;
   histogram age;
run;

The solution is two periods

In [ ]:
%let month=jan;
%let phase=1;
%let var=age;
%let lib=mac1;
proc sgplot data=&lib..nh3p&phase&month;
   histogram age;
run;

proc sgplot data=&lib..nh3p&phase&month;

The first period is treated as a delimiter, the second as text.