You are on page 1of 75

SAS MACROS

BY:
GURBEER SINGH

Objectives

How Marcos can help


Macro Variable definition and types
Referencing Macro Variables
Define and call a simple macro.
Macro Parameters
Scope of Macro Variables
SAS System Options
Writing an Efficient Macro
Auto Call Macros

HOW MACROS CAN HELP:


First, with macros you can make one small
change in your program and have SAS echo
that change throughout your program
Second, macros can allow you to write a piece
of code and use it over and over again in the
same program or in different programs

Macro Variable
SAS macro variables enable you to substitute text in your
SAS programs. Macro variables can supply a variety of
information, including
operating system information
SAS session information
text strings
SAS macro variables make your programs more reusable and
dynamic
The macro variables can be defined & used anywhere in SAS
programs, except within data lines

Macro Variable Contd


Macro variables defined by macro programmers are called
user-defined macro variables. Those defined by SAS are
called automatic macro variables.
Macro variables are stored in symbol tables, which list the
macro variable name and its value.

User-Defined Macro Variables


These are the user defined Macro variables whose value we
create and define in a SAS session
The simplest way to create and assign a value to a macro
variable is to use the macro program statement %LET

Example:
%let dsname=Newdata;
Where DSNAME is the name of the macro variable.
Newdata is the value of the macro variable dsname.

User Defined Macro Variables Contd..


Some other Examples:

1.

%let sto=24;

2.

%let sto2=%str(proc means data=year;


var rainfall;
run;
);

User-Defined Macro Variables


Contd
Few other ways to define a macro variables:

%LOCAL statement
%GLOBAL statement
%MACRO statement
SYMPUT routine
INTO clause

Macro Variable Reference


After a macro variable is created, the variable is
referenced with an ampersand preceding its name (&varname), which is called a macro variable reference.
Example:
%let cop=SAS;
data temp;
put This is a &cop training";
run;

The output will be:


This is a SAS training

Macro Variable Reference Contd


Referencing Macro Variables Indirectly
When the macro processor encounters multiple ampersands,
its basic action is to resolve two ampersands to one
ampersand. For example, to append the value of &N to CITY
and then reference the appropriate variable name.
Example:
To display the values of CITY1, CITY2, CITY3 we use the
following reference using &&.
%put &&city&n; /* correct */

In this example, the first macro scan will convert


&&city&n to &city1 which gives the value of CITY1.

10

Example:
%let a=b;
%let b=c;
%let c=10;
1.&a;
2.&&a;
3.&&&a;
4.&&&&a;
5.&&&&&a;
6.&a&b;
7.&&a&b;
8.&&a.&b;

11

Output:
1.
2.
3.
4.
5.
6.

b
b
c
b
c
bc

7. WARNING: Apparent symbolic reference AC not resolved.

8. bc

12

Question:
The following SAS program is submitted:
%let dept=prod;
%let prod=merchandise;
The following message is written to the SAS log:
The value is "merchandise"
Which SAS System option writes this message to the SAS log?
A. %put the value is "&&&dept";
B. %put the value is "&&dept";
C. %put the value is "&dept";
D. %put the value is &&&&dept;
ANSWER:

13

Nesting Macro Variables:


%let sto=year;
%let nest=%str(proc means data=&sto;
var rainfall;
);
Result after invoking macro variable &nest:
proc means data=year;
var rainfall;

14

Displaying Macro Variables:


%PUT displays macro variables to the log at compile time.
Syntax:
%PUT text macrovariables ;

Example:
%let mon=JAN;
%let yr=2012;
%put &mon , &yr;
This writes in the SAS log:
JAN , 2012

15

Displaying Macro Variables Contd..


%PUT can display all current macro variables.
%PUT _ALL_;

16

A Macro Problem
Problem: You reference a SAS datasetname several times in a SAS
job.
DATA PAYROLL;
INPUT EMP$ RATE;
DATALINES;
TOM 10
JIM 10
;
PROC PRINT DATA=PAYROLL;
TITLE "PRINT OF DATASET PAYROLL";
RUN;

