380 likes | 416 Views
Learn how to create SAS macros that generate code based on system, parameter, and data values for automating data processing. Includes conditional logic with %IF-%THEN and %ELSE statements.
E N D
4 Conditional Processing
Macros – So Far %macroallmns(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. 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 procsql; title"Order dates on orion.order_fact"; select min(order_date) format= mmddyy8., max(order_date) format= mmddyy8. fromorion.order_fact; select today()-max(order_date) into :diff fromorion.order_fact; quit; title; %put No of days between yesterday and max order date: &diff;
Update the data datarecent_orders; setorion.order_fact; order_date=order_date+&diff;/*make last order today*/; run; procsql; select min(order_date) asfirst_date format=mmddyy10., max(order_date) aslast_date format=mmddyy10. fromrecent_orders; ; quit;
Macro-Level Programming Always print the daily report procprintdata=recent_orders; whereorder_date="&sysdate9"d; varproduct_idtotal_retail_price; title"Daily sales: &sysdate9"; run; title; procmeansdata=recent_ordersnsummean; whereorder_date between "&sysdate9"d - 6 and "&sysdate9"d; var quantity total_retail_price; title"Weekly sales: &sysdate9"; run; title; Is itFriday? 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 procprintdata=recent_orders; whereorder_date="&sysdate9"d; varproduct_idtotal_retail_price; title"Daily sales: &sysdate9"; run; procmeansdata=recent_ordersnsummean; whereorder_date between "&sysdate9"d - 6 and "&sysdate9"d; var quantity total_retail_price; title"Weekly sales: &sysdate9"; run; Is itFriday? Yes
Processing Complete Steps %macrodaily; proc print data=recent_orders; where order_date="&sysdate9"d; varproduct_idtotal_retail_price; title "Daily sales: &sysdate9"; run; title; %mend daily; %daily Method 1: Create separate macros continued...
%macroweekly; • 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. %macroreports; %daily %if &sysday=Friday %then %weekly; %mend reports; %reports • Note: • Character constants are not quoted • Character constants are case sensitive.
The mlogic option %macroreports; %daily %if &sysday=Friday %then %weekly; %mend reports; optionsmlogic; %reports optionsnomlogic;
The MPRINT option (review) %macroreports; %daily %if &sysday=Friday %then %weekly; %mend reports; optionsmprint; %reports optionsnomprint;
%macroreports; %daily %if &sysday=Friday %then %weekly; %mend reports; optionsmlogicmprint; %reports optionsnomlogicnomprint;
A commonly made error. %macroreports; %daily %if &sysday=Friday then %weekly; %mend reports;
Processing Complete Steps Method 1: Write a third macro that always calls the DAILY macro and conditionally calls the WEEKLY macro. %macroreports; %daily %if &sysday=Friday %then %weekly; %mend reports; %reports • 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; statement;statement;... %END;
Processing Complete Steps Method 2: Use a single macro to generate the daily report unconditionally and the weekly report on Friday. %macroreports; proc print data=recent_orders; where order_date="&sysdate9"d; varproduct_idtotal_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"; run; title; %end; %mend reports; %reports
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 thephysical name or filerefof 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; optionsmacrogen; %macroreports; %include"&path\daily.sas"; %if &sysday=Friday %then%do; %include"&path\weekly.sas"; %end; %mend reports; %reports optionsnomacrogen;
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 thephysical name or filerefof 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; %macroreports; %include"&path\daily.sas" /source2; %if &sysday=Friday %then%do; %include"&path\weekly.sas" /source2; %end; %mend reports; %reports
The %INCLUDE Statement The %INCLUDEstatement Copies SAS statements from an external file to the input stack Is a global SAS statement Is not a macro language statement
A useful feature multiple where statements datatmp; set fram.frex4; where age >50; where male; run; procfreqdata=tmp; tables male; run; procmeansdata=tmp; var age; run;
The same keyword datatmp; set fram.frex4; where age >50; where same and male; run; procfreqdata=tmp; tables male; run; procmeansdata=tmp; var age; run;
Processing Complete Statements %macro count(type=,start=01jan2014,stop=31dec2014); procfreq 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; %end; run; title; %mend count;
optionsmprintmlogic; • %count() • %count(type=3) • optionsnomprintnomlogic;
%macrocust(place); %let place=%upcase(&place); data customers; set orion.customer; %if &place=US %then%do; where country='US'; keep customer_namecustomer_address country; %end; %else%do; where country ne 'US'; keep customer_namecustomer_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'; %end; run; %mendcust; Processing Complete Statements
optionsmprint; %cust(us) procsql; selectdistinct country fromcustomers;quit; %cust(international) procsql; selectdistinct country from customers; quit; optionsnomprint;
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. optionsmprint; %macro counts(rows); title 'Customer Counts by Gender'; procfreq data=orion.customer_dim; tables %if &rows ne %then &rows *; customer_gender; run; %mend counts; %counts() %counts(customer_age_group) optionsnomprint;