Copyright © 2010 SAS Institute Inc. All rights reserved. SAS ® Macros: Top Ten Questions (and Answers!) Kevin Russell –Technical Support Analyst SAS Institute.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 9: Introducing Macro Variables 1 © Spring 2012 Imelda Go, John Grego, Jennifer Lasecki and the University of South Carolina.
Chapter 3: Editing and Debugging SAS Programs. Some useful tips of using Program Editor Add line number: In the Command Box, type num, enter. Save SAS.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Macro Processor.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 11: Creating and Using Macro Programs 1 STAT 541 ©Spring 2012 Imelda Go, John Grego, Jennifer Lasecki and the University of South Carolina.
Session 7, Chapter 6 From SAS 9.3 Macro Language Reference Macro Expressions P 71.
1 SAS Formats and SAS Macro Language HRP223 – 2011 November 9 th, 2011 Copyright © Leland Stanford Junior University. All rights reserved. Warning:
Chapter 10.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction.
Guide To UNIX Using Linux Third Edition
Basic And Advanced SAS Programming
Guide To UNIX Using Linux Third Edition
 2000 Prentice Hall, Inc. All rights reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction 13.2The #include Preprocessor Directive 13.3The.
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
Let SAS Do the Coding for You! Robert Williams Business Info Analyst Sr. WellPoint Inc.
Welcome to SAS…Session..!. What is SAS..! A Complete programming language with report formatting with statistical and mathematical capabilities.
“SAS macros are just text substitution!” “ARRRRGGHHH!!!”
I OWA S TATE U NIVERSITY Department of Animal Science Writing Flexible Codes with the SAS Macro Facility (Chapter in the 7 Little SAS Book) Animal Science.
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.
Copyright © 2008, SAS Institute Inc. All rights reserved. SAS ® Macros: Top-Five Questions (and Answers!) Kim Wilson –Technical Support Analyst SAS Institute.
SCSUG Avoiding Hand Cramps: Name2 macro and arrays for related variables November 9, am South Center SAS Users Group Austin, Texas.
Chapter 10:Processing Macro Variables at Execution Time 1 STAT 541 © Spring 2012 Imelda Go, John Grego, Jennifer Lasecki and the University of South Carolina.
Managing Passwords in the SAS System Allen Malone Senior Analyst/Programmer Kaiser Permanente.
SAS Workshop Lecture 1 Lecturer: Annie N. Simpson, MSc.
Introduction to Shell Script Programming
SAS Macro: Some Tips for Debugging Stat St. Paul’s Hospital April 2, 2007.
INTRODUCTION TO SAS MACRO PROCESSING James R. Bence, Ph.D., Co-Director Quantitative Fisheries Center Professor Department of Fisheries and Wildlife March.
1 JavaScript in Context. Server-Side Programming.
5/30/2010 SAS Macro Language Group 6 Pradnya Nimkar, Li Lin, Linsong Zhang & Loc Tran.
Macro Overview Mihaela Simion. Macro Facility Overview Definition : The SAS Macro Facility is a tool within base SAS software that contains the essential.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
Macro Variable Resolution Enio Presutto York University, Toronto, Canada.
Introduction to SAS Macros Center for Statistical Consulting Short Course April 15, 2004.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
BMTRY 789 Lecture 10: SAS MACRO Facility Annie N. Simpson, MSc.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
Copyright © 2010, SAS Institute Inc. All rights reserved. SAS ® Using the SAS Grid.
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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
© Oxford University Press All rights reserved. CHAPTER 10 THE PREPROCESSOR DIRECTIVE.
Do not put content on the brand signature area NOBS for Noobs David B. Horvath, CCP, MS PhilaSUG Winter 2015 Meeting NOBS for Noobs.
SAS Programming Training Instructor:Greg Grandits TA: Textbooks:The Little SAS Book, 5th Edition Applied Statistics and the SAS Programming Language, 5.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
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.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Lecture 3 Translation.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 5: Passing and Processing Macro Parameters
Basic Elements of C++.
Two “identical” programs
3 Macro Storage.
Conditional Processing
Fall 2017 Questions and Answers (Q&A)
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 ©
Creating Macro Variables in the DATA Step
Macro Variable’s scope
Defining and Calling a Macro
Global and Local Symbol Tables
Retrieving Macro Variables in the DATA Step
3 Iterative Processing.
Making Remote Processing Less Remote
How Best to Use Macro Quoting Functions?
Presentation transcript:

Copyright © 2010 SAS Institute Inc. All rights reserved. SAS ® Macros: Top Ten Questions (and Answers!) Kevin Russell –Technical Support Analyst SAS Institute Inc.