Question: How can you change the name quickly in one place only AND
have the datasetname appear in a title?

17

A Macro Problem Contd


%LET NAME=PAYROLL;
DATA &NAME;
INPUT EMP$ RATE;
DATALINES;
TOM 10
JIM 10
;
PROC PRINT DATA=&NAME;
TITLE "PRINT OF DATASET &NAME";
RUN;

18

The Generated SAS Code


DATA PAYROLL;
INPUT EMP$ RATE;
DATALINES;
TOM 10
JIM 10
;
PROC PRINT DATA=PAYROLL;
TITLE "PRINT OF DATASET PAYROLL";
RUN;

Notes:
Macro variables are not resolved within single quotes.

19

Defining a Macro
A macro or macro definition enables you to write macro
programs.
General form of a macro definition:
%MACRO
%MACROmacro-name;
macro-name;
macro-text
macro-text
%MEND
%MEND<macro-name>;
<macro-name>;

macro-name follows SAS naming conventions.


macro-text can include
any text
SAS statements or steps
macro variables, functions, statements, or calls
any combination of the above.
20

Macro Compilation
When a macro definition is submitted,
macro language statements are
checked for syntax errors
compiled
SAS statements and other text are not
checked for syntax errors
compiled
the macro is stored as an entry in a SAS catalog, the
temporary catalog work.sasmacr by default.

21

SAS/Macros
(Passing Parameters)
Passing Information into a Macro Using Parameters
A macro variable defined in parentheses in a %MACRO
statement is a macro parameter. Macro parameters enable
you to pass information into a macro.
%macro plot(yvar= ,xvar= );
proc plot data=test;
plot &yvar*&xvar;
run;
%mend plot;
You invoke the macro by providing values for the parameters,
as follows:
%plot(yvar=income,xvar=age)
22

Macro Parameters
General form of a macro call with parameters:
%macro-name(value-1,
%macro-name(value-1,
value-n)
value-n)

Parameter values are


parenthesized
comma-delimited.
Parameter values can be any text, null values, macro
variable references, or macro calls.

23

Scope of Macro Variables


Every macro variable has a scope. A macro variable's scope
determines how it is assigned values and how the macro
processor resolves references to it.
Two types of scope exist for macro variables: global and local.
Scopes can be nested.

24

Local Macro Variables

25

Local macro variables are defined within an individual SAS


Macro

Local macro variables are stored in a local symbol table that


is created at the beginning of the execution of a macro

Local macro variables exist only during the execution of the


macro in which the variables are created and have no
meaning outside the defining macro

Global Macro Variables

26

Global macro variables exist for the duration of the SAS


session and can be referenced anywhere in the program;
either inside or outside a macro.

There is a global symbol table, which stores all global


macro variables.

Automatic Macro Variables


The Automatic macro variables are created when SAS is
invoked
They are Global in nature
They are usually assigned values by SAS session
They contain the information about the computing environment,
such as the date and time of the session, and the version of
SAS you are running

27

Automatic macro variables


Every time you invoke SAS, the macro processor automatically creates certain
macro variables. You can use these in your programs.
Some of those automatic variables are:
NAME

VALUE

SYSDATE

date of SAS invocation

SYSDAY

day of the week of SAS invocation

SYSTIME

time of SAS invocation

SYSSCP

operation system being used

SYSVER

release of SAS system being used

SYSERR

return code set by last DATA or PROC step

SYSLAST

name of most recently created SAS data set in the


form of libref.name. If no data set was created then
the value is _NULL_ .

28

Practice Exercise:
Exercise 1 :
Determine the values of the following system macro variables using your
current computer system.
&SYSDAY
Current day of the week
&SYSTIME
Current time
&SYSSCP
Operating system being used
&SYSVER
Current SAS version number
&SYSDATE
Current date, in DATE7. Format
Exercise 2:
Using system macro variables run a PROC CONTENTS and a PROC
PRINT on the LAST SAS dataset that was created. Include its name in a
title.

