Conditional Processing

Slides:



Advertisements
Similar presentations
Chapter 9: Introducing Macro Variables 1 © Spring 2012 Imelda Go, John Grego, Jennifer Lasecki and the University of South Carolina.
Advertisements

Chapter 11: Creating and Using Macro Programs 1 STAT 541 ©Spring 2012 Imelda Go, John Grego, Jennifer Lasecki and the University of South Carolina.
CSC110 Fall Chapter 5: Decision Visual Basic.NET.
Introduction to SQL Session 1 Retrieving Data From a Single Table.
“SAS macros are just text substitution!” “ARRRRGGHHH!!!”
1 Chapter 3: Macro Definitions 3.1 Defining and Calling a Macro 3.2 Macro Parameters 3.3 Macro Storage (Self-Study)
Computing for Research I Spring 2014 January 22, 2014.
SAS Macros ® 101 How I learned to stop worrying and love macros Alex Chaplin BCS USA Section.
1 Chapter 5: Macro Programs 5.1 Conditional Processing 5.2 Parameter Validation 5.3 Iterative Processing 5.4 Global and Local Symbol Tables.
Question 10 What do I write?. Spreadsheet Make sure that you have got a printout of your spreadsheet - no spreadsheet, no marks!
SAS Macro: Some Tips for Debugging Stat St. Paul’s Hospital April 2, 2007.
5/30/2010 SAS Macro Language Group 6 Pradnya Nimkar, Li Lin, Linsong Zhang & Loc Tran.
SQL Chapter Two. Overview Basic Structure Verifying Statements Specifying Columns Specifying Rows.
Introduction to SAS Macros Center for Statistical Consulting Short Course April 15, 2004.
Chapter 7: Macros in SAS  Macros provide for more flexible programming in SAS  Macros make SAS more “object-oriented”, like R 1 © Fall 2011 John Grego.
FOR MONDAY: Be prepared to hand in a one-page summary of the data you are going to use for your project and your questions to be addressed in the project.
FORMAT statements can be used to change the look of your output –if FORMAT is in the DATA step, then the formats are permanent and stored with the dataset.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Based on Learning SAS by Example: A Programmer’s Guide Chapters 1 & 2
SAS ® 101 Based on Learning SAS by Example: A Programmer’s Guide Chapter 25 By Tasha Chapman, Oregon Health Authority.
SAS ® 101 Based on Learning SAS by Example: A Programmer’s Guide Chapters 3 & 4 By Tasha Chapman, Oregon Health Authority.
JavaScript: Conditionals contd.
Web Database Programming Using PHP
VISUAL BASIC 6.0 Designed by Mrinal Kanti Nath.
Session 1 Retrieving Data From a Single Table
Definition of the Programming Language CPRL
User-Written Functions
Chapter 5: Passing and Processing Macro Parameters
Topics Introduction to Functions Defining and Calling a Void Function
Writing Basic SQL SELECT Statements
Chapter 2 - Introduction to C Programming
Web Database Programming Using PHP
Python: Control Structures
EGR 2261 Unit 4 Control Structures I: Selection
The Selection Structure
Functions CIS 40 – Introduction to Programming in Python
Two “identical” programs
Chapter 3: Working With Your Data
Chapter 2 - Introduction to C Programming
Microsoft Access Illustrated
Basic Queries Specifying Columns
Creating Macro Variables in SQL (Review)
Chapter 18: Modifying SAS Data Sets and Tracking Changes
3 Macro Storage.
Tamara Arenovich Tony Panzarella
Chapter 10 Programming Fundamentals with JavaScript
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 7: Macros in SAS Macros provide for more flexible programming in SAS Macros make SAS more “object-oriented”, like R Not a strong suit of text ©
Data Types, Identifiers, and Expressions
3 Macro Parameters.
WEB PROGRAMMING JavaScript.
Chapter 7 Additional Control Structures
Indirect References to Macro Variables
Introduction to SAS A SAS program is a list of SAS statements executed in order Every SAS statement ends with a semicolon! SAS statements can be in caps.
Creating Macro Variables in the DATA Step
PHP.
Defining and Calling a Macro
Global and Local Symbol Tables
Retrieving Macro Variables in the DATA Step
3 Iterative Processing.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Fundamentals of visual basic
3 Parameter Validation.
Core Objects, Variables, Input, and Output
A Useful Footnote Martha Cox Population Health Research Unit Community Health & Epidemiology Dalhousie University Good morning. We've all had this happen:
Topics Introduction to Functions Defining and Calling a Function
Passing Simple and Complex Parameters In and Out of Macros
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Restricting and Sorting Data
Presentation transcript:

Conditional Processing 4 Conditional Processing

Macros – So Far %macro allmns(dat); /*get basic data on numeric variables*/ title "Numeric Variables, dataset: &dat"; proc means data=&dat; run; title; %mend;

