Chapter 11: Creating and Using Macro Programs 1 STAT 541 ©Spring 2012 Imelda Go, John Grego, Jennifer Lasecki and the University of South Carolina.

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 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.
SYSTEM PROGRAMMING & SYSTEM ADMINISTRATION
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
VBA Modules, Functions, Variables, and Constants
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Program Design and Development
Chapter 2 Basic Elements of Fortan
Introduction to C Programming
Adding Automated Functionality to Office Applications.
Basic Elements of C++ Chapter 2.
Chapter 18: Modifying SAS Data Sets and Tracking Changes 1 STAT 541 ©Spring 2012 Imelda Go, John Grego, Jennifer Lasecki and the University of South Carolina.
“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.
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.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
©Spring 2012 Imelda Go, John Grego, Jennifer Lasecki and the University of South Carolina Chapter 17 supplement: Review of Formatting Data STAT 541.
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.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
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.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CPS120: Introduction to Computer Science Decision Making in Programs.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Introduction to SAS Macros Center for Statistical Consulting Short Course April 15, 2004.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
BMTRY 789 Lecture 10: SAS MACRO Facility Annie N. Simpson, MSc.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
JavaScript, Fourth Edition
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
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.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Controlling Program Flow with Decision Structures.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Chapter 14: Combining Data Vertically 1 STAT 541 ©Spring 2012 Imelda Go, John Grego, Jennifer Lasecki and the University of South Carolina.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
SAS ® 101 Based on Learning SAS by Example: A Programmer’s Guide Chapter 25 By Tasha Chapman, Oregon Health Authority.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 4 – C Program Control
The Selection Structure
Two “identical” programs
Microsoft Access Illustrated
Chapter 18: Modifying SAS Data Sets and Tracking Changes
Conditional Processing
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 ©
Topics Introduction to File Input and Output
3 Macro Parameters.
Creating Macro Variables in the DATA Step
Macro Variable’s scope
PHP.
Defining and Calling a Macro
Global and Local Symbol Tables
3 Iterative Processing.
Fundamentals of visual basic
Chapter 4 - Program Control
Topics Introduction to File Input and Output
Controlling Program Flow
Presentation transcript:

Chapter 11: Creating and Using Macro Programs 1 STAT 541 ©Spring 2012 Imelda Go, John Grego, Jennifer Lasecki and the University of South Carolina

2 Definition MACRO (noun) Etymology: short for macroinstruction Date: 1959 : a single computer instruction that stands for a sequence of operations Retrieved from

3 Macro Programs (a.k.a. Macros) Macros enable text substitution into programs. Macros enable text substitution into programs. Unlike macro variables, macros can use conditional logic. Unlike macro variables, macros can use conditional logic. Programs can become more dynamic and reusable, shorter, and easier to follow. Programs can become more dynamic and reusable, shorter, and easier to follow. It is useful for automation. Repetitive tasks can be performed quickly and efficiently. Macros can generalize the same or similar code. Parameters can be passed to the macro so that the macro itself does not have to be changed prior to execution. It is useful for automation. Repetitive tasks can be performed quickly and efficiently. Macros can generalize the same or similar code. Parameters can be passed to the macro so that the macro itself does not have to be changed prior to execution. It can help towards modular programming. Referencing a macro is similar to calling a subroutine. The main program can become more readable. It can help towards modular programming. Referencing a macro is similar to calling a subroutine. The main program can become more readable.

4 What is the SAS Macro Facility? It is a tool for text substitution that is meant to assist you in constructing your programs. The facility is part of base SAS. It has its own language that is different from that used in base SAS, but the two languages have similar conventions and syntax. It is a tool for text substitution that is meant to assist you in constructing your programs. The facility is part of base SAS. It has its own language that is different from that used in base SAS, but the two languages have similar conventions and syntax.

5 What are the potential disadvantages of using the SAS Macro Facility? Used a certain way, macros can make your programs harder to read. Used a certain way, macros can make your programs harder to read. Sharing macro programs with users who do not use macros has its challenges. Sharing macro programs with users who do not use macros has its challenges.