2 Copyright © 2010, SAS Institute Inc. All rights reserved. SAS® Macros: Top Ten Questions (and Answers!) 1.Can I use SAS functions within the macro facility? 2.What quoting function should I use to mask special characters? 3.How do I resolve a macro variable within single quotation marks? 4.How do I resolve error messages when output that was generated with the MPRINT system option looks fine? 5.What are the differences between the autocall facility and the stored compiled macro facility?

3 Copyright © 2010, SAS Institute Inc. All rights reserved. 6.How do I conditionally execute a macro from within a DATA step? 7.Why does my macro variable not resolve? 8.How can I use macros to loop through all files in a directory? 9.Can I use DATA step variables in a %IF-%THEN statement? 10.Why am I getting an error that states that a character operand was found in the %EVAL function or %IF condition where a numeric operand is required. SAS® Macros: Top Ten Questions (and Answers!)

4 Copyright © 2010, SAS Institute Inc. All rights reserved. Question 1: Can I use SAS functions within the macro facility? Answer: Yes, by using the %SYSFUNC macro function.

5 Copyright © 2010, SAS Institute Inc. All rights reserved. Example: %SYSFUNC macro function %put %sysfunc(date(),worddate20.); Output: 95 %put %sysfunc(date(),worddate20.); August 22, 2012

6 Copyright © 2010, SAS Institute Inc. All rights reserved. Question 2: What quoting function should I use to mask special characters such as the ampersand, percent sign, parentheses, commas and quotation marks? Answer: Depends. Use compile-time or execution- time quoting functions for your situation.

7 Copyright © 2010, SAS Institute Inc. All rights reserved.  Compile-time quoting functions:  %STR–masks commas, mnemonics, and unmatched quotation marks and parentheses.  %NRSTR–masks percent signs and ampersands in addition to the other special characters.  Execution-time quoting functions:  %BQUOTE–masks special characters and mnemonics in resolved values during macro execution.  %SUPERQ–masks special characters and mnemonics during macro execution. However, it also prevents further resolution of any macros or macro variables.

8 Copyright © 2010, SAS Institute Inc. All rights reserved. Example: Unmatched Quotation Mark (‘) %let singleq=O'neill; %put &singleq; Solution: %STR Function %let singleq=%str(O%'neill) %put &singleq; 3120 %put &singleq; O'neill

9 Copyright © 2010, SAS Institute Inc. All rights reserved. Example: Percent Sign (%) %let ex=This macro is called %showme; %put ex=&ex; 20 %let ex= This macro is called %showme; WARNING: Apparent invocation of macro SHOWME not resolved. 21 %put ex=&ex; WARNING: Apparent invocation of macro SHOWME not resolved. Solution: %NRSTR Function %let ex=%nrstr(This macro is called %showme); %put ex=&ex; 23 %let ex=%nrstr(This macro is called %showme); 24 %put ex=&ex; ex=This macro is called %showme

10 Copyright © 2010, SAS Institute Inc. All rights reserved. 31 %put WITH NO QUOTING FUNCTION:; WITH NO QUOTING FUNCTION: 32 %test(&x); ERROR: More positional parameters found than defined. Example: Commas (,) %macro test(value); %put &value; %mend; %let x=a,b,c; %put WITH NO QUOTING FUNCTION:; %test(&x); 34 %put WITH THE CORRECT QUOTING FUNCTION:; WITH THE CORRECT QUOTING FUNCTION: 35 %test(%bquote(&x)) a,b,c Solution: %BQUOTE Function %put WITH THE CORRECT QUOTING FUNCTION:; %test(%bquote(&x));

11 Copyright © 2010, SAS Institute Inc. All rights reserved. Example: Ampersand (&) data _null_; call symputx(‘Atlanta',‘Peaches&Cream'); run; %put NOT quoted:; %put &Atlanta; 5 %put NOT quoted:; NOT quoted: 6 %put &Atlanta; WARNING: Apparent symbolic reference CREAM not resolved. Peaches&Cream Solution: %SUPERQ Function %put THIS is quoted:; %put %superq(Atlanta); 8 %put THIS is quoted:; THIS is quoted: 9 %put %superq(Atlanta); Peaches&Cream

12 Copyright © 2010, SAS Institute Inc. All rights reserved. Question 3: How do I resolve a macro variable within single quotation marks? Answer: Use the %STR function

13 Copyright © 2010, SAS Institute Inc. All rights reserved. %let name=Fred; %put %str(%‘NAME: &name%'); 17 %put %str(%’NAME:&name%'); 'NAME: Fred' Example: %STR function

