SAS Macro Programming for Beginners
|
|
|
- Bruce Shepherd
- 9 years ago
- Views:
Transcription
1 Paper SAS Macro Programming for Beginners Susan J. Slaughter, Avocet Solutions, Davis, CA Lora D. Delwiche, Delwiche Consulting, Winters, CA ABSTRACT Macro programming is generally considered an advanced topic. But, while macros certainly can be challenging, it is also true that the basic concepts are not difficult to learn. This paper is designed for people who know the basics of SAS programming, but know nothing about SAS macro programming. We explain how the macro processor works, and how to use macros and macro variables. Using these techniques you can create flexible, reusable code that can save you time and effort. WHY USE MACROS? Because macro code takes longer to write and debug than standard SAS code, you generally won t use macros in programs that will be run only a few times. But if you find yourself writing similar code over and over again, then macros may make your job easier. Macros can help in several ways. 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. Third, you can make your programs data driven, letting SAS decide what to do based on actual data values. THE MACRO PROCESSOR The most important concept to keep in mind whenever you write macro code is that You are writing a program that writes a program. Here is how it works. macro statements macro processor standard SAS statements When you submit a standard SAS program, SAS compiles and then immediately executes it. But when you write macro code, there is an extra step. Before SAS can compile and execute your program, SAS must pass your macro statements to the macro processor which then resolves your macros generating standard SAS code. Because you are writing a program that writes a program, this is sometimes called meta-programming. MACROS VS. MACRO VARIABLES As you construct macro programs, you will use two basic building blocks: macros and macro variables. You can tell them apart because the names of macro variables start with an ampersand (&), while the names of macros start with a percent sign (%). 1 A macro variable is like a standard data variable except that it does not belong to a data set and has only a single value which is always character. The value of a macro variable could be a variable name, a numeral, or any text you want substituted in your program. A macro, however, is a larger piece of a program that can contain complex logic including complete DATA and PROC steps, and macro statements such as %IF-%THEN/%ELSE and %DO-%END. Macros often but not always contain macro variables. 1
2 THINK GLOBALLY AND LOCALLY Macro variables come in two varieties: either local or global. A macro variable s scope is local if it is defined inside a macro. Its scope is global if it is defined in open code which is everything outside a macro. You can use a global macro variable anywhere in your program, but you can use a local macro variable only inside its own macro. If you keep this in mind as you write your programs, you will avoid two common mistakes: trying to use a local macro variable outside its own macro, and accidentally creating local and global macro variables having the same name. YOU MAY QUOTE ME ON THAT Another caveat to keep in mind is that the macro processor doesn t check for macros inside single quotes. To get around this, simply use double quotes for titles or other quoted strings that contain macro code. SUBSTITUTING TEXT WITH %LET %LET is a straightforward macro statement that simply assigns a value to a macro variable. Despite its simplicity, by learning this one statement you will greatly increase the flexibility of your programs. Suppose you have a program that you run once a month. Every time you have to edit the program so it will select data for the correct month and print the correct title. This is time-consuming and prone to errors. You can use %LET to create a macro variable. Then you can change the value of the macro variable in the %LET statement, and SAS will repeat the new value throughout your program. The general form a %LET statement is %LET macro-variable-name = value; where macro-variable-name is a name you make up following the standard rules for SAS names (32 characters or fewer in length; starting with a letter or underscore; and containing only letters, numerals, or underscores). Value is the text to be substituted for the macro variable name, and can be up to 64,000 characters long. The following statements each create a macro variable. %LET iterations = 5; %LET winner = Lance Armstrong; Notice that there are no quotation marks around value even when it contains characters. Blanks at the beginning and end will be trimmed, and everything else between the equal sign and semicolon will become part of the value for the macro variable. To use the macro variable, you simply add the ampersand prefix (&) and stick the macro variable name wherever you want its value to be substituted. DO i = 1 to &iterations; TITLE First: &winner ; After being resolved by the macro processor, these statements would become DO i = 1 to 5; TITLE First: Lance Armstrong ; Example A company that manufactures bicycles maintains a file listing all their models. For each model they record its name, class (Road, Track, or Mountain), list price, and frame material. Here is a subset of the data: Black Bora Track 796 Aluminum Delta Breeze Road 399 CroMoly Jet Stream Track 1130 CroMoly Mistral Road 1995 Carbon Comp Nor'easter Mountain 899 Aluminum Santa Ana Mountain 459 Aluminum Scirocco Mountain 2256 Titanium Trade Wind Road 759 Aluminum 2
3 This DATA step reads the raw data from a file named Models.dat creating a SAS data set named MODELS. DATA models; INFILE 'c:\myrawdata\models.dat' TRUNCOVER; INPUT Model $ 1-12 Class $ Price Frame $ 28-38; Frequently the sales people want a list showing all the models of one particular class. Sometimes they want a list of road bikes, but other times they want mountain or track bikes. You could write three different programs one for each type or you could write one program with a macro variable. This program uses a %LET statement to create a macro variable named &BIKECLASS. To run the program, you type in the class of bike you want at the beginning of the program, and then SAS echoes that value throughout the program. %LET bikeclass = Mountain; * Use a macro variable to subset; WHERE Class = "&bikeclass"; TITLE "Current Models of &bikeclass Bicycles"; Note that the macro variable &BIKECLASS will be global because it is created outside of a macro in open code. When you submit the program with a value of Mountain, then the macro processor will resolve the macro variable and create this standard SAS code. * Use a macro variable to subset; WHERE Type = "Mountain"; TITLE "Current Models of Mountain Bicycles"; Here are the results: Current Models of Mountain Bicycles Model Class Price Frame Nor'easter Mountain $899 Aluminum Santa Ana Mountain $459 Aluminum Scirocco Mountain $2,256 Titanium This was a short program, with only two occurrences of the macro variable. But imagine if you had a long program with dozens of occurrences of the macro variable sprinkled throughout. You could save a lot of time and trouble by changing the macro variable only once at the beginning. CREATING MODULAR CODE WITH MACROS Anytime you find yourself repeating the same program statements over and over, you might want to consider creating a macro instead. Macros are simply a group of SAS statements that have a name. And, anytime you want that group of statements in your program, you use the name instead of the re-typing all the statements. The general form of a macro is %MACRO macro-name; macro-text %MEND macro-name; 3
4 The %MACRO statement tells SAS that this is the beginning of the macro and the %MEND statement signals the end of the macro. Macro-name is a name you make up for your macro. The name must follow standard SAS naming conventions (start with a letter or underscore; contain only letters, numerals or underscores; and can be up to 32 characters in length). You don t need to specify the macro-name in the %MEND statement, but it will make your programs easier to understand if you include it. Macro-text represents the SAS statements that you want in your macro. After you define your macro, you need to invoke it when you want to use it. Do this by adding a percent sign in front of the macro-name like this: %macro-name While you do not need to end this statement with a semicolon, it generally does no harm either. Example Looking again at the bicycle models data, the sales personnel like to have lists of models sorted both by model name and by price. The following program creates a macro named PRINTIT that has the PROC PRINT statements you need for the report. Then the program calls the macro twice; first without sorting the data (it is already sorted by model name), and then after executing a PROC SORT by Price. %MACRO printit; TITLE 'Current Models'; VAR Model Class Frame Price; %MEND printit; %printit PROC SORT DATA = models; BY Price; %printit Here are the standard SAS statements that are generated by the macro processor. The first PROC PRINT is generated by the first call to the PRINTIT macro, the PROC SORT comes from the original program and the second PROC PRINT is generated by the second call to the PRINTIT macro. TITLE 'Current Models'; VAR Model Class Frame Price; PROC SORT DATA = models; BY Price; TITLE 'Current Models'; VAR Model Class Frame Price; 4
5 And here are the results of the two PROC PRINTs: one before sorting and one after sorting by Price. Current Models Model Class Frame Price Black Bora Track Aluminum $796 Delta Breeze Road CroMoly $399 Jet Stream Track CroMoly $1,130 Mistral Road Carbon Comp $1,995 Nor'easter Mountain Aluminum $899 Santa Ana Mountain Aluminum $459 Scirocco Mountain Titanium $2,256 Trade Wind Road Aluminum $759 Current Models Model Class Frame Price Delta Breeze Road CroMoly $399 Santa Ana Mountain Aluminum $459 Trade Wind Road Aluminum $759 Black Bora Track Aluminum $796 Nor'easter Mountain Aluminum $899 Jet Stream Track CroMoly $1,130 Mistral Road Carbon Comp $1,995 Scirocco Mountain Titanium $2,256 This program is fairly simple with only two calls to the macro, so you didn t save much by putting the PROC PRINT statements in a macro. But if you had many calls to the macro, you could simplify your program a great deal by using a macro. And, if you need to make a change to any of the PROC PRINT statements, if they are in a macro, then you would only need to make one change instead of trying to find every occurrence of the PROC PRINT and risk making mistakes. ADDING PARAMETERS TO MACROS Macros allow you to execute a set of SAS statements with just one statement, and while this alone can be helpful, macros are even more powerful when you add parameters to them. Parameters are macro variables whose values are set when you invoke the macro. Parameters give your macros flexibility. To add parameters to your macro, simply list the macro-variable names followed by an equal sign in parentheses after the macro name: %MACRO macro-name (parameter-1=, parameter-2=,... parameter-n=); macro-text %MEND macro-name; For example, if you have a macro named %MONTHLYREPORT that has parameters for the month and region, it might start like this: %MACRO monthlyreport (month=, region=); Then when you invoke the macro, specify the values for the macro variables after the equal signs: %monthlyreport (month=may, region=west) Because these macro variables are defined in the macro, they are, by default, local to the macro and you cannot use them in any SAS statements outside the macro. 5
6 Example The PRINTIT macro from the previous example prints the desired reports, but you have to sort the data between calls to the macro and the title does not reflect the sort order of the report. This new macro, SORTANDPRINT includes the PROC SORT statements and adds parameters so that you can vary both the sort variable and the sort sequence (descending or not). Then the macro variables are added to a TITLE statement, so the report states how it is sorted. There are two calls to the macro, producing two reports. * For sortvar enter the variable for sorting the report. For sortseq use either Descending or do not enter a value for an ascending sequence; %MACRO sortandprint(sortseq=, sortvar=); PROC SORT DATA = models; BY &sortseq &sortvar; TITLE 'Current Models'; TITLE2 "Sorted by &sortseq &sortvar"; VAR Model Class Frame Price; %MEND sortandprint; %sortandprint(sortseq=descending, sortvar=price) %sortandprint(sortseq=, sortvar=class) The first call to the macro gives the &SORTSEQ macro variable the value DESCENDING and the &SORTVAR macro variable the value Price. So the statements generated by this call will sort the data by descending values of the variable Price. The second call to the macro gives &SORTSEQ no value and &SORTVAR the value Class. So this call will produce statements that sort the data by ascending (the default) Class. Here are the SAS statements that are generated by the macro processor: PROC SORT DATA = models; BY Descending Price; TITLE 'Current Models'; TITLE2 "Sorted by Descending Price"; VAR Model Class Frame Price; PROC SORT DATA = models; BY Class; TITLE 'Current Models'; TITLE2 "Sorted by Class"; VAR Model Class Frame Price; 6
7 Here are the results of the two PROC PRINTs, one sorted by descending Price, the other by Class. Current Models Sorted by Descending Price Model Class Frame Price Scirocco Mountain Titanium $2,256 Mistral Road Carbon Comp $1,995 Jet Stream Track CroMoly $1,130 Nor'easter Mountain Aluminum $899 Black Bora Track Aluminum $796 Trade Wind Road Aluminum $759 Santa Ana Mountain Aluminum $459 Delta Breeze Road CroMoly $399 Current Models Sorted by Class Model Class Frame Price Scirocco Mountain Titanium $2,256 Nor'easter Mountain Aluminum $899 Santa Ana Mountain Aluminum $459 Mistral Road Carbon Comp $1,995 Trade Wind Road Aluminum $759 Delta Breeze Road CroMoly $399 Jet Stream Track CroMoly $1,130 Black Bora Track Aluminum $796 MPRINT system option We have been showing you what SAS sees after the macro processor has resolved your program, but normally you won t see these statements. However if you specify the MPRINT sys tem option in your program, then SAS will print the resolved statements from macros in the SAS log. This can be very useful for debugging purposes. To turn on the MPRINT option, submit an OPTIONS statement like this: OPTIONS MPRINT; Here is what the SAS log looks like with the MPRINT option turned on: 6 %MACRO sortandprint(sortseq=, sortvar=); 7 PROC SORT DATA=models; 8 BY &sortseq &sortvar; 9 PROC PRINT DATA=models NOOBS; 10 TITLE 'Current Models'; 11 TITLE2 "Sorted by &sortseq &sortvar"; 12 VAR Model Class Frame Price; %MEND sortandprint; 16 %sortandprint(sortseq=descending, sortvar=price); MPRINT(SORTANDPRINT): PROC SORT DATA=models; MPRINT(SORTANDPRINT): BY Descending Price; NOTE: There were 8 observations read from the data set WORK.MODELS. 7
8 NOTE: The data set WORK.MODELS has 8 observations and 4 variables. NOTE: PROCEDURE SORT used (Total process time): real time 0.55 seconds cpu time 0.05 seconds MPRINT(SORTANDPRINT): PROC PRINT DATA=models NOOBS; MPRINT(SORTANDPRINT): TITLE 'Current Models'; MPRINT(SORTANDPRINT): TITLE2 "Sorted by Descending Price"; MPRINT(SORTANDPRINT): VAR Model Class Frame Price; MPRINT(SORTANDPRINT): MPRINT(SORTANDPRINT): NOTE: There were 8 observations read from the data set WORK.MODELS. NOTE: PROCEDURE PRINT used (Total process time): real time 0.81 seconds cpu time 0.07 seconds 17 %sortandprint(sortseq=, sortvar=class); MPRINT(SORTANDPRINT): PROC SORT DATA=models; MPRINT(SORTANDPRINT): BY Class; NOTE: There were 8 observations read from the data set WORK.MODELS. NOTE: The data set WORK.MODELS has 8 observations and 4 variables. NOTE: PROCEDURE SORT used (Total process time): real time 0.04 seconds cpu time 0.03 seconds MPRINT(SORTANDPRINT): PROC PRINT DATA=models NOOBS; MPRINT(SORTANDPRINT): TITLE 'Current Models'; MPRINT(SORTANDPRINT): TITLE2 "Sorted by Class"; MPRINT(SORTANDPRINT): VAR Model Class Frame Price; MPRINT(SORTANDPRINT): MPRINT(SORTANDPRINT): NOTE: There were 8 observations read from the data set WORK.MODELS. NOTE: PROCEDURE PRINT used (Total process time): real time 0.09 seconds cpu time 0.00 seconds 18 You can see that SAS has inserted into the regular SAS log the MPRINT lines. The statements generated by the macro processor are all labeled with the word MPRINT followed by the name of the macro that generated the statements in this case SORTANDPRINT. By using the MPRINT system option it is easy to see the standard SAS statements your macro is generating. CONDITIONAL LOGIC With macros and macro variables, you have a lot of flexibility. You can increase that flexibility still more by using conditional macro statements such as %IF. Here are the general forms of statements used for conditional logic in macros: 8
9 %IF condition %THEN action; %ELSE %IF condition %THEN action; %ELSE action; %IF condition %THEN %DO; action; %END; These statements probably look familiar because there are parallel statements in standard SAS code, but don t confuse these with their standard counterparts. These statements can only be used inside a macro, and can perform actions that would be completely impossible for standard SAS statements. With %IF, actions can include other macro statements or even complete DATA and PROC steps. Remember, the macro statements won t appear in the standard SAS code generated by the macro processor because you are writing a program that writes a program. Automatic macro variables Every time you invoke SAS, the macro processor automatically creates certain macro variables. You can use these in your programs. Two of the most commonly used automatic variables are Variable Name Example Description &SYSDATE 31OCT03 Character value of the date that job or session began &SYSDAY Friday Day of the week that job or session began Example The company maintains a file with information about every order they receive. For each order, the data include the customer ID number, date the order was placed, model name, and quantity ordered. Here are the data: OCT03 Delta Breeze OCT03 Santa Ana OCT03 Jet Stream OCT03 Santa Ana OCT03 Nor'easter OCT03 Scirocco OCT03 Mistral OCT03 Delta Breeze OCT03 Santa Ana 25 This DATA step reads the raw data from a file named Orders.dat creating a SAS data set named ORDERS. DATA orders; INFILE 'c:\myrawdata\orders.dat'; INPUT CustomerID $ 1-3 OrderDate DATE7. Model $ Quantity; Every Monday the president of the company wants a detail-level report showing all the current orders. On Friday the president wants a report summarized by customer. You could write two separate programs to run these reports, or you could write one program using macros. Combining conditional logic with the automatic variable &SYSDAY, the following program creates a macro named REPORTS that prints a detail report if you run it on Monday, and a summary report if you run it on Friday (and no report on other days). 9
10 %MACRO reports; %IF &SYSDAY = Monday %THEN %DO; PROC PRINT DATA = orders NOOBS; FORMAT OrderDate DATE7.; TITLE "&SYSDAY Report: Current Orders"; %END; %ELSE %IF &SYSDAY = Friday %THEN %DO; PROC TABULATE DATA = orders; CLASS CustomerID; VAR Quantity; TABLE CustomerID ALL, Quantity; TITLE "&SYSDAY Report: Summary of Orders"; %END; %MEND reports; %reports If you run this program on Monday, the macro processor with generate the following standard SAS code. PROC PRINT DATA = orders NOOBS; FORMAT OrderDate DATE7.; TITLE "Monday Report: Current Orders"; And the output will look like this: Monday Report: Current Orders Customer Order ID Date Model Quantity OCT03 Delta Breeze OCT03 Santa Ana OCT03 Jet Stream OCT03 Santa Ana OCT03 Nor'easter OCT03 Scirocco OCT03 Mistral OCT03 Delta Breeze OCT03 Santa Ana 25 If you run this program on Friday, the macro processor with generate the following standard SAS code. PROC TABULATE DATA = orders; CLASS CustomerID; VAR Quantity; TABLE CustomerID ALL, Quantity; TITLE "Friday Report: Summary of Orders"; 10
11 And the output will look like this: Friday Report: Summary of Orders ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ ƒƒƒƒƒƒƒƒƒƒƒƒ Quantity ƒƒƒƒƒƒƒƒƒƒƒƒ Sum ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒˆƒƒƒƒƒƒƒƒƒƒƒƒ CustomerID ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒˆƒƒƒƒƒƒƒƒƒƒƒƒ ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒˆƒƒƒƒƒƒƒƒƒƒƒƒ ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒˆƒƒƒƒƒƒƒƒƒƒƒƒ ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒˆƒƒƒƒƒƒƒƒƒƒƒƒ All Šƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ ƒƒƒƒƒƒƒƒƒƒƒƒœ DATA-DRIVEN PROGRAMS This is where your macro programs begin to take on a life of their own. Using the CALL SYMPUT macro routine you can let a macro program look at the data and then decide for itself what to do. CALL SYMPUT takes a value from a DATA step and assigns it to a macro variable which you can then use later in your program. CALL SYMPUT can take many forms, but to assign a single value to a single macro variable, use CALL SYMPUT with this general form: CALL SYMPUT( macro-variable, value); where macro-variable is the name of a macro variable, either new or old, and is enclosed in quotes. Value is the name of a variable from a DATA step whose current value you want to assign to that macro variable. CALL SYMPUT is often used in IF-THEN statements, for example IF Place = 1 THEN CALL SYMPUT( WinningTime, Time); This statement tells SAS to create a macro variable named &WINNINGTIME and set it equal to the current value of the variable TIME when the value of Place is 1. Be careful. You cannot create a macro variable with CALL SYMPUT and use it in the same DATA step. Here s why. When you submit macro code, it is resolved by the macro processor, and then compiled and executed. Not until the final stage execution does SAS see your data. CALL SYMPUT takes a data value from the execution phase, and passes it back to the macro processor for use in a later step. That s why you must put CALL SYMPUT in one DATA step, but not use it until a later step. Example The marketing department wants a report showing all the orders placed by their best customer. The following program finds the customer with the single largest order and then prints all the orders for that customer. 11
12 *Sort by Quantity; PROC SORT DATA = orders; BY DESCENDING Quantity; *Use CALL SYMPUT to find biggest order; DATA _NULL_; SET orders; IF _N_ = 1 THEN CALL SYMPUT("biggest", CustomerID); ELSE STOP; *Print all obs for customer with biggest order; PROC PRINT DATA = orders NOOBS; WHERE CustomerID = "&biggest"; FORMAT OrderDate DATE7.; TITLE "Customer &biggest Had the Single Largest Order"; This program has three steps. First PROC SORT sorts the data by descending Quantity so that the first observation is the largest single order. Then a DATA step reads the sorted data, and in the first iteration of the DATA step (when _N_ = 1), uses CALL SYMPUT to assign the current value of CustomerID (287) to the macro variable &BIGGEST. The keyword _NULL_ in the DATA statement tells SAS not to bother creating a new SAS data set, and the STOP statement tells SAS to stop after the first iteration. The DATA _NULL_ and STOP are not necessary but they make the program more efficient by preventing SAS from reading and writing observations that won t be used. The final step takes the macro variable &BIGGEST and inserts its value into the PROC PRINT so that SAS selects just the orders for customer number 287. Here are the standard SAS statements that SAS will see after the macro processor has resolved the final step: *Print all obs for customer with biggest order; PROC PRINT DATA = orders NOOBS; WHERE CustomerID = "287"; FORMAT OrderDate DATE7.; TITLE "Customer 287 Had the Single Largest Order"; The output will look like this: Customer 287 Had the Single Largest Order Customer Order ID Date Model Quantity OCT03 Delta Breeze OCT03 Santa Ana OCT03 Delta Breeze OCT03 Santa Ana 15 CONCLUSIONS There is no doubt that macros can be very complicated, but don t let that scare you off. Learning to use macro variables and incorporating simple macros into your programs can also make your work a lot easier. Get your feet wet by starting with adding macro variables to your programs. Then when you get the hang of macro variables, start building simple macros. To avoid mangling your macros, always write them one piece at a time. First write your program in standard SAS code. When that is working and bug-free, then add your %MACRO and %MEND statements. When that is working, then add your parameters, if any, one at a time. 12
13 REFERENCES Delwiche, Lora D. and Susan J. Slaughter (2003). The Little SAS Book: A Primer, Third Edition. SAS Institute, Cary, NC. SUGGESTED READING Carpenter, Art (1998). Carpenter s Complete Guide to the SAS Macro Language. SAS Institute, Cary, NC. ABOUT THE AUTHORS Susan Slaughter and Lora Delwiche are also the authors of The Little SAS Book: A Primer published by SAS Institute, and may be contacted at: Susan J. Slaughter (530) Lora D. Delwiche (530) SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. indicates USA registration. 1 There are a few exceptions. %INCLUDE, for example, is not part of the macro facility despite its percent sign prefix. And it is possible, though rather confusing, to write macros that do not start with a percent sign. 13
Nine Steps to Get Started using SAS Macros
Paper 56-28 Nine Steps to Get Started using SAS Macros Jane Stroupe, SAS Institute, Chicago, IL ABSTRACT Have you ever heard your coworkers rave about macros? If so, you've probably wondered what all the
AN INTRODUCTION TO MACRO VARIABLES AND MACRO PROGRAMS Mike S. Zdeb, New York State Department of Health
AN INTRODUCTION TO MACRO VARIABLES AND MACRO PROGRAMS Mike S. Zdeb, New York State Department of Health INTRODUCTION There are a number of SAS tools that you may never have to use. Why? The main reason
From The Little SAS Book, Fifth Edition. Full book available for purchase here.
From The Little SAS Book, Fifth Edition. Full book available for purchase here. Acknowledgments ix Introducing SAS Software About This Book xi What s New xiv x Chapter 1 Getting Started Using SAS Software
Macros from Beginning to Mend A Simple and Practical Approach to the SAS Macro Facility
Macros from Beginning to Mend A Simple and Practical Approach to the SAS Macro Facility Michael G. Sadof, MGS Associates, Inc., Bethesda, MD. ABSTRACT The macro facility is an important feature of the
Writing cleaner and more powerful SAS code using macros. Patrick Breheny
Writing cleaner and more powerful SAS code using macros Patrick Breheny Why Use Macros? Macros automatically generate SAS code Macros allow you to make more dynamic, complex, and generalizable SAS programs
The Power of CALL SYMPUT DATA Step Interface by Examples Yunchao (Susan) Tian, Social & Scientific Systems, Inc., Silver Spring, MD
Paper 052-29 The Power of CALL SYMPUT DATA Step Interface by Examples Yunchao (Susan) Tian, Social & Scientific Systems, Inc., Silver Spring, MD ABSTRACT AND INTRODUCTION CALL SYMPUT is a SAS language
Foundations & Fundamentals. A PROC SQL Primer. Matt Taylor, Carolina Analytical Consulting, LLC, Charlotte, NC
A PROC SQL Primer Matt Taylor, Carolina Analytical Consulting, LLC, Charlotte, NC ABSTRACT Most SAS programmers utilize the power of the DATA step to manipulate their datasets. However, unless they pull
Anyone Can Learn PROC TABULATE
Paper 60-27 Anyone Can Learn PROC TABULATE Lauren Haworth, Genentech, Inc., South San Francisco, CA ABSTRACT SAS Software provides hundreds of ways you can analyze your data. You can use the DATA step
B) Mean Function: This function returns the arithmetic mean (average) and ignores the missing value. E.G: Var=MEAN (var1, var2, var3 varn);
SAS-INTERVIEW QUESTIONS 1. What SAS statements would you code to read an external raw data file to a DATA step? Ans: Infile and Input statements are used to read external raw data file to a Data Step.
Paper 2917. Creating Variables: Traps and Pitfalls Olena Galligan, Clinops LLC, San Francisco, CA
Paper 2917 Creating Variables: Traps and Pitfalls Olena Galligan, Clinops LLC, San Francisco, CA ABSTRACT Creation of variables is one of the most common SAS programming tasks. However, sometimes it produces
Programming Tricks For Reducing Storage And Work Space Curtis A. Smith, Defense Contract Audit Agency, La Mirada, CA.
Paper 23-27 Programming Tricks For Reducing Storage And Work Space Curtis A. Smith, Defense Contract Audit Agency, La Mirada, CA. ABSTRACT Have you ever had trouble getting a SAS job to complete, although
Labels, Labels, and More Labels Stephanie R. Thompson, Rochester Institute of Technology, Rochester, NY
Paper FF-007 Labels, Labels, and More Labels Stephanie R. Thompson, Rochester Institute of Technology, Rochester, NY ABSTRACT SAS datasets include labels as optional variable attributes in the descriptor
Demonstrating a DATA Step with and without a RETAIN Statement
1 The RETAIN Statement Introduction 1 Demonstrating a DATA Step with and without a RETAIN Statement 1 Generating Sequential SUBJECT Numbers Using a Retained Variable 7 Using a SUM Statement to Create SUBJECT
The SAS Data step/macro Interface
Paper TS09 The SAS Data step/macro Interface Lawrence Heaton-Wright, Quintiles, Bracknell, Berkshire, UK ABSTRACT The SAS macro facility is an extremely useful part of the SAS System. However, macro variables
SAS Comments How Straightforward Are They? Jacksen Lou, Merck & Co.,, Blue Bell, PA 19422
SAS Comments How Straightforward Are They? Jacksen Lou, Merck & Co.,, Blue Bell, PA 19422 ABSTRACT SAS comment statements typically use conventional symbols, *, %*, /* */. Most programmers regard SAS commenting
More Tales from the Help Desk: Solutions for Simple SAS Mistakes Bruce Gilsen, Federal Reserve Board
More Tales from the Help Desk: Solutions for Simple SAS Mistakes Bruce Gilsen, Federal Reserve Board INTRODUCTION In 20 years as a SAS consultant at the Federal Reserve Board, I have seen SAS users make
SAS PROGRAM EFFICIENCY FOR BEGINNERS. Bruce Gilsen, Federal Reserve Board
SAS PROGRAM EFFICIENCY FOR BEGINNERS Bruce Gilsen, Federal Reserve Board INTRODUCTION This paper presents simple efficiency techniques that can benefit inexperienced SAS software users on all platforms.
Storing and Using a List of Values in a Macro Variable
Storing and Using a List of Values in a Macro Variable Arthur L. Carpenter California Occidental Consultants, Oceanside, California ABSTRACT When using the macro language it is not at all unusual to need
Table Lookups: From IF-THEN to Key-Indexing
Paper 158-26 Table Lookups: From IF-THEN to Key-Indexing Arthur L. Carpenter, California Occidental Consultants ABSTRACT One of the more commonly needed operations within SAS programming is to determine
Taming the PROC TRANSPOSE
Taming the PROC TRANSPOSE Matt Taylor, Carolina Analytical Consulting, LLC ABSTRACT The PROC TRANSPOSE is often misunderstood and seldom used. SAS users are unsure of the results it will give and curious
Counting the Ways to Count in SAS. Imelda C. Go, South Carolina Department of Education, Columbia, SC
Paper CC 14 Counting the Ways to Count in SAS Imelda C. Go, South Carolina Department of Education, Columbia, SC ABSTRACT This paper first takes the reader through a progression of ways to count in SAS.
Using Macros to Automate SAS Processing Kari Richardson, SAS Institute, Cary, NC Eric Rossland, SAS Institute, Dallas, TX
Paper 126-29 Using Macros to Automate SAS Processing Kari Richardson, SAS Institute, Cary, NC Eric Rossland, SAS Institute, Dallas, TX ABSTRACT This hands-on workshop shows how to use the SAS Macro Facility
The SET Statement and Beyond: Uses and Abuses of the SET Statement. S. David Riba, JADE Tech, Inc., Clearwater, FL
The SET Statement and Beyond: Uses and Abuses of the SET Statement S. David Riba, JADE Tech, Inc., Clearwater, FL ABSTRACT The SET statement is one of the most frequently used statements in the SAS System.
The presentation will include a code review and presentation of reports that appear in both English and Italian.
SAS Reporting in English, ed anche in italiano: A Methodology for Creating Reports in Two Languages Deborah Testa, Seven of Nine Systems, Inc. Studio City, CA ABSTRACT Project Leonardo was a disease management
3.GETTING STARTED WITH ORACLE8i
Oracle For Beginners Page : 1 3.GETTING STARTED WITH ORACLE8i Creating a table Datatypes Displaying table definition using DESCRIBE Inserting rows into a table Selecting rows from a table Editing SQL buffer
New Tricks for an Old Tool: Using Custom Formats for Data Validation and Program Efficiency
New Tricks for an Old Tool: Using Custom Formats for Data Validation and Program Efficiency S. David Riba, JADE Tech, Inc., Clearwater, FL ABSTRACT PROC FORMAT is one of the old standards among SAS Procedures,
Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, 2008. 1 Introduction 1. 2 Invoking Shell Scripts 2
Unix Shell Scripts Norman Matloff July 30, 2008 Contents 1 Introduction 1 2 Invoking Shell Scripts 2 2.1 Direct Interpretation....................................... 2 2.2 Indirect Interpretation......................................
Post Processing Macro in Clinical Data Reporting Niraj J. Pandya
Post Processing Macro in Clinical Data Reporting Niraj J. Pandya ABSTRACT Post Processing is the last step of generating listings and analysis reports of clinical data reporting in pharmaceutical industry
PharmaSUG 2015 - Paper QT26
PharmaSUG 2015 - Paper QT26 Keyboard Macros - The most magical tool you may have never heard of - You will never program the same again (It's that amazing!) Steven Black, Agility-Clinical Inc., Carlsbad,
The. Little SAS Book
The A Programming Approach Little SAS Book a p r i m e r F I F T H E D I T I O N Lora D. Delwiche and Susan J. Slaughter From The Little SAS Book, Fifth Edition. Full book available for purchase here.
1 Checking Values of Character Variables
1 Checking Values of Character Variables Introduction 1 Using PROC FREQ to List Values 1 Description of the Raw Data File PATIENTS.TXT 2 Using a DATA Step to Check for Invalid Values 7 Describing the VERIFY,
Changing the Shape of Your Data: PROC TRANSPOSE vs. Arrays
Changing the Shape of Your Data: PROC TRANSPOSE vs. Arrays Bob Virgile Robert Virgile Associates, Inc. Overview To transpose your data (turning variables into observations or turning observations into
PROC MEANS: More than just your average procedure
Paper 68-25 PROC MEANS: More than just your average procedure Peter R. Welbrock Strategic Information Systems, Inc., Philadelphia, PA Abstract PROC MEANS and its close relative PROC SUMMARY have been two
Everything you wanted to know about using Hexadecimal and Octal Numbers in Visual Basic 6
Everything you wanted to know about using Hexadecimal and Octal Numbers in Visual Basic 6 Number Systems No course on programming would be complete without a discussion of the Hexadecimal (Hex) number
Reading Delimited Text Files into SAS 9 TS-673
Reading Delimited Text Files into SAS 9 TS-673 Reading Delimited Text Files into SAS 9 i Reading Delimited Text Files into SAS 9 Table of Contents Introduction... 1 Options Available for Reading Delimited
Data-driven Validation Rules: Custom Data Validation Without Custom Programming Don Hopkins, Ursa Logic Corporation, Durham, NC
Data-driven Validation Rules: Custom Data Validation Without Custom Programming Don Hopkins, Ursa Logic Corporation, Durham, NC ABSTRACT One of the most expensive and time-consuming aspects of data management
2: Entering Data. Open SPSS and follow along as your read this description.
2: Entering Data Objectives Understand the logic of data files Create data files and enter data Insert cases and variables Merge data files Read data into SPSS from other sources The Logic of Data Files
Microsoft Excel Tips & Tricks
Microsoft Excel Tips & Tricks Collaborative Programs Research & Evaluation TABLE OF CONTENTS Introduction page 2 Useful Functions page 2 Getting Started with Formulas page 2 Nested Formulas page 3 Copying
Paper 109-25 Merges and Joins Timothy J Harrington, Trilogy Consulting Corporation
Paper 109-25 Merges and Joins Timothy J Harrington, Trilogy Consulting Corporation Abstract This paper discusses methods of joining SAS data sets. The different methods and the reasons for choosing a particular
Selecting Features by Attributes in ArcGIS Using the Query Builder
Helping Organizations Succeed with GIS www.junipergis.com Bend, OR 97702 Ph: 541-389-6225 Fax: 541-389-6263 Selecting Features by Attributes in ArcGIS Using the Query Builder ESRI provides an easy to use
Programming Idioms Using the SET Statement
Programming Idioms Using the SET Statement Jack E. Fuller, Trilogy Consulting Corporation, Kalamazoo, MI ABSTRACT While virtually every programmer of base SAS uses the SET statement, surprisingly few programmers
Creating Raw Data Files Using SAS. Transcript
Creating Raw Data Files Using SAS Transcript Creating Raw Data Files Using SAS Transcript was developed by Mike Kalt. Additional contributions were made by Michele Ensor, Mark Jordan, Kathy Passarella,
Macro Quoting. Overview of Macro Quoting CHAPTER 7
71 CHAPTER 7 Macro Quoting Overview of Macro Quoting 71 Understanding Why Macro Quoting is Necessary 72 Understanding Macro Quoting Functions 72 Passing Parameters That Contain Special Characters and Mnemonics
Encoding Text with a Small Alphabet
Chapter 2 Encoding Text with a Small Alphabet Given the nature of the Internet, we can break the process of understanding how information is transmitted into two components. First, we have to figure out
Search and Replace in SAS Data Sets thru GUI
Search and Replace in SAS Data Sets thru GUI Edmond Cheng, Bureau of Labor Statistics, Washington, DC ABSTRACT In managing data with SAS /BASE software, performing a search and replace is not a straight
Paper 70-27 An Introduction to SAS PROC SQL Timothy J Harrington, Venturi Partners Consulting, Waukegan, Illinois
Paper 70-27 An Introduction to SAS PROC SQL Timothy J Harrington, Venturi Partners Consulting, Waukegan, Illinois Abstract This paper introduces SAS users with at least a basic understanding of SAS data
ABSTRACT INTRODUCTION %CODE MACRO DEFINITION
Generating Web Application Code for Existing HTML Forms Don Boudreaux, PhD, SAS Institute Inc., Austin, TX Keith Cranford, Office of the Attorney General, Austin, TX ABSTRACT SAS Web Applications typically
PROC REPORT: How To Get Started
PROC REPORT: How To Get Started Malachy J. Foley University of North Carolina at Chapel Hill, NC ABSTRACT PROC REPORT started as a soupped-up version of PROC PRINT. Now this unique product combines features
You have got SASMAIL!
You have got SASMAIL! Rajbir Chadha, Cognizant Technology Solutions, Wilmington, DE ABSTRACT As SAS software programs become complex, processing times increase. Sitting in front of the computer, waiting
Technical Paper. Reading Delimited Text Files into SAS 9
Technical Paper Reading Delimited Text Files into SAS 9 Release Information Content Version: 1.1July 2015 (This paper replaces TS-673 released in 2009.) Trademarks and Patents SAS Institute Inc., SAS Campus
Microsoft Query, the helper application included with Microsoft Office, allows
3 RETRIEVING ISERIES DATA WITH MICROSOFT QUERY Microsoft Query, the helper application included with Microsoft Office, allows Office applications such as Word and Excel to read data from ODBC data sources.
IF The customer should receive priority service THEN Call within 4 hours PCAI 16.4
Back to Basics Backward Chaining: Expert System Fundamentals By Dustin Huntington Introduction Backward chaining is an incredibly powerful yet widely misunderstood concept, yet it is key to building many
Paper TU_09. Proc SQL Tips and Techniques - How to get the most out of your queries
Paper TU_09 Proc SQL Tips and Techniques - How to get the most out of your queries Kevin McGowan, Constella Group, Durham, NC Brian Spruell, Constella Group, Durham, NC Abstract: Proc SQL is a powerful
Access Tutorial 2: Tables
Access Tutorial 2: Tables 2.1 Introduction: The importance of good table design Tables are where data in a database is stored; consequently, tables form the core of any database application. In addition
SAS: A Mini-Manual for ECO 351 by Andrew C. Brod
SAS: A Mini-Manual for ECO 351 by Andrew C. Brod 1. Introduction This document discusses the basics of using SAS to do problems and prepare for the exams in ECO 351. I decided to produce this little guide
Microsoft Access Lesson 5: Structured Query Language (SQL)
Microsoft Access Lesson 5: Structured Query Language (SQL) Structured Query Language (pronounced S.Q.L. or sequel ) is a standard computing language for retrieving information from and manipulating databases.
9.1 SAS. SQL Query Window. User s Guide
SAS 9.1 SQL Query Window User s Guide The correct bibliographic citation for this manual is as follows: SAS Institute Inc. 2004. SAS 9.1 SQL Query Window User s Guide. Cary, NC: SAS Institute Inc. SAS
Preparing your data for analysis using SAS. Landon Sego 24 April 2003 Department of Statistics UW-Madison
Preparing your data for analysis using SAS Landon Sego 24 April 2003 Department of Statistics UW-Madison Assumptions That you have used SAS at least a few times. It doesn t matter whether you run SAS in
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
Would You Like To Earn $1000 s With The Click Of A Button?
Would You Like To Earn $1000 s With The Click Of A Button? (Follow these easy step by step instructions and you will) This Version of the ebook is for all countries other than the USA. If you need the
Click to create a query in Design View. and click the Query Design button in the Queries group to create a new table in Design View.
Microsoft Office Access 2010 Understanding Queries Queries are questions you ask of your database. They allow you to select certain fields out of a table, or pull together data from various related tables
Essential Project Management Reports in Clinical Development Nalin Tikoo, BioMarin Pharmaceutical Inc., Novato, CA
Essential Project Management Reports in Clinical Development Nalin Tikoo, BioMarin Pharmaceutical Inc., Novato, CA ABSTRACT Throughout the course of a clinical trial the Statistical Programming group is
Performing Queries Using PROC SQL (1)
SAS SQL Contents Performing queries using PROC SQL Performing advanced queries using PROC SQL Combining tables horizontally using PROC SQL Combining tables vertically using PROC SQL 2 Performing Queries
USING PROCEDURES TO CREATE SAS DATA SETS... ILLUSTRATED WITH AGE ADJUSTING OF DEATH RATES 1
USING PROCEDURES TO CREATE SAS DATA SETS... ILLUSTRATED WITH AGE ADJUSTING OF DEATH RATES 1 There may be times when you run a SAS procedure when you would like to direct the procedure output to a SAS data
A Method for Cleaning Clinical Trial Analysis Data Sets
A Method for Cleaning Clinical Trial Analysis Data Sets Carol R. Vaughn, Bridgewater Crossings, NJ ABSTRACT This paper presents a method for using SAS software to search SAS programs in selected directories
Access Queries (Office 2003)
Access Queries (Office 2003) Technical Support Services Office of Information Technology, West Virginia University OIT Help Desk 293-4444 x 1 oit.wvu.edu/support/training/classmat/db/ Instructor: Kathy
Intellect Platform - The Workflow Engine Basic HelpDesk Troubleticket System - A102
Intellect Platform - The Workflow Engine Basic HelpDesk Troubleticket System - A102 Interneer, Inc. Updated on 2/22/2012 Created by Erika Keresztyen Fahey 2 Workflow - A102 - Basic HelpDesk Ticketing System
Moving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
PHP Debugging. Draft: March 19, 2013 2013 Christopher Vickery
PHP Debugging Draft: March 19, 2013 2013 Christopher Vickery Introduction Debugging is the art of locating errors in your code. There are three types of errors to deal with: 1. Syntax errors: When code
Intellect Platform - Tables and Templates Basic Document Management System - A101
Intellect Platform - Tables and Templates Basic Document Management System - A101 Interneer, Inc. 4/12/2010 Created by Erika Keresztyen 2 Tables and Templates - A101 - Basic Document Management System
Innovative Techniques and Tools to Detect Data Quality Problems
Paper DM05 Innovative Techniques and Tools to Detect Data Quality Problems Hong Qi and Allan Glaser Merck & Co., Inc., Upper Gwynnedd, PA ABSTRACT High quality data are essential for accurate and meaningful
What You re Missing About Missing Values
Paper 1440-2014 What You re Missing About Missing Values Christopher J. Bost, MDRC, New York, NY ABSTRACT Do you know everything you need to know about missing values? Do you know how to assign a missing
Getting started with the Stata
Getting started with the Stata 1. Begin by going to a Columbia Computer Labs. 2. Getting started Your first Stata session. Begin by starting Stata on your computer. Using a PC: 1. Click on start menu 2.
Computer Programming In QBasic
Computer Programming In QBasic Name: Class ID. Computer# Introduction You've probably used computers to play games, and to write reports for school. It's a lot more fun to create your own games to play
EXTRACTING DATA FROM PDF FILES
Paper SER10_05 EXTRACTING DATA FROM PDF FILES Nat Wooding, Dominion Virginia Power, Richmond, Virginia ABSTRACT The Adobe Portable Document File (PDF) format has become a popular means of producing documents
Building Qualtrics Surveys for EFS & ALC Course Evaluations: Step by Step Instructions
Building Qualtrics Surveys for EFS & ALC Course Evaluations: Step by Step Instructions Jennifer DeSantis August 28, 2013 A relatively quick guide with detailed explanations of each step. It s recommended
Access 2010: Creating Queries Table of Contents INTRODUCTION TO QUERIES... 2 QUERY JOINS... 2 INNER JOINS... 3 OUTER JOINS...
Access 2010: Creating Queries Table of Contents INTRODUCTION TO QUERIES... 2 QUERY JOINS... 2 INNER JOINS... 3 OUTER JOINS... 3 CHANGE A JOIN PROPERTY... 4 REMOVING A JOIN... 4 CREATE QUERIES... 4 THE
Integrating the Internet into Your Measurement System. DataSocket Technical Overview
Integrating the Internet into Your Measurement System DataSocket Technical Overview Introduction The Internet continues to become more integrated into our daily lives. This is particularly true for scientists
How to Reduce the Disk Space Required by a SAS Data Set
How to Reduce the Disk Space Required by a SAS Data Set Selvaratnam Sridharma, U.S. Census Bureau, Washington, DC ABSTRACT SAS datasets can be large and disk space can often be at a premium. In this paper,
Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)
Unit- I Introduction to c Language: C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating
Basics of STATA. 1 Data les. 2 Loading data into STATA
Basics of STATA This handout is intended as an introduction to STATA. STATA is available on the PCs in the computer lab as well as on the Unix system. Throughout, bold type will refer to STATA commands,
Intellect Platform - Parent-Child relationship Basic Expense Management System - A103
Intellect Platform - Parent-Child relationship Basic Expense Management System - A103 Interneer, Inc. Updated 2/29/2012 Created by Erika Keresztyen Fahey 2 Parent-Child relationship - A103 - Basic Expense
Let the CAT Out of the Bag: String Concatenation in SAS 9 Joshua Horstman, Nested Loop Consulting, Indianapolis, IN
Paper S1-08-2013 Let the CAT Out of the Bag: String Concatenation in SAS 9 Joshua Horstman, Nested Loop Consulting, Indianapolis, IN ABSTRACT Are you still using TRIM, LEFT, and vertical bar operators
Instant Interactive SAS Log Window Analyzer
ABSTRACT Paper 10240-2016 Instant Interactive SAS Log Window Analyzer Palanisamy Mohan, ICON Clinical Research India Pvt Ltd Amarnath Vijayarangan, Emmes Services Pvt Ltd, India An interactive SAS environment
PharmaSUG 2013 - Paper MS05
PharmaSUG 2013 - Paper MS05 Be a Dead Cert for a SAS Cert How to prepare for the most important SAS Certifications in the Pharmaceutical Industry Hannes Engberg Raeder, inventiv Health Clinical, Germany
A Faster Index for sorted SAS Datasets
A Faster Index for sorted SAS Datasets Mark Keintz Wharton Research Data Services, Philadelphia PA ABSTRACT In a NESUG 2007 paper with Shuguang Zhang, I demonstrated a condensed index which provided significant
PharmaSUG 2014 Paper CC23. Need to Review or Deliver Outputs on a Rolling Basis? Just Apply the Filter! Tom Santopoli, Accenture, Berwyn, PA
PharmaSUG 2014 Paper CC23 Need to Review or Deliver Outputs on a Rolling Basis? Just Apply the Filter! Tom Santopoli, Accenture, Berwyn, PA ABSTRACT Wouldn t it be nice if all of the outputs in a deliverable
Using SQL Queries in Crystal Reports
PPENDIX Using SQL Queries in Crystal Reports In this appendix Review of SQL Commands PDF 924 n Introduction to SQL PDF 924 PDF 924 ppendix Using SQL Queries in Crystal Reports The SQL Commands feature
SAS Macro Autocall and %Include
Paper CC-019 SAS Macro Autocall and %Include Jie Huang, Merck & Co., Inc. Tracy Lin, Merck & Co., Inc. ABSTRACT SAS provides several methods to invoke external SAS macros in a SAS program. There are two
Let SAS Modify Your Excel File Nelson Lee, Genentech, South San Francisco, CA
ABSTRACT PharmaSUG 2015 - Paper QT12 Let SAS Modify Your Excel File Nelson Lee, Genentech, South San Francisco, CA It is common to export SAS data to Excel by creating a new Excel file. However, there
This can be useful to temporarily deactivate programming segments without actually deleting the statements.
EXST 700X SAS Programming Tips Page 1 SAS Statements: All SAS statements end with a semicolon, ";". A statement may occur on one line, or run across several lines. Several statements can also be placed
Importing Excel Files Into SAS Using DDE Curtis A. Smith, Defense Contract Audit Agency, La Mirada, CA
Importing Excel Files Into SAS Using DDE Curtis A. Smith, Defense Contract Audit Agency, La Mirada, CA ABSTRACT With the popularity of Excel files, the SAS user could use an easy way to get Excel files