6 What are the SAS Macro Facility’s two components? The macro processor compiles macros and integrates it with the SAS job. The macro processor compiles macros and integrates it with the SAS job. The macro language is the interface between the programmer and the processor. The macro language is the interface between the programmer and the processor. The macro language statements instruct the macro processor how to substitute text for you or how the facility should create the statements for you. After writing a macro, the macro is executed by invoking it instead of manually modifying the statements in a non-macro program prior to execution. The macro language statements instruct the macro processor how to substitute text for you or how the facility should create the statements for you. After writing a macro, the macro is executed by invoking it instead of manually modifying the statements in a non-macro program prior to execution.

7 How is the macro processor triggered in a SAS program? &varname &varname This is a reference to the macro variable named varname. The current value of the macro variable will replace all references of &varname in the program. %macroname %macroname This is a reference to the macro named macroname. This generates statements (with or without errors) that are contained in the macro. The contents of the macro are still subject to debugging by the user.

8 How do I use SAS macros? The first step is to create macro statements/code. The first step is to create macro statements/code. The second step is to invoke the macro statements/code. The second step is to invoke the macro statements/code.

9 Defining a Macro The definition begins with %MACRO and ends with %MEND. The definition begins with %MACRO and ends with %MEND. Example: Example: %macro printsubset(gender,titletext); proc print; where female="&gender"; title "&titletext"; run; %mend printsubset;

10 General Syntax %MACRO macro-name; text %MEND ; macro nameis any valid SAS name but not a reserved word in the SAS macro facility macro nameis any valid SAS name but not a reserved word in the SAS macro facility textis: textis: –constant text, possibly including SAS data set names, SAS variable names, or SAS statements –macro variables, macro functions, or macro program statements –any combination of the above

11 Compiling a Macro After submitting the macro definition, the macro scanner goes through it and sends it to the macro processor. After submitting the macro definition, the macro scanner goes through it and sends it to the macro processor. The macro processor: Checks for macro language syntax errors (non-macro language statements are NOT checked until AFTER the macro is executed) Checks for macro language syntax errors (non-macro language statements are NOT checked until AFTER the macro is executed) Writes error messages to the SAS log and creates a dummy (non-executable) macro if there are errors Writes error messages to the SAS log and creates a dummy (non-executable) macro if there are errors Stores the macro for later use if there are no errors. Stores all compiled macro language statements and constant text in a SAS catalog (default is Work.Sasmacr catalog) under an entry called macro-name.Macro. Stores the macro for later use if there are no errors. Stores all compiled macro language statements and constant text in a SAS catalog (default is Work.Sasmacr catalog) under an entry called macro-name.Macro.

12 The MCOMPILENOTE Option This option will write a note in the SAS log when a macro has completed compilation. OPTIONS MCOMPILENOTE= NONE | NOAUTOCALL | ALL; Default NONE (no notes written to the log) Default NONE (no notes written to the log) NOAUTOCALL (notes to log about completed macro compilation except for AUTOCALL macros) NOAUTOCALL (notes to log about completed macro compilation except for AUTOCALL macros) ALL (notes to log about all completed macro compilation) ALL (notes to log about all completed macro compilation)

13 Calling a Macro After compilation, the macro can be called for the duration of the SAS session without resubmitting it. After compilation, the macro can be called for the duration of the SAS session without resubmitting it. Macro calls: are specified by placing a percent sign (%) before the name of the macro are specified by placing a percent sign (%) before the name of the macro can be made anywhere in a program except within the data lines of a DATALINES statement can be made anywhere in a program except within the data lines of a DATALINES statement do not require semicolons (Macro calls are not SAS statements) do not require semicolons (Macro calls are not SAS statements) Example: %printsubset calls the macro named printsubset

14 Macro Execution Word scanner passes macro call to macro processor, which searches the SAS catalog (usually WORK.Sasmacr) for the macro. Word scanner passes macro call to macro processor, which searches the SAS catalog (usually WORK.Sasmacr) for the macro. Compiled macro language statements are executed Compiled macro language statements are executed Non-macro text is scanned Non-macro text is scanned Macro execution is halted at end of SAS step, and SAS code is executed Macro execution is halted at end of SAS step, and SAS code is executed Macro execution is resumed Macro execution is resumed