29

Exercise 1 Solution
%PUT **** SYSDAY = &SYSDAY;
%PUT **** SYSTIME = &SYSTIME;
%PUT **** SYSSCP = &SYSSCP;
%PUT **** SYSVER = &SYSVER;
%PUT **** SYSDATE = &SYSDATE;

30

Exercise 2 Solution:
proc contents data=&syslast;
title "contents of &syslast";
run;
The Generated Code:
proc contents data=WORK.COUNTYDT;
title "contents of WORK.COUNTYDT";
run;
Proc print data=&SYSLAST;
Run;

31

Question:
The following SAS program is submitted:
%macro execute;
<insert statement here>
proc print data = sasuser.houses;
run;
%end;
%mend;
Which of the following completes the above program so that it executes on Tuesday?
A. %if &sysday = Tuesday %then %do;
B. %if &sysday = 'Tuesday' %then %do;
C. %if "&sysday" = Tuesday %then %do;
D. %if '&sysday' = 'Tuesday' %then %do;
Answer:

32

Quick Quiz
Does a %LET statement outside of a macro program
create a macro variable in the global or local symbol
table?

33

Quick Quiz - Answer


Does a %LET outside of a macro program create a macro
variable in the global or local symbol table? GLOBAL

34

Example:
%macro holinfo(day,date);
%let holiday=Christmas;
%put *** Inside macro: ***;
%put *** &holiday occurs on &day, &date. ***;
%mend holinfo;
%holinfo(Thursday,12/25/2011)
%put *** Outside macro: ***;
%put *** &holiday occurs on &day, &date. ***;

35

Output:
*** Inside macro: ***
*** Christmas occurs on Thursday, 12/25/2011 ***
*** Outside macro: ***
WARNING: Apparent symbolic reference HOLIDAY not resolved.
WARNING: Apparent symbolic reference DAY not resolved.
WARNING: Apparent symbolic reference DATE not resolved.
*** &holiday occurs on &day, &date. ***

36

Question:
The following SAS program is submitted:
%let a=cat;
%macro animal(a=frog);
%let a=bird;
%mend;
%animal(a=pig)
%put a is &a;
What is written to the SAS log?
A. a is pig
B. a is cat
C. a is frog
D. a is bird
Answer: B

37

CONDITIONAL LOGIC
%IF condition %THEN action;
%ELSE %IF condition %THEN action;
%ELSE action;
%IF condition %THEN %DO;
action;
%END;

38

These statements can only be used inside a macro

The %DO Statement


%DO allows many statements to be conditionally compiled.
Example: Submit as before, but include titles.
%MACRO PTCHT(PRTCH,NAME,BARVAR);
%IF &PRTCH=YES %THEN
%DO;
PROC PRINT DATA=&NAME;
TITLE "PRINT OF DATASET &NAME";
RUN;
%END;
PROC CHART DATA=&NAME;
VBAR &BARVAR;
RUN;
%MEND;
%PTCHT(YES,PAYROLL,EMP)

39

The Generated SAS Code


PROC PRINT DATA=PAYROLL;
TITLE "PRINT OF DATASET PAYROLL";
RUN;
PROC CHART DATA=PAYROLL;
VBAR EMP;
RUN;

40

%DO can also vary a value.


Example: Run PROC PRINT &PRTNUM times.
%MACRO PRTMAC(PRTNUM,NAME);
%DO I= 1 %TO &PRTNUM;
PROC PRINT DATA=&&NAME.&I;
TITLE "PRINT OF DATASET &&NAME.&I";
RUN;
%END;
%MEND;
%PRTMAC(4,PAYROLL)

41

The Generated SAS Code


