SlideShare a Scribd company logo
SAS/MACROS
Chapter 2. Using Macro Variable Venkata Maguluri
Section 2.1 Basic Concepts Basic Concepts
Objectives Learn where macro variables are stored. Substitute the value of a macro variable anywhere in a program. Monitor the value that is substituted when a macro variable is referenced. Display macro variable values and text in the SAS log. Basic Concepts
Global Macro Variables Whenever the SAS System is invoked, a  global  symbol table is created and initialized with  automatic   or system-defined macro variables. You can also create  user-defined   global macro variables with the %LET statement: %let city=Dallas; %let date=05JAN2000; %let amount=975; Automatic Variables Global Symbol Table .  . .  . SYSTIME  09:47 SYSVER  8.01 .  . .  . CITY  Dallas DATE  05JAN2000 AMOUNT  975 User-defined Variables Basic Concepts
Referencing a Macro Variable To substitute the value of a macro variable in your program, you must reference it. A macro variable reference is made by preceding the macro variable name with an  ampersand  (&) causes the macro processor to search for the named variable and return its value if the variable exists. Basic Concepts
Referencing a Macro Variable Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975 Example: Use a macro variable reference to make a substitution in a SAS program statement. where fee>&amount; generates WHERE FEE>975; Basic Concepts
Referencing a Macro Variable The word scanner continues to tokenize literals enclosed in  double  quotes, permitting macro variables to resolve. where cityst CONTAINS "&city";  generates   WHERE CITYST CONTAINS "Dallas"; If you need to reference a macro variable within a  literal, enclose the literal in double quotes. The word scanner does not tokenize literals enclosed in  single  quotes, so macro variables do not resolve. where cityst contains '&city';  generates   WHERE CITYST CONTAINS '&city'; Basic Concepts Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975
Referencing a Macro Variable Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975 Referencing a nonexistent macro variable results in a warning message. title "Students from &cityst";   generates WARNING: Apparent symbolic reference CITYST not resolved. When the macro processor cannot act upon a macro variable reference, a message is printed in the SAS log. Basic Concepts
Referencing a Macro Variable Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975 Referencing an invalid macro variable name results in an error message. title "Students from &the_city_in_which_the_student_is_located"; generates ERROR: Symbolic variable name THE_CITY_IN_WHICH_THE_STUDENT_IS_LOCATED must be 32 or fewer characters long. Basic Concepts
Displaying Macro Variable Values Use the SYMBOLGEN system option to monitor the value that is substituted for a macro variable referenced.  General form of the  SYMBOLGEN  system option: OPTIONS  SYMBOLGEN; This system option displays the results of resolving macro variable references in the SAS log. Note: The default option setting is  NOSYMBOLGEN . Basic Concepts
Displaying Macro Variable Values Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975 Partial SAS Log where fee>&amount; SYMBOLGEN: Macro variable AMOUNT resolves to 975 where city_state contains "&city"; SYMBOLGEN: Macro variable CITY resolves to Dallas where city_state contains ’&city’; Why is no message displayed for the final example? Basic Concepts
Displaying Macro Variable Values To verify the values of macro variables, you may want to write your own messages to the SAS log. The %PUT statement writes text to the SAS log. General form of the %PUT statement: %PUT  text ; Basic Concepts
writes to the  SAS log only always writes to a new log line starting in column one writes a blank line if  text  is not specified does not require quotes around  tex t The %PUT statement continued... Displaying Macro Variable Values Basic Concepts
resolves macro triggers in  text  before   text  is written removes leading and trailing blanks from  text  unless a macro quoting function is used wraps lines when the length of  text  is greater than the current line size setting can be used inside or outside a macro definition. Displaying Macro Variable Values Basic Concepts
Example: Write a message to the SAS log to verify the value of the macro variable CITY. Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975 Partial SAS Log %put The value of the macro variable CITY is: &city; The value of the macro variable CITY is: Dallas Displaying Macro Variable Values Basic Concepts
Section 2.2 Automatic Macro Variables
Objectives Identify selected automatic macro variables. Display values of automatic macro variables in the SAS log. Automatic Micro Variables
System-Defined Automatic Macro Variables are created at SAS invocation are global (always available) are usually assigned values by SAS can be assigned values by the user in some cases. These variables Automatic Micro Variables
Some automatic macro variables have fixed values that are set at SAS invocation: Name   Value SYSDATE  date of SAS invocation (DATE7.) SYSDATE9 date of SAS invocation (DATE9.) SYSDAY  day of the week of SAS invocation SYSTIME  time of SAS invocation SYSENV  FORE (interactive execution) BACK (noninteractive or batch execution) SYSSCP  abbreviation for the operating system used such as OpenVMS, WIN, HP 300 SYSVER  release of SAS software being used SYSJOBID identifier of current SAS session  or batch job  mainframe systems:the userid or job name other systems: the process ID (PID). System-Defined Automatic Macro Variables Automatic Micro Variables
Some automatic macro variables have values that automatically change based on submitted SAS statements: System-Defined Automatic Macro Variables Automatic Micro Variables Name  Value SYSLAST  name of most recently created SAS  data set in the form  libref.nam e.  If no data set has been created, the value is _NULL_. SYSPARM  text specified at program invocation.
Example: Substitute system information in footnotes for a report. footnote1 "Created &systime &sysday, &sysdate9"; footnote2  "on the &sysscp system using Release &sysver"; title "REVENUES FOR DALLAS TRAINING CENTER"; proc tabulate data=perm.all(keep=location course_title fee); where upcase(location)="DALLAS"; class course_title; var fee; table course_title=" " all="TOTALS", fee=" "*(n*f=3. sum*f=dollar10.) / rts=30 box="COURSE"; run; System-Defined Automatic Macro Variables Automatic Micro Variables
System-Defined Automatic Macro Variables Automatic Micro Variables
The values of automatic macro variables can be displayed in the SAS log by specifying the _AUTOMATIC_ argument in the %PUT statement. %put _automatic_; System-Defined Automatic Macro Variables Automatic Micro Variables
Partial SAS Log The values of the macro variables SYSDATE, SYSDATE9, and SYSTIME are  character strings ,  not  SAS date or time values. System-Defined Automatic Macro Variables Automatic Micro Variables
Applications for Automatic  Variables SYSDATE  Check the current date to execute programs or   on certain days of the month. Substitute  SYSDATE9 the value in a TITLE statement. SYSDAY  Check the value to run a given job on a  certain day of the week. SYSENV  Check the execution mode before submitting code that requires interactive(foreground) processing. Possible applications for automatic macro variables: Automatic Micro Variables
Applications for Automatic  Variables SYSVER Check for the release of SAS software being used before executing a job with newer features. SYSJOBID Check who is currently executing the job to restrict certain processing or issue commands specific to a user . SYSERR Check the return code from a SAS procedure or DATA step and abort the job if the return code is nonzero. SYSRC Check the return code of any system command before continuing with the job. Automatic Micro Variables
The SYSPARM Macro Variable (Self-Study) OS/390   // EXEC SAS,OPTIONS='SYSPARM=SEATTLE' BATCH   //SYSIN DD DSN= program-name,DISP=SHR TSO   sas input(''' program-name''')   opt('sysparm=SEATTLE') CMS   sas program-name (sysparm=SEATTLE) OpenVMS sas/sysparm=SEATTLE program-name Windows sas program-name -sysparm SEATTLE UNIX Using the SYSPARM= system option to supply a value for the SYSPARM macro variable at SAS invocation.  To assign the value  SEATTLE  to the SYSPARM macro variable, specify the SYSPARM= system option: Automatic Micro Variables
title "REVENUES FOR &sysparm TRAINING CENTER"; proc tabulate data=perm.all(keep=location course_title fee); where upcase(location)="&sysparm"; class course_title; var fee; table course_title=’ ’ all=’TOTALS’, fee=’ ’*(n*f=3. sum*f=dollar10.) / rts=30 box=’COURSE’; run; Example: Use one program to create a revenue report for any training center. Supply the name of the center at SAS invocation. The SYSPARM Macro Variable (Self-Study) Automatic Micro Variables
Output for SYSPARM Value of  SEATTLE The SYSPARM Macro Variable (Self-Study) Automatic Micro Variables
Section 2.3 User-Defined Macro Variables
Objectives Create your own macro variables. Display values of user-defined macro variables in the SAS log. User-Defined Micro Variables
The %LET  Statement The %LET statement enables you to define a macro variable and assign it a value. General form of the %LET statement: %LET  variable = value ; User-Defined Micro Variables
Rules for the %LET statement: variable   can be any name following the SAS  naming convention. if  variable   already exists in the symbol table,   value   replaces  the current value. if either  variable   or  value   contains a macro  trigger, the trigger is evaluated  before  the  assignment is made. continued... The %LET  Statement User-Defined Micro Variables
Rules for the %LET statement: value   can be any string: - maximum length is 32K characters - minimum length is 0 characters  (null valu e) - numeric tokens are stored as character strings - mathematical expressions are  not  evaluated - the case of  value   is preserved - quotes bounding literals are stored as part of  value - leading and trailing blanks  are removed  from  value   before the assignment is made. The %LET  Statement User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; Value ... The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; Value Ed Norton The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” 0 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” 0 3+4 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 varlist ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 varlist name age height ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Example: Assign the value  DALLAS  to the macro  variable SITE. Use the macro variable to control program output. %let site=DALLAS; title "REVENUES FOR &site TRAINING CENTER"; proc tabulate data=perm.all(keep=location  course_title fee); where upcase(location)="&site"; class course_title; var fee; table course_title=’ ’ all=’TOTALS’, fee=’ ’*(n*f=3. sum*f=dollar10.) / rts=30 box=’COURSE’; run; The %LET  Statement Examples User-Defined Micro Variables
PROC TABULATE Output The %LET  Statement Examples User-Defined Micro Variables
Displaying User-defined Macro Variables The values of user-defined macro variables can be displayed in the SAS log by specifying the _USER_ argument in the %PUT statement. %let city=Dallas; %let date=22MAY95; %let amount=795; %put _user_; continued... User-Defined Micro Variables
Note: The statement  %put _all_;  displays both  automatic and user-defined macro variables. Partial SAS Log Displaying User-defined Macro Variables User-Defined Micro Variables
Tips on Writing Macro-based Programs write and debug the desired SAS program without any macro coding make sure the SAS program runs with hard-coded programming constants on a fixed set of data generalize the program by removing hard-coded programming constants and substituting macro variable references initialize the macro variables with %LET statements and try different values for the macro variables use the SYMBOLGEN system option to assist in debugging or confirmation. If you use a macro to generate SAS code, User-Defined Micro Variables
Using Macro Functions
Objectives Use macro functions to manipulate character strings and other operations. Using Micro Functions
Many macro applications require character string manipulation. Selected macro character functions: %UPCASE translates letters from lowercase to uppercase. %SUBSTR produces a substring of a character string.  %SCAN extracts a word from a character string. %LENGTH determines the length of a character string. Using Micro Functions
Macro functions have the same basic syntax as the corresponding DATA step functions and yield similar results. Manipulating Character Strings Using Micro Functions
Most comparison operators in the SAS language are case sensitive. Example: Create a summary of total fees  outstanding for each course. %let paidval=n; proc means data=perm.all sum maxdec=0; where paid="&paidval"; var fee; class course_title; title "Outstanding Fees for Each Course"; run; Using Micro Functions
Because the  value  of the macro variable PAIDVAL was specified in  lowercase , the WHERE expression finds no matching observations. All the  values  of the data set variable PAID are in  uppercase . Partial Log Case of Text Issues Using Micro Functions
You can use the %UPCASE function to translate the  value  of a macro variable to uppercase  before  substituting its value in a SAS program.  General form of the %UPCASE function: % UPCASE ( argumen t) Case of Text Issues Using Micro Functions
Example: For each course, create a summary of total fees outstanding and account for case.  %let paidval=n; proc means data=perm.all sum maxdec=0; where upcase(paid)=”%upcase(&paidval)"; var fee; class course_title; title "Outstanding Fees for Each Course"; run; Case of Text Issues Using Micro Functions
Case of Text Issues Using Micro Functions
Extracting Parts of Strings requires the first two arguments. The third argument is optional. returns the portion of  argument  beginning at  position  for a length of  n  characters. The %SUBSTR function General form of the %SUBSTR function: %SUBSTR ( argumen t,  position  < ,n >) continued… Using Micro Functions
returns the portion of  argument  beginning at  position  to the end of  argument  when an  n  value is not supplied. produces a warning and reads from  position  to the end of  argumen t, if a n n  value is supplied that extends beyond the bounds of  argumen t. Extracting Parts of Strings Using Micro Functions
constant text macro variable references macro functions macro calls. You can specify  argumen t,  positio n, and  n  values using General form of the %SUBSTR function: %SUBSTR ( argumen t,  position  < ,n >) It is not necessary to place  argument  in quotes because it is  always  handled as a character string by the %SUBSTR function. Extracting Parts of Strings Using Micro Functions
Example: Print all courses held since the start of the current month. Use the %SUBSTR  function and SYSDATE9 macro variable to determine the month and year. proc print data=perm.schedule; where begin_date between &quot;01%substr(&sysdate9,3)&quot;d and &quot;&sysdate9&quot;d; title &quot;All Courses Held So Far This Month&quot;; title2 &quot;(as of &sysdate9)&quot;; run; Extracting Parts of Strings Using Micro Functions
Extracting Parts of Strings Using Micro Functions
You can assign several words to a macro variable’s value and extract them with the %SCAN function. General form of the %SCAN function: %SCAN ( argument ,  n  <  , delimiter s>) Extracting Parts of Strings Using Micro Functions
requires the  first two arguments .  returns the  nth  word of  argumen t , where words are strings of characters separated by delimiters. Consecutive delimiters are treated as one delimiter. uses a  default set of delimiters  if none are specified. returns a  null string  if there are fewer than  n w ords in  argumen t. The %SCAN function Extracting Parts of Strings Using Micro Functions
constant text macro variable references macro functions macro calls. %SCAN ( argument ,  n  <  , delimiter s>) You can specify values for  argument ,   n , and  delimiters  using The value of  n  can also be an arithmetic expression that yields an  integer . Extracting Parts of Strings Using Micro Functions
Example: Use PROC DATASETS to investigate the structure of the last data set created. data work.thisyear; set perm.schedule; where year(begin_date) = year(“sysdate9”d); run; %let libref=%scan(&syslast,1); %let dsname=%scan(&syslast,2,.); proc datasets lib=&libref nolist; title &quot;Contents of the Data Set &syslast&quot;; contents data=&dsname; run; quit; Extracting Parts of Strings Using Micro Functions
Partial Output Extracting Parts of Strings Using Micro Functions
By using the automatic macro variables  SYSDATE9  and  SYSTIME  you can include the date and time in a title: title &quot;Report Produced on &sysdate9.&quot;; title2 &quot;at &systime.&quot;; generates Using Micro Functions
SYSDATE9  represents the  date  that the  SAS session started  and  SYSTIME  represents the  time  the  SAS session started .  If you started your interactive SAS session at 10:30 PM yesterday, what  date and time  would be in your report? What if you wanted to see the date or time in some other format besides DATE9.? Other SAS Functions Using Micro Functions
You can utilize the %SYSFUNC macro function  to execute SAS functions.  Example: The following code was submitted on Friday,  June 9, 2000: title &quot;%sysfunc(today(),weekdate.) - SALES REPORT&quot;; The title on the next report would be Friday, June 9, 2000 – SALES REPORT Other SAS Functions Using Micro Functions
General form of the %SYSFUNC function: %SYSFUNC (function(argument(s)) <,format>) The first argument is  required . The second argument is  optional . function(argument(s))  is the name of one of  most SAS functions and the corresponding  arguments. Other SAS Functions Using Micro Functions
All SAS functions can be used with %SYSFUNC except: DIF DIM HBOUND IORCMSG INPUT LAG LBOUND MISSING PUT RESOLVE SYMGET  All Variable Information Functions Other SAS Functions Using Micro Functions
Combining Macro Variable References with Text
Objectives Place a macro variable reference adjacent to text or another macro variable reference. Combining Micro Variable references with Text
You can reference macro variables anywhere in your program. Some applications may require placing a macro variable reference adjacent to leading and/or trailing text tex t &variable &variable text tex t &variable text or referencing adjacent macro variables &variable &variable in order to build a new token. Combining Macro Variable references with Text
You can place text immediately before a macro variable reference to build a new token. Example: Data sets are stored in a SAS data library with this naming convention: Y yymon yy  can be  90 ,  91 ,  92 ,  93 ,  94 , and so on. mon  can be  JAN ,  FEB ,  MAR , and so on. Write a program that uses a macro variable to build the month portion of the SAS data set name. Combining Macro Variable references with Text
%let month=jan; proc chart data=perm.y90 &month ; hbar week / sumvar=sale; run; proc plot data=perm.y90 &month ; plot sale*day; run; PROC CHART DATA=PERM.Y90 JAN ; HBAR WEEK / SUMVAR=SALE; RUN; PROC PLOT DATA=PERM.Y90 JAN ; PLOT SALE*DAY; RUN; generates Combining Macro Variables with Text Combining Micro Variable references with Text
You can reference macro variables that have no blanks between them to build new tokens. Example: Modify the previous program to allow both the month  and the year  to be  substituted. %let year=90 ; %let month=jan; proc chart data=perm.y &year &month; hbar week / sumvar=sale; run; proc plot data=perm.y &year &month; plot sale*day; run; Combining Macro Variables with Text Combining Micro Variable references with Text
PROC CHART DATA=PERM.Y 90 JAN; HBAR WEEK / SUMVAR=SALE; RUN; PROC PLOT DATA=PERM.Y 90 JAN; PLOT SALE*DAY; RUN; The generated program is identical to the program in the previous example. Combining Macro Variables with Text Combining Micro Variable references with Text
You can place text immediately after a macro variable reference if it does not change the macro variable name. Example: Modify the previous program to  substitute the name of an analysis  variable. %let year=90; %let month=jan; %let var=sale; proc chart data=perm.y&year&month; hbar week / sumvar =&var ; run; proc plot data=perm.y&year&month; plot  &var *day; run; Combining Macro Variables with Text Combining Micro Variable references with Text
PROC CHART DATA=PERM.Y90JAN; HBAR WEEK / SUMVAR= SALE ; RUN; PROC PLOT DATA=PERM.Y90JAN; PLOT  SALE *DAY; RUN; The generated program is identical to the program in the previous example. Combining Macro Variables with Text Combining Micro Variable references with Text
Example: Modify the previous program to allow a base SAS or SAS/GRAPH procedure. /* GRAPHICS should be null or G */ %let graphics=g ; %let year=90; %let month=jan; %let var=sale; proc  &graphicschart  data=perm.y&year&month; hbar week / sumvar=&var; run; proc  &graphicsplot  data=perm.y&year&month; plot &var*day; run; What is wrong with this program? Combining Macro Variables with Text Combining Micro Variable references with Text
SAS interprets the macro variable’s name to be GRAPHICSCHART because there is no delimiter between the macro reference and the rest of the text. Partial Log Combining Macro Variables with Text Combining Micro Variable references with Text
Macro Variable Name Delimiter The word scanner recognizes the end of a macro variable name when it encounters a character that cannot be part of the name token. A  period ( .) is a special character that is treated as part of the macro variable reference and does not appear when the macro variable is resolved. Combining Micro Variable references with Text
Example: Correct the resolution problem in the previous example. %let graphics=g; %let year=90; %let month=jan; %let var=sale; proc  &graphics. chart data=perm.y&year&month; hbar week / sumvar=&var; run; proc  &graphics. plot data=perm.y&year&month; plot &var*day; run; Macro Variable Name Delimiter Combining Micro Variable references with Text
word scanner treats  &graphics.  as the reference value of the macro variable GRAPHICS is returned to the input stack word scanner processes  gchart  as one token. If these SAS statements are executed, the PROC  GCHART  DATA=PERM.Y90JAN; HBAR WEEK / SUMVAR=SALE; RUN; PROC  GPLOT  DATA=PERM.Y90JAN; PLOT SALE*DAY; RUN; The SAS compiler receives Macro Variable Name Delimiter Combining Micro Variable references with Text
Example: Modify the previous program to include a macro variable used to define the libref. %let lib=perm; %let graphics=g; %let year=90; %let month=jan; %let var=sale; libname &lib ’SAS-data-library’; proc &graphics.chart data =&lib. y&year&month; hbar week / sumvar=&var; run; proc &graphics.plot data =&lib. y&year&month; plot &var*day; run; What is the problem this time? Macro Variable Name Delimiter Combining Micro Variable references with Text
The statements %let lib=perm; ... libname  &lib  'SAS-data-library'; proc &graphics.chart data= &lib .y &year&month ; ... proc &graphics.plot data =&lib .y &year&month ; LIBNAME  PERM  'SAS-data-library'; PROC GCHART DATA= PERM Y 90JAN ; HBAR WEEK / SUMVAR=SALE; RUN; PROC GPLOT DATA= PERM Y 90JAN ; PLOT SALE*DAY; RUN; send these statements to the SAS compiler: The period after  &lib  is interpreted as a delimiter. Macro Variable Name Delimiter Combining Micro Variable references with Text
Use another period after the delimiter period to supply the needed token. %let lib=perm; ... libname  &lib  'SAS-data-library'; proc &graphics.chart data= &lib ..y &year&month ; ... proc &graphics.plot data =&lib ..y &year&month ; Macro Variable Name Delimiter Combining Micro Variable references with Text
proc &graphics.chart data= &lib ..y &year&month ; ... PROC GCHART DATA= PERM .Y 90JAN ; ... The first period is treated as a macro variable name delimiter. The second period is simply text. The compiler receives delimiter text Macro Variable Name Delimiter Combining Micro Variable references with Text
Quoting in the Macro Facility
Objectives Describe when macro quoting functions are needed. Protect tokens so the word scanner and macro processor interpret them properly. Quoting Micro Facility
The SAS language uses matched pairs of quotes to distinguish character constants from names. The quotes are not stored as part of the token they define. data one; var='TEXT';  run; VAR is stored as a four-byte variable with the value  TEXT .   If  TEXT  were not enclosed in quotes, it would be treated as  a variable name . Quoting Micro Facility
proc print; title &quot;Joan’s Report&quot;; run; The title text is  Joan’s Report  and does not contain the  outer matched quotes . The outer quotes are double quotes to prevent  ambiguity  with respect to the  unmatched single quote  (apostrophe) within the text. Quoting Micro Facility
Suppose you want to store one or more SAS statements in a macro variable. options symbolgen; %let prog=data new; x=1; run; &prog proc print; run; Quoting Micro Facility
How do you explain the processing reported in this SAS log? Quoting Micro Facility
In the previous example, SAS interpreted the first “;” as the end of the macro assignment statement. In some applications you need to  mask  the meaning of text you want to assign to a macro variable. You can use  macro quoting functions  to remove the normal syntactic meaning of tokens. Need for Macro Quoting Quoting Micro Facility
The %STR function is used to protect  (quot e) tokens so the macro processor does not interpret them as macro-level syntax. General form of the %STR function: %STR ( argumen t) argument can be any combination of text and macro triggers. Quoting Micro Facility
removes the normal meaning of a semicolon and other special tokens that appear as constant text. Other special tokens include: The %STR function +  -  *  /  ,  <  >  =  blank LT  EQ  GT  AND  OR  NOT  LE  GE  NE continued... The %STR Function Quoting Micro Facility
allows macro triggers to work normally preserves leading and trailing blanks in its argument. The %STR function also Note: The %NRSTR function performs the same  quoting function as %STR, except it also quotes macro triggers (& and %). The %STR Function Quoting Micro Facility
There are a number of ways that text can be quoted. Method One: Quote all text. %let prog=%str(data new; x=1; run;); The %STR Function Quoting Micro Facility
Method Two: Quote only the semicolons. %let prog=data new%str(;) x=1%str(;)run%str(;); The %STR Function Quoting Micro Facility
Method Three: Create a macro variable with a quoted value. %let s=%str(;); %let prog=data new&s x=1&s run&s; The %STR Function Quoting Micro Facility
Example: Use the %STR function to store one or more SAS statements as the value of the macro variable PROG. Display the value of PROG through the SYMBOLGEN system option using a %PUT statement. The %STR Function Quoting Micro Facility
The %STR Function Quoting Micro Facility
options symbolgen; %let text=Joan’s Report; proc print data=perm.courses; where days >3; title &quot;&text&quot;; run; Example: Suppose you want to assign text containing an apostrophe to a macro variable. The %STR Function Quoting Micro Facility
Partial SAS Log The %STR Function Quoting Micro Facility
The word scanner interprets the apostrophe as the beginning of a literal defined by a pair of single quotes. The %STR function can also be used to quote tokens that normally occur in pairs: ’  &quot;  )  ( The %STR Function Quoting Micro Facility
To perform this quoting, you  must precede  any of the above tokens  with a percent sign  within the %STR function argument. %let text=%str(Joan % ’s Report); %let text=Joan%str( % ’)s Report; The value of TEXT is  Joan’s Report  in both cases. The %STR Function Quoting Micro Facility
options symbolgen; %let text=%str(Joan%’s Report); proc print data=perm.courses; where days >3; title &quot;&text&quot;; run; %put The value of TEXT is: &text; Example: Use the %STR function to assign text containing an apostrophe to a macro variable. The %STR Function Quoting Micro Facility
Partial SAS Log The %STR Function Quoting Micro Facility
You were earlier introduced to the %SYSFUNC macro function and used it to include a date in a title.  For example, title &quot;Report Produced on sysfunc(today(),mmddyy10.)&quot;; results in the title Report Produced on 06/12/2000 for a report run on June 12, 2000. Quoting Micro Facility
If you wanted to use a different format, the results may  not  be what you expect. For example, title &quot;Report Produced on %sysfunc(today(),worddate.)&quot;; results in the title: Report Produced on  June 12, 2000 Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
The extra blanks are from the default length of  worddate .  You need to left-justify the resulting formatted date. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
You cannot nest functions within %SYSFUNC, but you can use a %SYSFUNC for each function needed.  Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
However, the code title “Report Produced on %sysfunc(left(%sysfunc(today(),worddate.))))”; results in the following error message: ERROR:The function LEFT referenced by the %SYSFUN or %QSYSFUNC macro function has too many arguments. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
The LEFT function expects only  one  argument.  However, you are passing it &quot;June 12, 2000&quot;.  It is interpreting the comma as the delimiter between  two  arguments. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
You can mask the comma by using the  %QSYSFUNC  function instead: title &quot;Report Produced on %sysfunc(left(%qsysfunc(today(),worddate.))))&quot;; The title is now: Report Produced on June 12, 2000 Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
 

