170 likes | 267 Vues
Learn all about SAS Macros, their definition, advantages, usage, variables, parameterization, calling techniques, and debugging methods. Discover how Macros enhance flexibility, save time, and facilitate complex programming tasks in SAS.
E N D
BMTRY 789 Lecture 10: SAS MACRO Facility Annie N. Simpson, MSc.
What's a MACRO? MACRO: a rule or pattern that specifies how a certain input sequence should be mapped to an output sequence according to a defined procedure. (Wikipedia)
Facts about Macros • SAS macro code is separate from SAS code • Allows you to do repetitive assignments where the only difference is a variable (s) • Enables great flexibility in SAS programming and saves time
Macros from beginning to %Mend • The % typically identifies a macro command • Code enclosed within %MACRO and %MEND are viewed by SAS as a program • You can (almost) freely mix regular SAS code with Macro code • Once you define a macro program, you then need to “call” (or invoke) it • You call a macro by %«macro name» (you don't use the word MACRO when you call it...only when you are defining it)
MACRO VARIABLE • Macro variables are either defined by a %LET statement or as parameters within a macro program • A macro variable is referenced in your program by preceding the macro variable name with an ampersand (&).
LAB DATA Example • Consider you want to create BOXPLOTS for several lab tests: • Hemoglobin, Hematocrit, Platelets • Each BOXPLOT should have its own title and axis. • Of course, we will use SAS for this
Adding Parameters to Macros • Once you identify potential parameters, list them out in parenthesis separated by a comma in the MACRO declaration • When you call the MACRO, you pass the values to the MACRO again in parenthesis separated by commas
What happens? • What happens if you run this program? • ?? • Let's check the log
Don’t forget to CALL! • Nothing happened because we didn't CALL the macro • Here's what the log reads after we call %labs
SAS LOG WILL LOOK DIFFERENT • Note, in the SAS MACRO log, you do not get the NOTES interspersed with the PROC statements • Why? Because the entire MACRO gets compiled into a bundle of code • You can “look” into the bundle of code by using the MPRINT system option
%Put • On occasion, you may want to “look inside” a macro variable to see what value is stored • This often occurs during debugging parameters • You accomplish this by the %Put statement followed by the variable name • %Put writes values to the SAS LOG • There are also special %Put statements: %put _all_ %put _user_ %put _local_ %put _global_
%LET • Creates a macro variable and assigns it a value • %LET can be used inside or outside of a macro program Syntax %LET macro-variable =<value>; (CAN BE A STRING OF WORDS)
Conclusions • MACROS save time • Necessary when have a large number of variables. • Imagine running a regression for every variable when you have 100+ variables! • Programs are reusable and easier to understand.