15 Developing and Debugging Macros A number of SAS system options are available. A number of SAS system options are available. –MPRINT Option –MLOGIC Option Comments can be added to the program Comments can be added to the program

16 The MPRINT Option This option shows in the SAS log the code that results from the macro. OPTIONS MPRINT | NOMPRINT; MPRINT (displays statements generated by macro execution-- statements are useful for debugging macros) MPRINT (displays statements generated by macro execution-- statements are useful for debugging macros) default NOMPRINT (does not display statements generated by macro execution) default NOMPRINT (does not display statements generated by macro execution)

17 The MLOGIC Option This option prints messages that indicate macro actions that were taken during macro execution. OPTIONS MLOGIC | NOMLOGIC; MLOGIC (messages about macro actions are printed in the log during macro execution) debugging MLOGIC (messages about macro actions are printed in the log during macro execution) debugging default NOMLOGIC (messages about macro actions are not printed in the log) default NOMLOGIC (messages about macro actions are not printed in the log)

18 The Macro Comment Statement Macro comments are not part of the code that results after the macro is compiled. Regular SAS comments are. %*comment; comment is any message comment is any message The statement ends with a semi-colon. The statement ends with a semi-colon.

19 Using Macro Parameters A parameter list is an optional part of the %MACRO statement that names one or more macro variables whose values are specified upon calling the macro. Example:The %macro printsubset(gender,titletext); proc print; where gender="&gender"; title "&titletext"; %mend printsubset; The macro prints the variables for records with the specified gender and titletext macro variable values.

20 General Syntax for %MACRO Statement %MACRO macro-name >; macro-name names the macro (a SAS name that is not a reserved word in the macro facility) macro-name names the macro (a SAS name that is not a reserved word in the macro facility) parameter-list names one or more local macro variables whose values are specified when the macro is invoked (Macro parameters are separated by commas and can be referenced in the macro.) parameter-list names one or more local macro variables whose values are specified when the macro is invoked (Macro parameters are separated by commas and can be referenced in the macro.)

21 Syntax for Macros with Positional Parameters %MACRO macro-name (positional-parameter-1 ) text %MEND macro-name; Parameters can be in any order. Parameters can be in any order. Macro invocation must have them in the same order as they appear in the %MACRO statement. Macro invocation must have them in the same order as they appear in the %MACRO statement. Separate more than one parameter with commas. Separate more than one parameter with commas. If an invocation does not supply a value for a positional parameter, a null value is assigned to that parameter. If an invocation does not supply a value for a positional parameter, a null value is assigned to that parameter.

22 Syntax for Macros with Keyword Parameters %MACRO macro-name (keyword-parameter= >) text %MEND macro-name; Keyword parameters name one or more macro parameters followed by equal signs. Default values can follow the equal signs. An omitted default value is the null value. Keyword parameters name one or more macro parameters followed by equal signs. Default values can follow the equal signs. An omitted default value is the null value. Override a default value by specifying the macro variable name followed by the equal sign and new value in the invocation. Override a default value by specifying the macro variable name followed by the equal sign and new value in the invocation.

23 Syntax for Macros That Include Mixed Parameter Lists %MACRO macro-name (positional-parameter-1, keyword-parameter= >) text %MEND macro-name; Parameter lists can consist of both positional and keyword parameter lists. Parameter lists can consist of both positional and keyword parameter lists. Positional parameters must be listed first before any keyword parameters. Positional parameters must be listed first before any keyword parameters.

24 Syntax for Macros That Include the PARMBUFF Option %MACRO macro-name /PARMBUFF; text %MEND macro-name; PARMBUFF option creates an automatic macro variable SYSPBUFF to define a macro that accepts a varying number of parameters each time you call it. PARMBUFF option creates an automatic macro variable SYSPBUFF to define a macro that accepts a varying number of parameters each time you call it. SYSPBUFF has the value of the list of parameters separated by commas and all enclosed in parentheses. SYSPBUFF has the value of the list of parameters separated by commas and all enclosed in parentheses. text contains a reference to the automatic macro variable SYSPBUFF text contains a reference to the automatic macro variable SYSPBUFF