More Related Content

PPT
SAS Macros part 1
PPT
SAS Macros
PDF
Sas cheat
PDF
SAS cheat sheet
PDF
Introduction to SAS
PPTX
SAS Macro
PPT
Base SAS Statistics Procedures
PPT
SAS Functions
SAS Macros part 1
SAS Macros
Sas cheat
SAS cheat sheet
Introduction to SAS
SAS Macro
Base SAS Statistics Procedures
SAS Functions

What's hot (20)

PDF
SAS EG大數據資料庫分析 訓練課程
PPT
Arrays in SAS
DOCX
Sas practice programs
PDF
PPTX
Understanding sas data step processing.
PPT
Utility Procedures in SAS
PPT
SAS BASICS
PPTX
Sas Functions INDEX / INDEXC / INDEXW
PPT
SAS Access / SAS Connect
PPTX
Presentation on CDISC- SDTM guidelines.
DOCX
SAS Programming Notes
PPT
Finding everything about findings about (fa)
DOCX
Learn SAS Programming
PPTX
SAS basics Step by step learning
PPTX
SAS Clinical Online Training
PDF
How to create SDTM DM.xpt using Python v1.1
DOCX
Base sas interview questions
PDF
Introduction To Sas
PPT
Sas Plots Graphs
PDF
Proc report
SAS EG大數據資料庫分析 訓練課程
Arrays in SAS
Sas practice programs
Understanding sas data step processing.
Utility Procedures in SAS
SAS BASICS
Sas Functions INDEX / INDEXC / INDEXW
SAS Access / SAS Connect
Presentation on CDISC- SDTM guidelines.
SAS Programming Notes
Finding everything about findings about (fa)
Learn SAS Programming
SAS basics Step by step learning
SAS Clinical Online Training
How to create SDTM DM.xpt using Python v1.1
Base sas interview questions
Introduction To Sas
Sas Plots Graphs
Proc report
Ad

