SAS Macro Facility


Macro Definition

The SAS Macro Facility is discussed in detail in chapter 20 of the SAS Language Reference. While there are extensive features, simple macros can be easily developed with just a few program statements, namely %macro and %mend to define a macro, and the ampersand & for variable substitution.

Here is a macro for a randomized complete block design (RCBD):

%macro rcbd(resp,trt,block,data);
proc glm data=&data;		/* randomized complete block design */
   class &trt █
   model &resp = &block &trt / ss3;
   lsmeans &trt / stderr pdiff;
   output out=diag p=pred r=resid;
proc plot data=diag;		/* diagnostic plots of pred vs. resid */
   plot resid*pred=&trt;
%mend rcbd;
And here is a macro for a two-factor completely randomized design:
%macro twoway(resp,A,B,data);
proc glm data=&data;		/* two-way analysis of variance */
   class &A &B;
   model &resp = &A | &B / ss3;
   lsmeans &A &B / stderr pdiff;
   lsmeans &A * &B / stderr pdiff out=lsm;
   output out=diag p=pred r=resid;
proc plot data=lsm;		/* interaction plots */
   plot lsmean * &B = &A;
proc plot data=diag;		/* diagnostic plots of pred vs. resid */
   plot resid * pred = &A;
   plot resid * pred = &B;
%mend twoway;
Once these macros are defined, they can be used as follows:
/* RCBD for two different responses */
%rcbd(yield,fert,location);
%rcbd(temp,fert,location);

/* Two-Way Analsys for different predictors */
%twoway(height,nitro,variety);
%twoway(height,row,column);

Include External Files

Macros and other SAS commands can be stored in an external file which can be included. For instance, suppose the two macros defined above were stored in a file called macro.sas. The procedures section could be condensed to the following:
/* include previously defined macros */
%include 'macro.sas';

/* RCBD for two different responses */
%rcbd(yield,fert,location);
%rcbd(temp,fert,location);

/* Two-Way Analsys for different predictors */
%twoway(height,nitro,variety);
%twoway(height,row,column);

Printing Macro Expansions

Macro expansions can be printed by turning on the mprint option:
options ls=80 ps=40 mprint;
This can be very handy to verify that macros are doing what they were designed to do.
Last modified: Thu Jun 8 17:37:09 1995 by Brian Yandell
yandell@stat.wisc.edu