14 Copyright © 2010, SAS Institute Inc. All rights reserved. Question 4: How do I resolve error messages when output that was generated with the MPRINT system option looks fine? Answer: Use the %UNQUOTE function.

15 Copyright © 2010, SAS Institute Inc. All rights reserved. options mprint; %macro test; %let val=aaa; %let test = %str(%'&val%'); data _null_; val = &test; put val=; run; %mend test; %test Example: %UNQUOTE function NOTE: Line generated by the macro variable "TEST". 596 'aaa' - MPRINT(TEST): val = 'aaa'; ERROR : Expecting an arithmetic expression.

16 Copyright © 2010, SAS Institute Inc. All rights reserved. Solution: %UNQUOTE Function options mprint; %macro test; %let val = aaa; %let test = %unquote(%str(%'&val%')); data _null_; val = &test; put val=; run; %mend test; %test

17 Copyright © 2010, SAS Institute Inc. All rights reserved. Question 5: What are the differences between the autocall facility and the stored compiled macro facility? Answer: The differences are in the features for each facility.

18 Copyright © 2010, SAS Institute Inc. All rights reserved. Features Autocall Facility Stored Compiled Macro Facility Easy to maintain if code is shared YesMaybe Easy to hide code to the end user NoYes Uses less overheadNoYes Easy to transfer across platforms and releases of SAS YesNo Autocall Facility vs. Stored Compiled Macro Facility

19 Copyright © 2010, SAS Institute Inc. All rights reserved. Links that explain how to create Autocall and Stored Compiled Macro Libraries. Usage note number: Creating an autocall macro library on the PC Usage note number: How to create a stored compiled macro library

20 Copyright © 2010, SAS Institute Inc. All rights reserved. Autocall Facility  Macro source code is implicitly included and compiled to the WORK.SASMACR catalog.  To use autocall macros, you have to set the MAUTOSOURCE and the SASAUTOS= system options.  The MAUTOSOURCE option activates the autocall facility.  The SASAUTOS= option specifies the autocall library or libraries.  To use the autocall facility, submit the following statements: filename fileref ‘autocall-library-path’; options mautosource sasautos=(sasautos fileref);

21 Copyright © 2010, SAS Institute Inc. All rights reserved. Stored Compiled Macro Facility  The stored compiled macro facility provides access to permanent SAS catalogs from which you can invoke compiled macros directly.  To use these stored compiled macros, you have to set the MSTORED and the SASMSTORE= system options.  The MSTORED option searches for the compiled macros in a SAS catalog that you reference with the SASMSTORE= option.  The SASMSTORE= option specifies the libref for the SAS library that contains the stored compiled macros.  To use the stored compiled macro facility, submit the following statements: libname libref ‘SAS-data-library-path’; options mstored sasmstore=libref;

22 Copyright © 2010, SAS Institute Inc. All rights reserved. Question 6: How do I conditionally execute a macro from within a DATA step? Answer: Use the CALL EXECUTE routine.

23 Copyright © 2010, SAS Institute Inc. All rights reserved. /* Compile the macro BREAK. The BYVAL */ /* parameter is generated in the CALL */ /* EXECUTE routine. */ %macro break(byval); data age_&byval; set sorted(where=(age=&byval)); run; %mend; proc sort data=sashelp.class out=sorted; by age; run; options mprint; data _null_; set sorted; by age; if first.age then call execute(‘%break(‘||age||’)’); run; Example: CALL EXECUTE routine

24 Copyright © 2010, SAS Institute Inc. All rights reserved. MPRINT(BREAK): data age_11; MPRINT(BREAK): set sorted(where=(age=11)); MPRINT(BREAK): run; MPRINT(BREAK): data age_12; MPRINT(BREAK): set sorted(where=(age=12)); MPRINT(BREAK): run; MPRINT(BREAK): data age_13; MPRINT(BREAK): set sorted(where=(age=13)); MPRINT(BREAK): run; MPRINT(BREAK): data age_14; MPRINT(BREAK): set sorted(where=(age=14)); MPRINT(BREAK): run; MPRINT(BREAK): data age_15; MPRINT(BREAK): set sorted(where=(age=15)); MPRINT(BREAK): run; MPRINT(BREAK): data age_16; MPRINT(BREAK): set sorted(where=(age=16)); MPRINT(BREAK): run; Output:

25 Copyright © 2010, SAS Institute Inc. All rights reserved. Question 7: Why does my macro variable not resolve? Answer: The macro variable might not resolve for a few reasons:  macro variable scope  no step boundary  timing issues