Similar to SAS Macros part 2 (20)

PPT
Sas macros part 4.1
PPT
SAS Macros part 3
PPTX
BAS 150 Lesson 8 Lecture
PPTX
Combres
PPT
When best to use the %let statement, the symput routine, or the into clause t...
PDF
224-2009
PPT
Prog1 chap1 and chap 2
PPTX
Meta data for Switch Abstraction library
PDF
Task Perform addition subtraction division and multiplic.pdf
PPT
SAS Macros part 4.1
PDF
handout6.pdf
PPT
Basics Of SAS Programming Language
ODP
PDF
SAS_and_R.pdf
ODP
TXT
Oracle sql tuning
PPT
Vpd Virtual Private Database By Saurabh
PPT
JDBC Java Database Connectivity
PPTX
01 surya bpc_script_ppt
PDF
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Sas macros part 4.1
SAS Macros part 3
BAS 150 Lesson 8 Lecture
Combres
When best to use the %let statement, the symput routine, or the into clause t...
224-2009
Prog1 chap1 and chap 2
Meta data for Switch Abstraction library
Task Perform addition subtraction division and multiplic.pdf
SAS Macros part 4.1
handout6.pdf
Basics Of SAS Programming Language
SAS_and_R.pdf
Oracle sql tuning
Vpd Virtual Private Database By Saurabh
JDBC Java Database Connectivity
01 surya bpc_script_ppt
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Ad