Conditionally create SAS code within a macro program Conditionally create SAS code within a macro program. Insert entire steps, entire statements, and partial statements into a SAS program.

Macro-Level Programming Macro-level programming can generate code conditionally, based on: system values parameter values data values

Example: Orion Star submits a program every night to report daily sales. Every Friday, a second program is submitted to summarize weekly sales. Automate the application so that only one program is required.

The original data proc sql; title "Order dates on orion.order_fact"; select min(order_date) format= mmddyy8., max(order_date) format= mmddyy8. from orion.order_fact; select today()-max(order_date) into :diff quit; title; %put No of days between yesterday and max order date: &diff;

Update the data data recent_orders; set orion.order_fact; order_date=order_date+&diff;/*make last order today*/; run; proc sql; select min(order_date) as first_date format=mmddyy10., max(order_date) as last_date format=mmddyy10. from recent_orders; ; quit;

Macro-Level Programming Always print the daily report proc print data=recent_orders; where order_date="&sysdate9"d; var product_id total_retail_price; title "Daily sales: &sysdate9"; run; title; proc means data=recent_orders n sum mean; where order_date between "&sysdate9"d - 6 and "&sysdate9"d; var quantity total_retail_price; title "Weekly sales: &sysdate9"; run; title; Is it Friday? Yes

Conditional Processing %IF-%THEN and %ELSE statements. Conditional processing is performed with General form of %IF-%THEN and %ELSE statements: expression can be any valid macro expression. The %ELSE statement is optional. These macro language statements can be used only inside a macro definition. %IF expression %THEN action; %ELSE action;

Macro Expressions Similarities to SAS expressions: arithmetic operators logical operators (Do not precede AND or OR with %.) comparison operators (symbols and mnemonics) case sensitivity special WHERE operators not valid Differences compared to SAS expressions: Character operands are not quoted. Ranges such as 1 <= &x <= 10 behave differently. The IN operator does not require parentheses.

Conditional Processing Actions that can follow the keywords %THEN and %ELSE: a macro language statement a macro variable reference a macro call any text

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

Macro-Level Programming Always print the daily report proc print data=recent_orders; where order_date="&sysdate9"d; var product_id total_retail_price; title "Daily sales: &sysdate9"; run; proc means data=recent_orders n sum mean; where order_date between "&sysdate9"d - 6 and "&sysdate9"d; var quantity total_retail_price; title "Weekly sales: &sysdate9"; run; Is it Friday? Yes

Processing Complete Steps Method 1: Create separate macros %macro daily; proc print data=recent_orders; where order_date="&sysdate9"d; var product_id total_retail_price; title "Daily sales: &sysdate9"; run; title; %mend daily; %daily These two macros contain only sascode (text); not much different than in chapter 3. continued...

%macro weekly; proc means data=recent_orders n sum mean; where order_date between "&sysdate9"d - 6 and "&sysdate9"d; var quantity total_retail_price; title "Weekly sales: &sysdate9"; run; title; %mend weekly; %weekly

Processing Complete Steps Method 1: Write a third macro that always calls the DAILY macro and conditionally calls the WEEKLY macro. %macro reports; %daily %if &sysday=Friday %then %weekly; %mend reports; %reports This is a true macro program, with a macro call and a macro language statement. This macro contains no sascode (text). This is a "system driven" macro insofar as it is driven by or makes a decision according to system information, such as the day of the week. Note: Character constants are not quoted Character constants are case sensitive.

The mlogic option %macro reports; %daily %if &sysday=Friday %then %weekly; %mend reports; options mlogic; %reports options nomlogic;

The MPRINT option (review) %macro reports; %daily %if &sysday=Friday %then %weekly; %mend reports; options mprint; %reports options nomprint;

%macro reports; %daily %if &sysday=Friday %then %weekly; %mend reports; options mlogic mprint; %reports options nomlogic nomprint;

A commonly made error. %macro reports; %daily %if &sysday=Friday then %weekly; %mend reports; Type answer here

Processing Complete Steps Method 1: Write a third macro that always calls the DAILY macro and conditionally calls the WEEKLY macro. %macro reports; %daily %if &sysday=Friday %then %weekly; %mend reports; %reports This is a true macro program, with a macro call and a macro language statement. This macro contains no sascode (text). This is a "system driven" macro insofar as it is driven by or makes a decision according to system information, such as the day of the week. Note: Character constants are not quoted Character constants are case sensitive.

Conditional Processing %IF-%THEN and %ELSE statements. Conditional processing is performed with General form of %IF-%THEN and %ELSE statements: expression can be any valid macro expression. The %ELSE statement is optional. These macro language statements can be used only inside a macro definition. %IF expression %THEN action; %ELSE action;

Conditional Processing Use %DO and %END statements following %THEN or %ELSE to generate text that contains semicolons. %IF expression %THEN %DO; statement; statement;... %END; %ELSE %DO;