PROC PRINT DATA=PAYROLL1;
TITLE "PRINT OF DATASET PAYROLL1";
RUN;
PROC PRINT DATA=PAYROLL2;
TITLE "PRINT OF DATASET PAYROLL2";
RUN;
PROC PRINT DATA=PAYROLL3;
TITLE "PRINT OF DATASET PAYROLL3";
RUN;
PROC PRINT DATA=PAYROLL4;
TITLE "PRINT OF DATASET PAYROLL4";
RUN;

42

Practice Exercises
Exercise :
If the following macro was defined to the SAS system:
%MACRO FREQ(DSN,VAR1,VAR2);
PROC FREQ DATA=&DSN;
TABLES &VAR1*&VAR2 / NOPERCENT;
RUN;
%MEND FREQ;

What code would the SAS compiler see after this macro call?
%FREQ(FREQ,SALARIES,SALES)

43

Exercise Solution
PROC FREQ DATA=FREQ;
TABLES SALARIES*SALES / NOPERCENT;
RUN;

44

Macro Language Elements


Contd
How the Macro Processor Evaluates Arithmetic Expressions
The %EVAL function evaluates arithmetic expressions with
operands that represent integer values.
%let
%let
%let
%let

45

a=%eval(1+2);
b=%eval(10*3);
c=%eval(4/2);
i=%eval(5/3);

Question:
The following SAS program is submitted:
%let value = .5;
%let add = 5;
%let newval = %eval(&value + &add);
Which one of the following is the resulting value of the macro variable
NEWVAL?
A. 5
B. 5.5
C. .5 + 5
D. Null

46

Answer: D

47

SAS System Options


The MLOGIC system option displays macro execution
messages in the SAS log, including
macro intialization
parameter values
results of arithmetic and logical operations
macro termination.
General form of the MLOGIC | NOMLOGIC option:
OPTIONS MLOGIC;
OPTIONS NOMLOGIC;
The default setting is NOMLOGIC.

48

SAS System Options


Contd
The MPRINT option
General form of the MPRINT | NOMPRINT option:
OPTIONS MPRINT;
OPTIONS NOMPRINT;
The default setting is NOMPRINT.
The SYMBOLGEN option
General form of the SYMBOLGEN | NOSYMBOLGEN option:
OPTIONS SYMBOLGEN;
OPTIONS NOSYMBOLGEN;
The default setting is NOSYMBOLGEN.

49

Exercise:
Write any small macro program after setting all the three
options and check the log for results.

50

Call SYMPUT
CALL SYMPUT takes a value from a DATA step and
assigns it to a macro variable which you can then use later in your
program

Syntax:
CALL SYMPUT(macro-variable, value);

51

Example:
data _null_;
format var datetime.;
var=datetime();
call symput('date_time',var);
run;
%Put DateTime- &date_time;

52

Example:
The data corresponds to : Emergency room visits with doctor
names and charged amounts.
data ervisits;
input doctor $ charged;
datalines;
White 358
Smith 935
White 421
Jones 144
Smith 105
Jones 1234
;
run;

53

Question:
How we can get name of the First Doctor that visited the
Emergency Room into Macro Variable?

54

Solution:
data _null_;
set ervisits;
if _n_ = 1 then
call symput('frstdoc',doctor);
run;
%put First ER Visit on Record was treated by &frstdoc;
Log
The First ER Visit on Record was treated by White

55

The Select Clause INTO


Give SQL an interface to the SAS macro language.
SELECT <DISTINCT> object-item <,object-item>...
INTO :macro-variable-specification
<, :macro-variable-specification>...
Where :macro-variable-specification is one of the following:
:macro-variable <SEPARATED BY 'character' <NOTRIM>>;
:macro-variable-1 - :macro-variable-n <NOTRIM>;

56

Get First Value From Dataset into Macro