25 The Global Symbol Table The table is created during the initialization of a SAS session and is deleted at the end of the session. The table contains global macro variables that: The table is created during the initialization of a SAS session and is deleted at the end of the session. The table contains global macro variables that: –are available any time during the session –can be created by a user –have values that can be changed during the session (except for some automatic variables) Create a global macro variable with: Create a global macro variable with: –a %LET statement (used outside a macro definition) –a DATA step that contains a SYMPUT routine –a DATA step that contains a SYMPUTX routine –a SELECT statement that contains an INTO clause in PROC SQL –A %GLOBAL statement

26 The %GLOBAL Statement The %GLOBAL statement: Creates one or more macro variables in the global symbol table and assigns null values to them Creates one or more macro variables in the global symbol table and assigns null values to them Can be used either inside or outside a macro definition Can be used either inside or outside a macro definition Has no effect on variables that are already in the global symbol table Has no effect on variables that are already in the global symbol table %GLOBAL macro-variable-1 ; macro-variable-1 is the name of one or more macro variables or a text expression that generates one or more macro variable names macro-variable-1 is the name of one or more macro variables or a text expression that generates one or more macro variable names

27 The Local Symbol Table When a macro variable is in a local symbol table, it is available only during execution of the macro in which it is defined. When a macro variable is in a local symbol table, it is available only during execution of the macro in which it is defined. The local symbol table contains macro variables that can be: The local symbol table contains macro variables that can be: –created and initialized at macro parameter invocation –created or updated during macro execution –referenced anywhere within the macro Create a local macro variable within a macro definition: Create a local macro variable within a macro definition: –parameters in a macro definition –a %LET statement within a macro definition –a DATA step that contains a SYMPUT routine within a macro definition –a DATA step that contains a SYMPUTX routine within a macro definition –a SELECT statement that contains an INTO clause in PROC SQL within a macro definition –A %LOCAL statement

28 The %LOCAL Statement The %LOCAL statement: Can appear only inside a macro definition Can appear only inside a macro definition Creates one or more macro variables in the local symbol table and assigns null values to them Creates one or more macro variables in the local symbol table and assigns null values to them Has no effect on variables that are already in the local symbol table Has no effect on variables that are already in the local symbol table %LOCAL macro-variable-1 ; macro-variable-1 is the name of one or more macro variables or a text expression that generates one or more macro variable names macro-variable-1 is the name of one or more macro variables or a text expression that generates one or more macro variable names

29 Multiple Local Symbol Tables Multiple local symbol tables can exist concurrently during macro execution if there are nested macros. If a macro program calls another macro program, and if both macros create local symbol tables, then two local symbol tables will exist while the second macro executes. Multiple local symbol tables can exist concurrently during macro execution if there are nested macros. If a macro program calls another macro program, and if both macros create local symbol tables, then two local symbol tables will exist while the second macro executes.

30 The MPRINTNEST Option This option allows the macro nesting information to be written to the SAS log in the MPRINT output. This has no effect on the MPRINT output that is sent to an external file. MPRINT and MPRINTNEST must both be set in order for the output to be written to the log. OPTIONS MPRINTNEST | NOMPRINTNEST; MPRINTNEST specifies that macro nesting information is written in the MPRINT output in the log MPRINTNEST specifies that macro nesting information is written in the MPRINT output in the log NOMPRINTNEST specifies that macro nesting information is not written in the MPRINT output in the log NOMPRINTNEST specifies that macro nesting information is not written in the MPRINT output in the log