Recently uploaded (20)

PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation theory and applications.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Empathic Computing: Creating Shared Understanding
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Network Security Unit 5.pdf for BCA BBA.
Encapsulation_ Review paper, used for researhc scholars
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Approach and Philosophy of On baking technology
Encapsulation theory and applications.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Diabetes mellitus diagnosis method based random forest with bat algorithm
Per capita expenditure prediction using model stacking based on satellite ima...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
MYSQL Presentation for SQL database connectivity
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Understanding_Digital_Forensics_Presentation.pptx
Big Data Technologies - Introduction.pptx
Review of recent advances in non-invasive hemoglobin estimation
Empathic Computing: Creating Shared Understanding
The Rise and Fall of 3GPP – Time for a Sabbatical?
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

SAS Macros part 2

  • 2. Chapter 2. Using Macro Variable Venkata Maguluri
  • 3. Section 2.1 Basic Concepts Basic Concepts
  • 4. Objectives Learn where macro variables are stored. Substitute the value of a macro variable anywhere in a program. Monitor the value that is substituted when a macro variable is referenced. Display macro variable values and text in the SAS log. Basic Concepts
  • 5. Global Macro Variables Whenever the SAS System is invoked, a global symbol table is created and initialized with automatic or system-defined macro variables. You can also create user-defined global macro variables with the %LET statement: %let city=Dallas; %let date=05JAN2000; %let amount=975; Automatic Variables Global Symbol Table . . . . SYSTIME 09:47 SYSVER 8.01 . . . . CITY Dallas DATE 05JAN2000 AMOUNT 975 User-defined Variables Basic Concepts
  • 6. Referencing a Macro Variable To substitute the value of a macro variable in your program, you must reference it. A macro variable reference is made by preceding the macro variable name with an ampersand (&) causes the macro processor to search for the named variable and return its value if the variable exists. Basic Concepts
  • 7. Referencing a Macro Variable Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975 Example: Use a macro variable reference to make a substitution in a SAS program statement. where fee>&amount; generates WHERE FEE>975; Basic Concepts
  • 8. Referencing a Macro Variable The word scanner continues to tokenize literals enclosed in double quotes, permitting macro variables to resolve. where cityst CONTAINS &quot;&city&quot;; generates WHERE CITYST CONTAINS &quot;Dallas&quot;; If you need to reference a macro variable within a literal, enclose the literal in double quotes. The word scanner does not tokenize literals enclosed in single quotes, so macro variables do not resolve. where cityst contains '&city'; generates WHERE CITYST CONTAINS '&city'; Basic Concepts Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975
  • 9. Referencing a Macro Variable Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975 Referencing a nonexistent macro variable results in a warning message. title &quot;Students from &cityst&quot;; generates WARNING: Apparent symbolic reference CITYST not resolved. When the macro processor cannot act upon a macro variable reference, a message is printed in the SAS log. Basic Concepts
  • 10. Referencing a Macro Variable Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975 Referencing an invalid macro variable name results in an error message. title &quot;Students from &the_city_in_which_the_student_is_located&quot;; generates ERROR: Symbolic variable name THE_CITY_IN_WHICH_THE_STUDENT_IS_LOCATED must be 32 or fewer characters long. Basic Concepts
  • 11. Displaying Macro Variable Values Use the SYMBOLGEN system option to monitor the value that is substituted for a macro variable referenced. General form of the SYMBOLGEN system option: OPTIONS SYMBOLGEN; This system option displays the results of resolving macro variable references in the SAS log. Note: The default option setting is NOSYMBOLGEN . Basic Concepts
  • 12. Displaying Macro Variable Values Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975 Partial SAS Log where fee>&amount; SYMBOLGEN: Macro variable AMOUNT resolves to 975 where city_state contains &quot;&city&quot;; SYMBOLGEN: Macro variable CITY resolves to Dallas where city_state contains ’&city’; Why is no message displayed for the final example? Basic Concepts
  • 13. Displaying Macro Variable Values To verify the values of macro variables, you may want to write your own messages to the SAS log. The %PUT statement writes text to the SAS log. General form of the %PUT statement: %PUT text ; Basic Concepts
  • 14. writes to the SAS log only always writes to a new log line starting in column one writes a blank line if text is not specified does not require quotes around tex t The %PUT statement continued... Displaying Macro Variable Values Basic Concepts
  • 15. resolves macro triggers in text before text is written removes leading and trailing blanks from text unless a macro quoting function is used wraps lines when the length of text is greater than the current line size setting can be used inside or outside a macro definition. Displaying Macro Variable Values Basic Concepts
  • 16. Example: Write a message to the SAS log to verify the value of the macro variable CITY. Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975 Partial SAS Log %put The value of the macro variable CITY is: &city; The value of the macro variable CITY is: Dallas Displaying Macro Variable Values Basic Concepts
  • 17. Section 2.2 Automatic Macro Variables
  • 18. Objectives Identify selected automatic macro variables. Display values of automatic macro variables in the SAS log. Automatic Micro Variables
  • 19. System-Defined Automatic Macro Variables are created at SAS invocation are global (always available) are usually assigned values by SAS can be assigned values by the user in some cases. These variables Automatic Micro Variables
  • 20. Some automatic macro variables have fixed values that are set at SAS invocation: Name Value SYSDATE date of SAS invocation (DATE7.) SYSDATE9 date of SAS invocation (DATE9.) SYSDAY day of the week of SAS invocation SYSTIME time of SAS invocation SYSENV FORE (interactive execution) BACK (noninteractive or batch execution) SYSSCP abbreviation for the operating system used such as OpenVMS, WIN, HP 300 SYSVER release of SAS software being used SYSJOBID identifier of current SAS session or batch job mainframe systems:the userid or job name other systems: the process ID (PID). System-Defined Automatic Macro Variables Automatic Micro Variables
  • 21. Some automatic macro variables have values that automatically change based on submitted SAS statements: System-Defined Automatic Macro Variables Automatic Micro Variables Name Value SYSLAST name of most recently created SAS data set in the form libref.nam e. If no data set has been created, the value is _NULL_. SYSPARM text specified at program invocation.
  • 22. Example: Substitute system information in footnotes for a report. footnote1 &quot;Created &systime &sysday, &sysdate9&quot;; footnote2 &quot;on the &sysscp system using Release &sysver&quot;; title &quot;REVENUES FOR DALLAS TRAINING CENTER&quot;; proc tabulate data=perm.all(keep=location course_title fee); where upcase(location)=&quot;DALLAS&quot;; class course_title; var fee; table course_title=&quot; &quot; all=&quot;TOTALS&quot;, fee=&quot; &quot;*(n*f=3. sum*f=dollar10.) / rts=30 box=&quot;COURSE&quot;; run; System-Defined Automatic Macro Variables Automatic Micro Variables
  • 23. System-Defined Automatic Macro Variables Automatic Micro Variables
  • 24. The values of automatic macro variables can be displayed in the SAS log by specifying the _AUTOMATIC_ argument in the %PUT statement. %put _automatic_; System-Defined Automatic Macro Variables Automatic Micro Variables
  • 25. Partial SAS Log The values of the macro variables SYSDATE, SYSDATE9, and SYSTIME are character strings , not SAS date or time values. System-Defined Automatic Macro Variables Automatic Micro Variables
  • 26. Applications for Automatic Variables SYSDATE Check the current date to execute programs or on certain days of the month. Substitute SYSDATE9 the value in a TITLE statement. SYSDAY Check the value to run a given job on a certain day of the week. SYSENV Check the execution mode before submitting code that requires interactive(foreground) processing. Possible applications for automatic macro variables: Automatic Micro Variables
  • 27. Applications for Automatic Variables SYSVER Check for the release of SAS software being used before executing a job with newer features. SYSJOBID Check who is currently executing the job to restrict certain processing or issue commands specific to a user . SYSERR Check the return code from a SAS procedure or DATA step and abort the job if the return code is nonzero. SYSRC Check the return code of any system command before continuing with the job. Automatic Micro Variables
  • 28. The SYSPARM Macro Variable (Self-Study) OS/390 // EXEC SAS,OPTIONS='SYSPARM=SEATTLE' BATCH //SYSIN DD DSN= program-name,DISP=SHR TSO sas input(''' program-name''') opt('sysparm=SEATTLE') CMS sas program-name (sysparm=SEATTLE) OpenVMS sas/sysparm=SEATTLE program-name Windows sas program-name -sysparm SEATTLE UNIX Using the SYSPARM= system option to supply a value for the SYSPARM macro variable at SAS invocation. To assign the value SEATTLE to the SYSPARM macro variable, specify the SYSPARM= system option: Automatic Micro Variables
  • 29. title &quot;REVENUES FOR &sysparm TRAINING CENTER&quot;; proc tabulate data=perm.all(keep=location course_title fee); where upcase(location)=&quot;&sysparm&quot;; class course_title; var fee; table course_title=’ ’ all=’TOTALS’, fee=’ ’*(n*f=3. sum*f=dollar10.) / rts=30 box=’COURSE’; run; Example: Use one program to create a revenue report for any training center. Supply the name of the center at SAS invocation. The SYSPARM Macro Variable (Self-Study) Automatic Micro Variables
  • 30. Output for SYSPARM Value of SEATTLE The SYSPARM Macro Variable (Self-Study) Automatic Micro Variables
  • 31. Section 2.3 User-Defined Macro Variables
  • 32. Objectives Create your own macro variables. Display values of user-defined macro variables in the SAS log. User-Defined Micro Variables
  • 33. The %LET Statement The %LET statement enables you to define a macro variable and assign it a value. General form of the %LET statement: %LET variable = value ; User-Defined Micro Variables
  • 34. Rules for the %LET statement: variable can be any name following the SAS naming convention. if variable already exists in the symbol table, value replaces the current value. if either variable or value contains a macro trigger, the trigger is evaluated before the assignment is made. continued... The %LET Statement User-Defined Micro Variables
  • 35. Rules for the %LET statement: value can be any string: - maximum length is 32K characters - minimum length is 0 characters (null valu e) - numeric tokens are stored as character strings - mathematical expressions are not evaluated - the case of value is preserved - quotes bounding literals are stored as part of value - leading and trailing blanks are removed from value before the assignment is made. The %LET Statement User-Defined Micro Variables
  • 36. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; Value ... The %LET Statement Examples User-Defined Micro Variables
  • 37. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; Value Ed Norton The %LET Statement Examples User-Defined Micro Variables
  • 38. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 39. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 40. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 41. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” 0 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 42. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” 0 3+4 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 43. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 44. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 varlist ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 45. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 varlist name age height ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 46. Example: Assign the value DALLAS to the macro variable SITE. Use the macro variable to control program output. %let site=DALLAS; title &quot;REVENUES FOR &site TRAINING CENTER&quot;; proc tabulate data=perm.all(keep=location course_title fee); where upcase(location)=&quot;&site&quot;; class course_title; var fee; table course_title=’ ’ all=’TOTALS’, fee=’ ’*(n*f=3. sum*f=dollar10.) / rts=30 box=’COURSE’; run; The %LET Statement Examples User-Defined Micro Variables
  • 47. PROC TABULATE Output The %LET Statement Examples User-Defined Micro Variables
  • 48. Displaying User-defined Macro Variables The values of user-defined macro variables can be displayed in the SAS log by specifying the _USER_ argument in the %PUT statement. %let city=Dallas; %let date=22MAY95; %let amount=795; %put _user_; continued... User-Defined Micro Variables
  • 49. Note: The statement %put _all_; displays both automatic and user-defined macro variables. Partial SAS Log Displaying User-defined Macro Variables User-Defined Micro Variables
  • 50. Tips on Writing Macro-based Programs write and debug the desired SAS program without any macro coding make sure the SAS program runs with hard-coded programming constants on a fixed set of data generalize the program by removing hard-coded programming constants and substituting macro variable references initialize the macro variables with %LET statements and try different values for the macro variables use the SYMBOLGEN system option to assist in debugging or confirmation. If you use a macro to generate SAS code, User-Defined Micro Variables
  • 52. Objectives Use macro functions to manipulate character strings and other operations. Using Micro Functions
  • 53. Many macro applications require character string manipulation. Selected macro character functions: %UPCASE translates letters from lowercase to uppercase. %SUBSTR produces a substring of a character string. %SCAN extracts a word from a character string. %LENGTH determines the length of a character string. Using Micro Functions
  • 54. Macro functions have the same basic syntax as the corresponding DATA step functions and yield similar results. Manipulating Character Strings Using Micro Functions
  • 55. Most comparison operators in the SAS language are case sensitive. Example: Create a summary of total fees outstanding for each course. %let paidval=n; proc means data=perm.all sum maxdec=0; where paid=&quot;&paidval&quot;; var fee; class course_title; title &quot;Outstanding Fees for Each Course&quot;; run; Using Micro Functions
  • 56. Because the value of the macro variable PAIDVAL was specified in lowercase , the WHERE expression finds no matching observations. All the values of the data set variable PAID are in uppercase . Partial Log Case of Text Issues Using Micro Functions
  • 57. You can use the %UPCASE function to translate the value of a macro variable to uppercase before substituting its value in a SAS program. General form of the %UPCASE function: % UPCASE ( argumen t) Case of Text Issues Using Micro Functions
  • 58. Example: For each course, create a summary of total fees outstanding and account for case. %let paidval=n; proc means data=perm.all sum maxdec=0; where upcase(paid)=”%upcase(&paidval)&quot;; var fee; class course_title; title &quot;Outstanding Fees for Each Course&quot;; run; Case of Text Issues Using Micro Functions
  • 59. Case of Text Issues Using Micro Functions
  • 60. Extracting Parts of Strings requires the first two arguments. The third argument is optional. returns the portion of argument beginning at position for a length of n characters. The %SUBSTR function General form of the %SUBSTR function: %SUBSTR ( argumen t, position < ,n >) continued… Using Micro Functions
  • 61. returns the portion of argument beginning at position to the end of argument when an n value is not supplied. produces a warning and reads from position to the end of argumen t, if a n n value is supplied that extends beyond the bounds of argumen t. Extracting Parts of Strings Using Micro Functions
  • 62. constant text macro variable references macro functions macro calls. You can specify argumen t, positio n, and n values using General form of the %SUBSTR function: %SUBSTR ( argumen t, position < ,n >) It is not necessary to place argument in quotes because it is always handled as a character string by the %SUBSTR function. Extracting Parts of Strings Using Micro Functions
  • 63. Example: Print all courses held since the start of the current month. Use the %SUBSTR function and SYSDATE9 macro variable to determine the month and year. proc print data=perm.schedule; where begin_date between &quot;01%substr(&sysdate9,3)&quot;d and &quot;&sysdate9&quot;d; title &quot;All Courses Held So Far This Month&quot;; title2 &quot;(as of &sysdate9)&quot;; run; Extracting Parts of Strings Using Micro Functions
  • 64. Extracting Parts of Strings Using Micro Functions
  • 65. You can assign several words to a macro variable’s value and extract them with the %SCAN function. General form of the %SCAN function: %SCAN ( argument , n < , delimiter s>) Extracting Parts of Strings Using Micro Functions
  • 66. requires the first two arguments . returns the nth word of argumen t , where words are strings of characters separated by delimiters. Consecutive delimiters are treated as one delimiter. uses a default set of delimiters if none are specified. returns a null string if there are fewer than n w ords in argumen t. The %SCAN function Extracting Parts of Strings Using Micro Functions
  • 67. constant text macro variable references macro functions macro calls. %SCAN ( argument , n < , delimiter s>) You can specify values for argument , n , and delimiters using The value of n can also be an arithmetic expression that yields an integer . Extracting Parts of Strings Using Micro Functions
  • 68. Example: Use PROC DATASETS to investigate the structure of the last data set created. data work.thisyear; set perm.schedule; where year(begin_date) = year(“sysdate9”d); run; %let libref=%scan(&syslast,1); %let dsname=%scan(&syslast,2,.); proc datasets lib=&libref nolist; title &quot;Contents of the Data Set &syslast&quot;; contents data=&dsname; run; quit; Extracting Parts of Strings Using Micro Functions
  • 69. Partial Output Extracting Parts of Strings Using Micro Functions
  • 70. By using the automatic macro variables SYSDATE9 and SYSTIME you can include the date and time in a title: title &quot;Report Produced on &sysdate9.&quot;; title2 &quot;at &systime.&quot;; generates Using Micro Functions
  • 71. SYSDATE9 represents the date that the SAS session started and SYSTIME represents the time the SAS session started . If you started your interactive SAS session at 10:30 PM yesterday, what date and time would be in your report? What if you wanted to see the date or time in some other format besides DATE9.? Other SAS Functions Using Micro Functions
  • 72. You can utilize the %SYSFUNC macro function to execute SAS functions. Example: The following code was submitted on Friday, June 9, 2000: title &quot;%sysfunc(today(),weekdate.) - SALES REPORT&quot;; The title on the next report would be Friday, June 9, 2000 – SALES REPORT Other SAS Functions Using Micro Functions
  • 73. General form of the %SYSFUNC function: %SYSFUNC (function(argument(s)) <,format>) The first argument is required . The second argument is optional . function(argument(s)) is the name of one of most SAS functions and the corresponding arguments. Other SAS Functions Using Micro Functions
  • 74. All SAS functions can be used with %SYSFUNC except: DIF DIM HBOUND IORCMSG INPUT LAG LBOUND MISSING PUT RESOLVE SYMGET All Variable Information Functions Other SAS Functions Using Micro Functions
  • 75. Combining Macro Variable References with Text
  • 76. Objectives Place a macro variable reference adjacent to text or another macro variable reference. Combining Micro Variable references with Text
  • 77. You can reference macro variables anywhere in your program. Some applications may require placing a macro variable reference adjacent to leading and/or trailing text tex t &variable &variable text tex t &variable text or referencing adjacent macro variables &variable &variable in order to build a new token. Combining Macro Variable references with Text
  • 78. You can place text immediately before a macro variable reference to build a new token. Example: Data sets are stored in a SAS data library with this naming convention: Y yymon yy can be 90 , 91 , 92 , 93 , 94 , and so on. mon can be JAN , FEB , MAR , and so on. Write a program that uses a macro variable to build the month portion of the SAS data set name. Combining Macro Variable references with Text
  • 79. %let month=jan; proc chart data=perm.y90 &month ; hbar week / sumvar=sale; run; proc plot data=perm.y90 &month ; plot sale*day; run; PROC CHART DATA=PERM.Y90 JAN ; HBAR WEEK / SUMVAR=SALE; RUN; PROC PLOT DATA=PERM.Y90 JAN ; PLOT SALE*DAY; RUN; generates Combining Macro Variables with Text Combining Micro Variable references with Text
  • 80. You can reference macro variables that have no blanks between them to build new tokens. Example: Modify the previous program to allow both the month and the year to be substituted. %let year=90 ; %let month=jan; proc chart data=perm.y &year &month; hbar week / sumvar=sale; run; proc plot data=perm.y &year &month; plot sale*day; run; Combining Macro Variables with Text Combining Micro Variable references with Text
  • 81. PROC CHART DATA=PERM.Y 90 JAN; HBAR WEEK / SUMVAR=SALE; RUN; PROC PLOT DATA=PERM.Y 90 JAN; PLOT SALE*DAY; RUN; The generated program is identical to the program in the previous example. Combining Macro Variables with Text Combining Micro Variable references with Text
  • 82. You can place text immediately after a macro variable reference if it does not change the macro variable name. Example: Modify the previous program to substitute the name of an analysis variable. %let year=90; %let month=jan; %let var=sale; proc chart data=perm.y&year&month; hbar week / sumvar =&var ; run; proc plot data=perm.y&year&month; plot &var *day; run; Combining Macro Variables with Text Combining Micro Variable references with Text
  • 83. PROC CHART DATA=PERM.Y90JAN; HBAR WEEK / SUMVAR= SALE ; RUN; PROC PLOT DATA=PERM.Y90JAN; PLOT SALE *DAY; RUN; The generated program is identical to the program in the previous example. Combining Macro Variables with Text Combining Micro Variable references with Text
  • 84. Example: Modify the previous program to allow a base SAS or SAS/GRAPH procedure. /* GRAPHICS should be null or G */ %let graphics=g ; %let year=90; %let month=jan; %let var=sale; proc &graphicschart data=perm.y&year&month; hbar week / sumvar=&var; run; proc &graphicsplot data=perm.y&year&month; plot &var*day; run; What is wrong with this program? Combining Macro Variables with Text Combining Micro Variable references with Text
  • 85. SAS interprets the macro variable’s name to be GRAPHICSCHART because there is no delimiter between the macro reference and the rest of the text. Partial Log Combining Macro Variables with Text Combining Micro Variable references with Text
  • 86. Macro Variable Name Delimiter The word scanner recognizes the end of a macro variable name when it encounters a character that cannot be part of the name token. A period ( .) is a special character that is treated as part of the macro variable reference and does not appear when the macro variable is resolved. Combining Micro Variable references with Text
  • 87. Example: Correct the resolution problem in the previous example. %let graphics=g; %let year=90; %let month=jan; %let var=sale; proc &graphics. chart data=perm.y&year&month; hbar week / sumvar=&var; run; proc &graphics. plot data=perm.y&year&month; plot &var*day; run; Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 88. word scanner treats &graphics. as the reference value of the macro variable GRAPHICS is returned to the input stack word scanner processes gchart as one token. If these SAS statements are executed, the PROC GCHART DATA=PERM.Y90JAN; HBAR WEEK / SUMVAR=SALE; RUN; PROC GPLOT DATA=PERM.Y90JAN; PLOT SALE*DAY; RUN; The SAS compiler receives Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 89. Example: Modify the previous program to include a macro variable used to define the libref. %let lib=perm; %let graphics=g; %let year=90; %let month=jan; %let var=sale; libname &lib ’SAS-data-library’; proc &graphics.chart data =&lib. y&year&month; hbar week / sumvar=&var; run; proc &graphics.plot data =&lib. y&year&month; plot &var*day; run; What is the problem this time? Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 90. The statements %let lib=perm; ... libname &lib 'SAS-data-library'; proc &graphics.chart data= &lib .y &year&month ; ... proc &graphics.plot data =&lib .y &year&month ; LIBNAME PERM 'SAS-data-library'; PROC GCHART DATA= PERM Y 90JAN ; HBAR WEEK / SUMVAR=SALE; RUN; PROC GPLOT DATA= PERM Y 90JAN ; PLOT SALE*DAY; RUN; send these statements to the SAS compiler: The period after &lib is interpreted as a delimiter. Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 91. Use another period after the delimiter period to supply the needed token. %let lib=perm; ... libname &lib 'SAS-data-library'; proc &graphics.chart data= &lib ..y &year&month ; ... proc &graphics.plot data =&lib ..y &year&month ; Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 92. proc &graphics.chart data= &lib ..y &year&month ; ... PROC GCHART DATA= PERM .Y 90JAN ; ... The first period is treated as a macro variable name delimiter. The second period is simply text. The compiler receives delimiter text Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 93. Quoting in the Macro Facility
  • 94. Objectives Describe when macro quoting functions are needed. Protect tokens so the word scanner and macro processor interpret them properly. Quoting Micro Facility
  • 95. The SAS language uses matched pairs of quotes to distinguish character constants from names. The quotes are not stored as part of the token they define. data one; var='TEXT'; run; VAR is stored as a four-byte variable with the value TEXT . If TEXT were not enclosed in quotes, it would be treated as a variable name . Quoting Micro Facility
  • 96. proc print; title &quot;Joan’s Report&quot;; run; The title text is Joan’s Report and does not contain the outer matched quotes . The outer quotes are double quotes to prevent ambiguity with respect to the unmatched single quote (apostrophe) within the text. Quoting Micro Facility
  • 97. Suppose you want to store one or more SAS statements in a macro variable. options symbolgen; %let prog=data new; x=1; run; &prog proc print; run; Quoting Micro Facility
  • 98. How do you explain the processing reported in this SAS log? Quoting Micro Facility
  • 99. In the previous example, SAS interpreted the first “;” as the end of the macro assignment statement. In some applications you need to mask the meaning of text you want to assign to a macro variable. You can use macro quoting functions to remove the normal syntactic meaning of tokens. Need for Macro Quoting Quoting Micro Facility
  • 100. The %STR function is used to protect (quot e) tokens so the macro processor does not interpret them as macro-level syntax. General form of the %STR function: %STR ( argumen t) argument can be any combination of text and macro triggers. Quoting Micro Facility
  • 101. removes the normal meaning of a semicolon and other special tokens that appear as constant text. Other special tokens include: The %STR function + - * / , < > = blank LT EQ GT AND OR NOT LE GE NE continued... The %STR Function Quoting Micro Facility
  • 102. allows macro triggers to work normally preserves leading and trailing blanks in its argument. The %STR function also Note: The %NRSTR function performs the same quoting function as %STR, except it also quotes macro triggers (& and %). The %STR Function Quoting Micro Facility
  • 103. There are a number of ways that text can be quoted. Method One: Quote all text. %let prog=%str(data new; x=1; run;); The %STR Function Quoting Micro Facility
  • 104. Method Two: Quote only the semicolons. %let prog=data new%str(;) x=1%str(;)run%str(;); The %STR Function Quoting Micro Facility
  • 105. Method Three: Create a macro variable with a quoted value. %let s=%str(;); %let prog=data new&s x=1&s run&s; The %STR Function Quoting Micro Facility
  • 106. Example: Use the %STR function to store one or more SAS statements as the value of the macro variable PROG. Display the value of PROG through the SYMBOLGEN system option using a %PUT statement. The %STR Function Quoting Micro Facility
  • 107. The %STR Function Quoting Micro Facility
  • 108. options symbolgen; %let text=Joan’s Report; proc print data=perm.courses; where days >3; title &quot;&text&quot;; run; Example: Suppose you want to assign text containing an apostrophe to a macro variable. The %STR Function Quoting Micro Facility
  • 109. Partial SAS Log The %STR Function Quoting Micro Facility
  • 110. The word scanner interprets the apostrophe as the beginning of a literal defined by a pair of single quotes. The %STR function can also be used to quote tokens that normally occur in pairs: ’ &quot; ) ( The %STR Function Quoting Micro Facility
  • 111. To perform this quoting, you must precede any of the above tokens with a percent sign within the %STR function argument. %let text=%str(Joan % ’s Report); %let text=Joan%str( % ’)s Report; The value of TEXT is Joan’s Report in both cases. The %STR Function Quoting Micro Facility
  • 112. options symbolgen; %let text=%str(Joan%’s Report); proc print data=perm.courses; where days >3; title &quot;&text&quot;; run; %put The value of TEXT is: &text; Example: Use the %STR function to assign text containing an apostrophe to a macro variable. The %STR Function Quoting Micro Facility
  • 113. Partial SAS Log The %STR Function Quoting Micro Facility
  • 114. You were earlier introduced to the %SYSFUNC macro function and used it to include a date in a title. For example, title &quot;Report Produced on sysfunc(today(),mmddyy10.)&quot;; results in the title Report Produced on 06/12/2000 for a report run on June 12, 2000. Quoting Micro Facility
  • 115. If you wanted to use a different format, the results may not be what you expect. For example, title &quot;Report Produced on %sysfunc(today(),worddate.)&quot;; results in the title: Report Produced on June 12, 2000 Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 116. The extra blanks are from the default length of worddate . You need to left-justify the resulting formatted date. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 117. You cannot nest functions within %SYSFUNC, but you can use a %SYSFUNC for each function needed. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 118. However, the code title “Report Produced on %sysfunc(left(%sysfunc(today(),worddate.))))”; results in the following error message: ERROR:The function LEFT referenced by the %SYSFUN or %QSYSFUNC macro function has too many arguments. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 119. The LEFT function expects only one argument. However, you are passing it &quot;June 12, 2000&quot;. It is interpreting the comma as the delimiter between two arguments. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 120. You can mask the comma by using the %QSYSFUNC function instead: title &quot;Report Produced on %sysfunc(left(%qsysfunc(today(),worddate.))))&quot;; The title is now: Report Produced on June 12, 2000 Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 121.