26 Copyright © 2010, SAS Institute Inc. All rights reserved.  Macro variable scope: Local macro variables versus global macro variables.  No step boundary: The DATA step does not have an ending RUN statement before a CALL SYMPUT or a CALL SYMPUTX routine.  Timing issues: a result of using the CALL EXECUTE and CALL SYMPUT routines together. Debugging Options:  %PUT _USER_;  %PUT _GLOBAL_;  %PUT _LOCAL_;  %PUT _ALL_;  %PUT _AUTOMATIC_; Reasons for Macro Variable Not Resolving:

27 Copyright © 2010, SAS Institute Inc. All rights reserved. Macro Variable Scope  Local macro variables are not available outside of the macros in which they are defined. Such a macro variable only exists as long as its associated macro is executing. 1 %macro showme(test); 2 %let inside=RESOLVE ME.; 3 %put this shows INSIDE: &INSIDE; 4 %mend; 5 6 %showme(VALUE) this shows INSIDE: RESOLVE ME. 7 %put &inside; WARNING: Apparent symbolic reference INSIDE not resolved. &inside %macro showme(test); %let inside=RESOLVE ME.; %put this shows INSIDE: &INSIDE; %mend; %global inside; %showme(VALUE) %put &inside;  Global macro variables are available throughout an entire SAS session.

28 Copyright © 2010, SAS Institute Inc. All rights reserved. No Step Boundary Example: No RUN statement before %PUT statement: data test; x="MYVALUE"; call symputx('macvar',x); %put WILL I RESOLVE &macvar?; 57 %put WILL I RESOLVE &macvar?; WARNING: Apparent symbolic reference MACVAR not resolved. Output: data test; x="MYVALUE"; call symputx('macvar',x); run; %put WILL I RESOLVE &macvar?; Example: RUN statement before %PUT statement 14 %put WILL I RESOLVE &macvar?; WILL I RESOLVE MYVALUE? Output:

29 Copyright © 2010, SAS Institute Inc. All rights reserved. data names; input code name $; cards; 1 first 2 second 3 third ; %macro report(munc); data check; set names(where=(code=&munc)); call symput ('namemac', name); run; %if &namemac ne %then %do; proc print data=check; title "data for &namemac"; run; %end; %mend report; data _null_ ; set names; call execute('%report('||code||')'); run; data check; set names(where=(code=1); call symput(‘namemac’,name); run; Warning and error / stop macro Input stack Common Issue with the CALL SYMPUT and CALL EXECUTE Routines %report(1) Timing Issue

30 Copyright © 2010, SAS Institute Inc. All rights reserved. Timing Issue WARNING: Apparent symbolic reference NAMEMAC not resolved. ERROR: A character operand was found in the %EVAL Function or %IF condition where a numeric operand is required. The Condition was:&namemac ne ERROR: The macro REPORT will stop executing. Solution: Use %NRSTR Bad Code %macro report(munc); data check; set names(where=(code=&munc)); call symput ('namemac', name); run; %if &namemac ne %then %do; proc print data=check; title "data for &namemac"; run; %end; %mend report; data _null_; set names; call execute('%report('||code||')'); run; Good Code %macro report(munc); data check; set names(where=(code=&munc)); call symput ('namemac', name); run; %if &namemac ne %then %do; proc print data=check; title "data for &namemac"; run; %end; %mend report; data _null_; set names; call execute(‘%nrstr(%report ('||code||'))'); run;

31 Copyright © 2010, SAS Institute Inc. All rights reserved. Question 8: How can I use macros to loop through all files in a directory? Answer: Use the %DO statement.

32 Copyright © 2010, SAS Institute Inc. All rights reserved. %macro drive(dir,ext); %let filrf=mydir; %let rc=%sysfunc(filename(filrf,&dir)); %let did=%sysfunc(dopen(&filrf)); %let memcnt=%sysfunc(dnum(&did)); %do i = 1 %to &memcnt; %let name=%qscan(%qsysfunc(dread(&did,&i)),-1,.); %if %qupcase(%qsysfunc(dread(&did,&i))) ne %qupcase(&ext) %then %do; %if (%superq(ext) ne and %qupcase(&name) = %qupcase(&ext)) or (%superq(ext) = and %superq(name) ne) %then %do; %put %qsysfunc(dread(&did,&i)); %end; %let rc=%sysfunc(dclose(&did)); %mend drive; %drive(c:\,sas) Example: %DO statement

33 Copyright © 2010, SAS Institute Inc. All rights reserved. Link to sample on previous slide. Sample number: Listing all the files that are located in a specific directory

34 Copyright © 2010, SAS Institute Inc. All rights reserved. Question 9: Can I use DATA step variables in a %IF-%THEN statement? Answer: No, DATA step variables cannot be used in %IF-%THEN statements.

35 Copyright © 2010, SAS Institute Inc. All rights reserved. %macro test; data sample; text=“OPEN”; %if TEXT=OPEN %then %do; %put TRUE?; %end; run; %mend; Example: DATA step variable in %IF-%THEN statement

36 Copyright © 2010, SAS Institute Inc. All rights reserved. %IF-%THEN statement vs. IF-THEN statement %IF-%THEN Statement IF-THEN Statement  Conditionally executes SAS statements during DATA step execution.  Conditionally generates text.  Expression can only contain operands that are constant text or text expressions that generate text.  Expression can only contain operands that are DATA step variables, character or numeric constants, or date and time constants.  Executes during DATA step execution. If the statement is contained within a macro, it is stored as text.  Cannot refer to DATA step variables.  Executes during macro execution. If the statement is contained in a DATA step, it is executed before DATA step compilation.

37 Copyright © 2010, SAS Institute Inc. All rights reserved. Question 10: How do I resolve an error stating that a character operand was found in the %EVAL function or %IF condition where a numeric operand is required ? Answer: Use the %SYSEVALF function.

38 Copyright © 2010, SAS Institute Inc. All rights reserved. %macro test(val); %if &val < 0 %then %put TRUE; %mend test; %test(-1.2) 99 %test(-1.2) ERROR: A character operand was found in the %EVAL function or %IF condition where a numeric operand is required. The condition was: &val < 0 ERROR: The macro TEST will stop executing. Example: %SYSEVALF function Solution: %macro test(val); %if %sysevalf(&val < 0) %then %put TRUE; %mend test; %test(-1.2) 673 %macro test(val); 674 %if %sysevalf(&val < 0) %then %put TRUE; 675 %mend test; 676 %test(-1.2) TRUE

39 Copyright © 2010, SAS Institute Inc. All rights reserved. References Question 2: What quoting function should I use to mask special characters? SAS Usage Note 31012, “An error occurs when a comma is present in the value of a parameter being passed to a macro.” Cary, NC: SAS Institute Inc. Available at support.sas.com/kb/31/012.html. Question 3: How do I resolve a macro variable within single quotation marks? SAS Sample 25076, “Resolve a macro variable within single quotes.” Cary, NC: SAS Institute Inc. Available at support.sas.com/kb/25/076.html. Question 5: What are the differences between the autocall facility and the stored compiled facility? SAS Usage Note 445, “How to have shared access with the stored compiled macro facility.” Cary, NC: SAS Institute Inc. Available at support.sas.com/kb/00/445.html. SAS Usage Note 23210, “How to hide macro code so that it does not appear in the log when the program is executed.” Cary, NC: SAS Institute Inc. Available at support.sas.com/kb/23/210.html. SAS Usage Note 24451, “Creating an autocall macro on a PC.” Cary, NC: SAS Institute Inc. Available at support.sas.com/kb/24/451.html. Question 6: How do I conditionally execute a macro from within a DATA step? SAS Sample 26140, “Creating a new data set for each BY group in a data set.” Cary, NC: SAS Institute Inc. Available at support.sas.com/kb/26/140.html. Question 7: Why does my macro variable not resolve? SAS Usage Note 23134, “Macro variables created with the CALL SYMPUT routine do not resolve when invoked by the CALL EXECUTE routine.” Cary, NC: SAS Institute Inc. Available at support.sas.com/kb/23/134.html. Question 8: How can I use macros to loop through all files in a directory? SAS Sample 25074, “Listing all files that are located in a specific directory.” Cary, NC: SAS Institute Inc. Available at support.sas.com/kb/25/074.html.

40 Copyright © 2010, SAS Institute Inc. All rights reserved. Recommended Reading Burlew, Michelle SAS Macro Programming Made Easy, Second Edition. Cary, NC: SAS Press. Carpenter, Art Carpenter's Complete Guide to the SAS ® Macro Language, Second Edition. Cary, NC: SAS Press. Tyndall, Russ. Give Your Macro Code an Extreme Makeover: Tips for even the most seasoned macro programmer. Cary, NC: SAS Institute Inc. Available at support.sas.com/techsup/technote/ts739.pdf.

Copyright © 2010 SAS Institute Inc. All rights reserved. Questions?