31 The MLOGICNEST Option This option allows the macro nesting information to be displayed in the MLOGIC output in the SAS log. The setting does not affect the output of any currently executing macro. OPTIONS MLOGICNEST | NOMLOGICNEST; MLOGICNEST specifies that macro nesting information is written in the MLOGIC output in the log MLOGICNEST specifies that macro nesting information is written in the MLOGIC output in the log NOMLOGICNEST specifies that macro nesting information is not written in the MLOGIC output in the log NOMLOGICNEST specifies that macro nesting information is not written in the MLOGIC output in the log

32 Processing Statements Conditionally %IF-%THEN/%ELSE Statement %IF expression %THEN action; expressionis any macro expression (constant text, a text expression, a macro variable reference, a macro call, or a macro program statement) that resolves to an integer. expressionis any macro expression (constant text, a text expression, a macro variable reference, a macro call, or a macro program statement) that resolves to an integer. Comparisons are case-sensitive. Comparisons are case-sensitive. If the expression resolves to an integer other than zero, the expression is true and the %THEN clause is processed. If the expression resolves to an integer other than zero, the expression is true and the %THEN clause is processed. If the expression resolves to zero, then the expression is false and the %ELSE statement, if any, is processed. If the expression resolves to zero, then the expression is false and the %ELSE statement, if any, is processed. If the expression resolves to a null value or a value with nonnumeric characters, the macro processor issues an error message. If the expression resolves to a null value or a value with nonnumeric characters, the macro processor issues an error message. %IF comparisons are case-sensitive. %IF comparisons are case-sensitive.

33 Processing Statements Conditionally Use %DO-%END with %IF-%THEN and %ELSE statements in order to conditionally place text that contains multiple statements onto the input stack. Use %DO-%END with %IF-%THEN and %ELSE statements in order to conditionally place text that contains multiple statements onto the input stack. %IF expression %THEN %DO; text and/or macro language statements %END; %ELSE %DO; text and/or macro language statements %END; text and/or macro language statements is either constant text, a text expression, and/or a macro statement. text and/or macro language statements is either constant text, a text expression, and/or a macro statement.

34 Processing Statements Iteratively %DO macro-variable=start %TO stop ; text and macro language statements %END; macro-variable is a macro variable or a text expression that generates a macro variable name (functions as index that determines number of loop iterations)—If macro variable does not exist, it is created in the local symbol table. macro-variable is a macro variable or a text expression that generates a macro variable name (functions as index that determines number of loop iterations)—If macro variable does not exist, it is created in the local symbol table. start and stop are integers or macro expressions that generate integers to help control the total number of iterations start and stop are integers or macro expressions that generate integers to help control the total number of iterations increment is a positive integer (default is 1) that is added to the index variable in each loop iteration (Increment is evaluated before the first iteration of the loop and can’t be changed as the loop iterates.) increment is a positive integer (default is 1) that is added to the index variable in each loop iteration (Increment is evaluated before the first iteration of the loop and can’t be changed as the loop iterates.) The index variable is evaluated at the beginning of each loop. The loop ends when the index variable first exceeds the stop value. The index variable is evaluated at the beginning of each loop. The loop ends when the index variable first exceeds the stop value.

35 Using Arithmetic and Logical Expressions the %EVAL Function The %EVAL function evaluates arithmetic and logical expressions using integer arithmetic. The %EVAL function evaluates arithmetic and logical expressions using integer arithmetic. %EVAL (arithmetic or logical expression) Caution: Error messages are generated in the log when the expression contains non-integer values. The function does not convert a value that contains a period to a number. Caution: Error messages are generated in the log when the expression contains non-integer values. The function does not convert a value that contains a period to a number.

36 Using Arithmetic and Logical Expressions the %SYSEVALF Function The %SYSEVALF function evaluates arithmetic and logical expressions using floating-point arithmetic. The %SYSEVALF function evaluates arithmetic and logical expressions using floating-point arithmetic. %SYSEVALF (expression, ); The second parameter conversion-type is optional and can be BOOLEAN, CEIL, FLOOR, or INTEGER. The second parameter conversion-type is optional and can be BOOLEAN, CEIL, FLOOR, or INTEGER. This is the only macro function that can evaluate expressions with floating point or missing values. This is the only macro function that can evaluate expressions with floating point or missing values.