Processing Complete Steps Method 2: Use a single macro to generate the daily report unconditionally and the weekly report on Friday. %macro reports; proc print data=recent_orders; where order_date="&sysdate9"d; var product_id total_retail_price; title "Daily sales: &sysdate9"; run; title; %if &sysday=Friday %then %do; proc means data=recent_orders n sum mean; where order_date between "&sysdate9"d - 6 and "&sysdate9"d; var quantity total_retail_price; title "Weekly sales: &sysdate9"; %end; %mend reports; %reports Here is a second approach to the same application ("Method 2"). The advantage is that this is a single macro, not three macros as in "Method 1". This is a common technique.

The %INCLUDE Statement The %INCLUDE statement retrieves SAS source code from an external file and places it on the input stack. %INCLUDE file-specification < / SOURCE2 >; file-specification is the physical name or fileref of the file to be retrieved and placed on the input stack. SOURCE2 requests inserted SAS statements to appear in the SAS log.

Processing Complete Statements Method 3: Store the production SAS programs in external files. Copy those files to the input stack with %INCLUDE statements. %let path=c:\users\dlm1\dropbox\tmp; options macrogen; %macro reports; %include "&path\daily.sas"; %if &sysday=Friday %then %do; %include "&path\weekly.sas"; %end; %mend reports; %reports options nomacrogen; This is a modular approach. Warning: %INCLUDE may LOOK like a macro language statement, but it is NOT. It is a global SAS statement. Offer your sincere apologies to anyone who is confused.

The %INCLUDE Statement The %INCLUDE statement retrieves SAS source code from an external file and places it on the input stack. %INCLUDE file-specification < / SOURCE2 >; file-specification is the physical name or fileref of the file to be retrieved and placed on the input stack. SOURCE2 requests inserted SAS statements to appear in the SAS log.

%let path=c:\users\dlm1\dropbox\tmp; %macro reports; %include "&path\daily.sas" /source2; %if &sysday=Friday %then %do; %include "&path\weekly.sas" /source2; %end; %mend reports; %reports

The %INCLUDE Statement The %INCLUDE statement Copies SAS statements from an external file to the input stack Is a global SAS statement Is not a macro language statement

Processing Complete Statements

A useful feature multiple where statements data tmp; set fram.frex4; where age >50; where male; run; proc freq data=tmp; tables male; proc means data=tmp; var age;

The same keyword data tmp; set fram.frex4; where age >50; where same and male; run; proc freq data=tmp; tables male; proc means data=tmp; var age;

Processing Complete Statements %macro count(type=,start=01jan2014,stop=31dec2014); proc freq data=recent_orders; where order_date between "&start"d and "&stop"d; table quantity; title1 "Orders from &start to &stop"; %if &type= %then %do; title2 "For All Order Types"; %end; %else %do; title2 "For Order Type &type Only"; where same and order_type=&type; run; title; %mend count; Note the SAME AND argument in the highlighted WHERE statement. The log will contain a note that the WHERE clause has been augmented. The affect is like "ANDing" the WHERE clauses together. This is a "parameter driven" macro insofar as it is driven by or makes a decision according to a parameter value.

options mprint mlogic; %count() %count(type=3) options nomprint nomlogic;

Processing Complete Statements %macro cust(place); %let place=%upcase(&place); data customers; set orion.customer; %if &place=US %then %do; where country='US'; keep customer_name customer_address country; %end; %else %do; where country ne 'US'; keep customer_name customer_address country location; length location $ 12; if country="AU" then location='Australia'; else if country="CA" then location='Canada'; else if country="DE" then location='Germany'; else if country="IL" then location='Israel'; else if country="TR" then location='Turkey'; else if country="ZA" then location='South Africa'; run; %mend cust; Processing Complete Statements This example is conceptually no different than the previous example. The previous example featured a proc step and this example features a data step. Otherwise, same concept. One purpose here is to present both %if-%then and if-then in the same program. Students should understand the difference. An upcoming quiz addresses this. Also note the parameter values on the macro call are typed in lower case. Would it make a difference if they were typed in upper case or mixed case? No. Note the %upcase function at the top of the macro. One way to look at this application, as well as the previous applications in this chapter, is that this program is really two programs in one. Depending on the parameter value, one DATA step is generated, or an entirely different DATA step is generated. This is clearly illustrated on the next two slides. The macro language makes this benefit possible.

options mprint; %cust(us) proc sql; select distinct country from customers;quit; %cust(international) from customers; quit; options nomprint;

Processing Partial Statements

Processing Partial Statements Conditionally insert text into the middle of a statement. Generate either a one-way or two-way frequency table, depending on parameter values. options mprint; %macro counts(rows); title 'Customer Counts by Gender'; proc freq data=orion.customer_dim; tables %if &rows ne %then &rows *; customer_gender; run; %mend counts; %counts() %counts(customer_age_group) options nomprint; Here again, a single program is really two programs in one. Made possible by the macro facility.