Variable
SQL will stop after selecting one value.
proc sql noprint;
SELECT doctor
INTO :frstdoc
from ervisits;
quit;
%put First ER Visit on Record was treated by &frstdoc;
LOG
The First ER Visit on Record was treated by White

57

Selecting ALL Values Into a Single Macro


Variable
The Separated clause inserts all values and separators.
proc sql noprint;
SELECT doctor
INTO :docs separated by ', '
from ervisits;
quit;
%put The Doctors who all Visited in sequence were: &docs;
LOG
The Doctors who all Visited in sequence were: White, Smith, White,
Jones, Smith, Jones

58

DISTINCT eliminates duplicates.


proc sql noprint;
SELECT distinct doctor
INTO :docs separated by ', '
from ervisits;
quit;
%put The Doctors who all Visited were: &docs;
LOG
The Doctors who all Visited in sequence were: White,
Smith, Jones

59

Question:

Given the SAS data set SAUSER.HIGWAY:


SASUSER.HIGHWAY

The following SAS program is submitted:


%macro highway;
proc sql nonprint;
%let numgrp=6;
select distinct status into:group1-:group&numgrp from sasuser.highway;
quit;

60

Question Contd
%do i=1 %to &numgrp;
proc print data =sasuser.highway;
where status ="&&group&I";
run;
%end;
%mend;
%highway
How many reports are produced?
A. 2
B. 6
C. 0
D. 5

61

Answer: A

62

Question:
The following SAS program is submitted:
options yearcutoff = 1950;
%macro y2kopt(date);
%if &date >= 14610 %then %do;
options yearcutoff = 2000;
%end;
%else %do;
options yearcutoff = 1900;
%end;
%mend;

63

Question Contd
data _null_ ;
date = "01jan2000"d;
call symput("date",left(date));
run;
%y2kopt(&date)
The SAS date for January 1, 2000 is 14610 and the SAS system option for
YEARCUTOFF is set to 1920 prior to submitting the above program. Which one of
the following is the value of YEARCUTOFF when the macro finishes execution?
A. 1900
B. 1920
C. 1950
D. 2000
Answer: D

64

Auto Call Macros:


SAS provides several methods to invoke external SAS macros in a
SAS program. There are two that are most often used:
1.Autocall

library
2. %Include statement

65

Telling SAS where Macros are


located
If you place all the files containing macros in
this location:
C:\Documents and Settings\XYZ\My Documents\SAS Macros\
and place the following statements in the autoexec.sas file:
filename statmacs 'C:\Documents and Settings\XYZ\My Documents\SAS
Macros\';
OPTIONS MAUTOSOURCE SASAUTOS=(STATMACS, SASAUTOS);
then you can call the macros when
desired.

66

% INCLUDE statement
Users can also use %INCLUDUE to include a macro stored in an
external file. Shown below are the syntax and sample code:
%INCLUDE source;
Eg.
%include 'c:\maclib\flag.sas' ;

67

Draft

Output
Delivery
System (ODS)
1. Integrate
your output.
Benefits
2. Customize content of your output.
3. Customize appearance of your output.
4. Improve your customer satisfaction

68

Output Delivery System (ODS)

Draft

ODS HTML FILE=.myfilename.html.;


proc tabulate data=census f=dollar8.;
class sex educ;
var income;
table educ=Education,
income=Average Salary*
mean= *
(sex= all);
run;

ODS HTML CLOSE;

69

Output Delivery System (ODS)

Draft

The ODS HTML result is the output shown below

70

Output Delivery System (ODS)

Draft

If you dont like this look, you can change it by switching styles. The table above uses the default style, which is called Default.. For a different look try:

ODS HTML FILE=.myfilename.html.


STYLE=BarrettsBlue;
* the TABULATE code goes here ;
ODS HTML CLOSE;

71

Output Delivery System (ODS)

Draft

72

Output Delivery System (ODS)

Draft

Embedded Images

73

Output Delivery System (ODS)

Draft

Embedded Links

74

Questions?

75

You might also like