Intro to SAS Macro Programming (Part 1)

Dec 29, 2015

Intro to SAS Macro Programming (Part 1)


Trying different statistical languages and being confortable with them is a big advantage for today's statisticians and data scientists.
This is why I wanted to do this series of posts that will include (besides R and Python) SAS, SAS Macro , Julia..etc


What is SAS?

I will try to be as unbiased as possible here. According to its Wikipedia page, SAS  is a software suite that can mine, alter, manage and retrieve data from a variety of sources and perform statistical analysis on it.

SAS has a multitude of procedures specialized in statistical analysis, data manipulation and visualisation.

SAS programming consists on writing the code composed by SAS Data Steps and SAS Procedures, and Executing it.

The concepts of parameters and variables is included in the SAS Macros.





What is SAS Macro?

SAS Macro is considered to be a part of the advanced concepts of SAS programming.
It allows the automatisation of SAS programs in a dynamic way, and therefore it facilitates the execution of repetitive tasks with SAS.

Components :

A SAS Macro code is composed of two main elements: Macros and Macro Variables.
In a SAS program, these 2 components are referenced with these symbols ;

&Name :    Reference to a  Macro Variable
%Name :     Reference to a  Macro Statement

Macro Variable

  • It is a SAS variable, commonly called a "symbolic Variable"
  • It is used to store and manipulate text strings within SAS
  • It follows the variable naming rules of SAS
  • Always preceded by a symbole : &



Syntaxe:

%LET  is used to create and put values into a SAS macro variable.

% LET Macro Variable Name =Value;


Example: 

In the example bellow, we will try to see how does SAS macro variables work exactly.
Let's test this code in SAS: 

Declaring macro variables:

%Let Region = Africa ;
%Let Product = Boot ;


Using macro variables:

 Proc Print Data=  SASHELP.Shoes;
Where Region = ‘’&Region’’ and product = ∏
Run; 



Macro Statement

It is a SAS variable, commonly call SAS Macro Statements can contain the combination of the following points:
  • Text
  • SAS Procedures or SAS Data Steps
  • References to macro variables
Syntaxe:

%Macro Macro Name;
Macro Statements;
%Mend ;

Example: 

Let's test this code in SAS: 
The first step is to input the macro statement into SAS:

%Macro Print ;
Proc print data=SASHELP.Shoes;
Where Region ="&Region";
Run;
%Mend;

 Then, we have to assign a value a the macro variable Region :

%let Region =Africa;

Finally, to execute the macro and see the result:

%Print;

Let's  try an other example :

%let Region =Asia;
%Print;

Using macros with allow users to write less code and make their programs more dynamic and flexible with changements of table names or columns..etc