Macros Básicas de SAS
Macros Básicas de SAS
Initiate your SAS software and let’s get started. Performing these commands as you
read through would help you memorize these commands better.
Example:
where policydate='09Sep14'd;
Run;
Above SAS code is written to extract policy level details for 09-Sep-14 and let us say
that the user needs to run this code on a daily basis after changing the date (at both
the places) to current date.
Thankfully, SAS – like any other programming language, provides the facility of
automating codes with use of SAS macro programming. Now, let us look at the same
code once automated by SAS macros.
Where policydate=”&sysdate9”d;
Run;
In this case, the user does not need to provide value for current date. The code will
automatically pick current date from system.
Make our job easier by re-using similar code multiple times after defining it
ones.
Make changes in variable at a single place and reflect them at multiple
locations.
Make your programs data driven, i.e. letting SAS decide what to do based on
actual data values
Above all, it helps to reduce the efforts required to read and write SAS Code. Macro
programming is typically covered as advanced topic in SAS, but the basic concepts
of SAS macros are easy to understand.
I will now introduce the concept of SAS programming and I assume that you are
aware about basics of SAS programming. We will look at how macro processor
works, how to use SAS macros & macro variables and How to create flexible and
reusable code to save time and efforts?
Macro variable name follows the SAS naming convention and if variable already
exists then value is overwritten.
Value of macro variable in %Let statement can be any string and it has following
characteristics:-
It can be of any length between 0 to 65,534 characters
Numeric values are also stored as character string
Mathematical expressions are not evaluated
Quotation mark can also be stored as a part of value
Leading and trailing blanks are removed before assignment
Example:-
We can also declare multiple macro variables and use them at different places in
SAS Code. Macro variable are not resolved when they are accessed within single
quotes. Hence, we should use double quotes to reference them.
Text¯ovaribale
¯ovariableText
Text¯ovraibleText
A period (.) is used as delimiter that defines the end of a macro variable.
Here, you can see that the program did not execute because we required
(ORION.COUNTRY) and not (ORIONCOUNTRY). This happened because here
period (.) is used as separator between two macro variables. Now, to use period as
a separator between library name and dataset, we need to provide period (.) twice.
SAS Macros
SAS Macros are useful when we want to execute same set of SAS statements again
and again. This is an ideal case for use of macro rather than typing / copy pasting
same statements.
Syntax:-
Macro Statements;
%MEND;
Text
SAS statements or steps
Macro variable references
Macro statements, expressions or calls
After definition of macro, we need to invoke/ call it when want to use it.
Here we do not need to end this statement with a semicolon but it is a good
programming practice to have it.
Example:-
You can see that we have used same set of statements twice using macro.
Positional Parameters
Keyword Parameters
Syntax:-
Definition
%MEND;
Calling
At calling stage, values to parameters are passed in similar order as they are defined
in the macro definition.
Example:-
Run;
%AV(AU, Sydney);
Syntax:-
Definition
Macro Text;
%MEND;
Calling
Example:-
Let’s discuss some examples of SAS Macro Variable and SAS Macros, when you
want to use a particular value multiple times in a program and its value changes over
time.
For example:-
You want to extract transaction details, Manpower details, Budget details and
others for current month only and this is monthly task (Repetitive). You can
provide value for current month (between 01-Sep-14 to 30-Sep-14) and with help
of Macro Variables, we can create the programme in such a manner that we need
to define them only once.
At initial stage of my career, I used to write SAS codes for data conversion like
text to number, number to text, adjusting width of the data type and converting
report in specific layout format and others. But with the help of SAS macros, I
can write SAS macro for each specific task and call it whenever they are required.
SAS Macros are typically considered as part of advance SAS Programming and are
used widely in reporting, data manipulation and automation of SAS programs. They
do not help to reduce the time of execution, but instead, they reduce repetition of
similar steps in your program and enhance the readability of Programs.
Let’s now proceed further can learn the process of creating conditional and
repetitive steps using SAS Macro.
Syntax:-
Both syntax work in similar manner – the only difference is, first one executes only
one statement after THEN or ELSE, whereas the second syntax can execute
multiple statements.
Example
Let’s say, we have transactional data for a company which deals in food business.
Here manager requires details of all the sales on daily basis except on MONDAY.
On Monday, he want a additional summary report for item wise total sales (People
call it as MONDAY Report!)
Here we will first define a separate macro for Daily and Monday reports (you can
combine these together also).
Now on daily basis it will call Macro “Daily” and check if today is MONDAY then it
will run MACRO “Monday”. Similarly if we have multiple statements to execute after
%IF-%Then then we should go for %IF-%THEN-%DO-%END.
Loops
Loops are used to create a dynamic program, which executes for a number of
iterations, based on some conditions (called conditional iteration). These statements
are also valid only inside a macro.
Syntax:
Key things about syntax:
Example:
Let’s say we have a series of SAS data sets YR1990 – YR2013 that contain business
detail and now we want to calculate the average sales for each of these years.
If we will not use the SAS macro then we need to write PROC MEANS steps for
each of the year, which is not a good idea.
Now let’s look at how we can use SAS Macros to do this job easily:
We can achieve this with %UNTIL and %WHILE.
Conditional statements and loops empower SAS Macros to perform conditional and
iterative tasks. They appear similar to SAS conditional statements and loops and
they work similar in some cases. The major difference between the two is %if-%then’
can ONLY be used inside the MACRO program (whether inside the DATA step, or
outside) and ‘if-then’ is ONLY used inside the DATA step (whether MACRO or non-
MACRO).
Now, let’s understand the use of Macro functions to manipulate text, perform
arithmetic operations and execute SAS functions.
%UPCASE()
This function is used to convert case of letters to uppercase:
Example:
Title %UPCASE(&heading);
Run;
%SUBSTR()
This function returns the given number of characters from specified position.
If number of character is not supplied, %SUBSTR function will return characters from
given position till end of the string.
Example:
%LET def=%SUBSTR(&abc,19,7);
Title %Upcase(&def);
Run;
Here we have first extracted “country” from macro variable abc and store it into def
and after that used it to show title in upper case.
%SCAN()
This function will return the nth word in a string (having n words separated by
delimiters).
It will return NULL value, if string does not have n words separated by delimiter and
if we have not given delimiter then it will use default value for it. Default delimiters
are blank , . ( & ! $ * ) ; – / %.
Example: –
%LET ABC=%SCAN(&STR,2);
%LET BCD=%SCAN(&STR,1,i);
%PUT &ABC;
%PUT &BCD;
ABC will store string “Vidhya”, here it automatically identify the second word based
on default delimiter and BCD will have value “Analyt” because we have mentioned
that i is a delimiter and we required the first word.
%EVAL()
This function is used to perform mathematical and logical operation with macro
variables. Remember, macro variable contains only text (numerical values are also
stored as text) and therefore we can’t perform any arithmetical and logical operation,
if we try to use them directly. EVAL() function also returns a text result.
Syntax: – %EVAL (Expression)
Example: –
%LET A=3 ;
%LET B=&A+1;
%LET C=%EVAL(&A+1);
As we know, macro variables store value as text, macro variable B will store 3+1 and
with the use of %EVAL, C will store 4.
Question?
If, we create a variable like:
If you answered 6.2, you are wrong! This statement will throw up error because SAS
understands “.” as character. Now, to evaluate floating numbers, we will
use %SYSEVALF () function and above statement should be written as:
%LET D=%SYSEVALF(&A+3.2);
%SYSFUNC()
This function is used to execute SAS functions in macro environment. With the
help of this function, we can increase the list of functions available to the macro
language significantly. This function can allow us to make almost all DATA step
and user-written functions usable in SAS Macros.
Syntax: –
It has two arguments, first is for the function and second is optional to format the
output of function.
Example: –
%Put %SYSFUNC(Today(),Date9.);
%STR()
This function removes/masks the normal meaning of following token + – * /, > < = ; “
LT EQ GT LE GE LE NE AND OR NOT blank. It also preserves leading and trailing
blanks of the string. Please note that this does not mask & and %.
%NSTR ()
This functions works exactly as %STR, but it also masks macro triggers % and &.
Example: –
%LET D=5;
%PUT &abc;
%PUT &bcd;
Here first %PUT statement will return S 5 Analytics whereas second one will return
S &D Analytics.