sas macros final
DESCRIPTION
A detailed presentation of the SAS MACROs.TRANSCRIPT
SAS MACROSBY:
GURBEER SINGH
1
2
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
3
4
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
5
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.
6
User-Defined Macro VariablesThese 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;
);
7
8
User-Defined Macro Variables Contd…
Few other ways to define a macro variables:
%LOCAL statement %GLOBAL statement %MACRO statement SYMPUT routine INTO clause
9
Macro Variable ReferenceAfter a macro variable is created, the variable is referenced with an ampersand preceding its name (&var-name), 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
10
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.
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. b
2. b
3. c
4. b
5. c
6. bc7. 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 ProblemProblem: 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 10JIM 10
;PROC PRINT DATA=&NAME;
TITLE "PRINT OF DATASET &NAME";RUN;
18
The Generated SAS CodeDATA 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
20
Defining a MacroA macro or macro definition enables you to write macro programs.
General form of a macro definition:
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.
%MACRO macro-name; macro-text%MEND <macro-name>;
%MACRO macro-name; macro-text%MEND <macro-name>;
21
Macro CompilationWhen 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.
SAS/Macros(Passing Parameters)
Passing Information into a Macro Using ParametersA 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
23
Macro ParametersGeneral form of a macro call with parameters:
Parameter values are parenthesized comma-delimited.
Parameter values can be any text, null values, macro variable references, or macro calls.
%macro-name(value-1, … value-n)%macro-name(value-1, … value-n)
24
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.
25
Local Macro Variables
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
26
Global Macro Variables
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.
27
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
Automatic macro variables
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
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:
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
33
Quick QuizDoes a %LET statement outside of a macro program create a macro variable in the global or local symbol table?
34
Quick Quiz - AnswerDoes a %LET outside of a macro program create a macro variable in the global or local symbol table? GLOBAL
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;
These statements can only be used inside a macro
38
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 CodePROC 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 CodePROC 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 ExercisesExercise :• 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
45
Macro Language Elements Contd…
How the Macro Processor Evaluates Arithmetic Expressions
The %EVAL function evaluates arithmetic expressions with operands that represent integer values.
%let a=%eval(1+2);
%let b=%eval(10*3);
%let c=%eval(4/2);
%let 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
48
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.
49
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.
Exercise:
Write any small macro program after setting all the three options and check the log for results.
50
Call SYMPUTCALL 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 INTOGive 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 VariableThe 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 arelocatedIf 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 statementUsers 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
DraftOutput Delivery System (ODS) Benefits
1. Integrate your output.
2. Customize content of your output.
3. Customize appearance of your output.
4. Improve your customer satisfaction
68
Draft
Output Delivery System (ODS)
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
Draft
Output Delivery System (ODS)
The ODS HTML result is the output shown below
70
Draft
Output Delivery System (ODS)• If you don’t 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
Draft
Output Delivery System (ODS)
72
Draft
Output Delivery System (ODS)
• Embedded Images
73
Draft
Output Delivery System (ODS)
• Embedded Links
74
Questions?
75