SAS宏入门
- 格式:ppt
- 大小:386.50 KB
- 文档页数:68
第10章SAS宏功能10.1 概述SAS系统的MACRO处理器可以让程序更简洁更明了及更容易维护,帮助用户在使用SAS系统时更方便更自动化,具体来说,它具有以下功能:1.获取SAS的系统信息;2.有条件地执行数据步和过程步;3.开发交互式系统;4.在不同的数据步和过程步之间传递数据;5.重复执行SAS代码等等。
.SAS宏语言的管理1.MACRO变量2.MACRO程序语句3.MACRO表达式和函数10.2 SAS宏变量的使用与定义宏变量(有时也称符号变量)属于SAS宏语言的范畴,和数据步中的变量的概念是不一样的。
除了数据行外,你可以在SAS程序的任何地方定义和使用宏变量。
数据步变量是和数据集相联系的,而宏变量是独立于数据集的。
数据集变量的值取决于正在处理的观测,而一个宏变量的值总是不变,直到被明确改变。
宏变量类似于一般变量的命名方法。
程序中以&宏名来引用MACRO变量(有时为了清晰起见,也可以通过&宏名. 来引用MACRO变量)SAS宏变量共有两种:1.系统宏变量2.用户自定义的宏变量。
10.2.1 系统宏变量 一些系统宏变量01 /* Program_10-l-l.sas */02 DA TA _NULL_;03 PUT 'SYSDATE=' "&SYSDA TE"; /* 执行时的日期 */04 PUT 'SYSDAY='"&SYSDAY"; /* 执行时是星期几 */05 PUT 'SYSENV='"&SYSENV"; /* 交互模式或批次模式 */06 PUT 'SYSSCP='"&SYSSCP"; /* 返回正在用的操作系统 */07 PUT 'SYSJOBID = '"&SYSJOBID"; /* 程序的操作执行代码 */08 PUT 'SYSERR='"&SYSERR"; /* 程序执行的错误码 */ 09 PUT 'SYSRC='"&SYSRC";/*程序执行的回复码 */ 10 PUT 'SYSLIBRC='"&SYSLIBRC"; /* 使用LIBNAME 时设置是否正确 */11 PUT 'SYSFILRC='"&SYSFILRC"; /*使用FILENAME 时设置是否正确*/12 RUN;使用宏语句 %put _automatic_; 可以查看所有的系统宏变量,结果显示在LOG窗口。
SAS宏语言基础薛 富 波 第四军医大学卫生统计学教研室 E-mail: xuefubo@一,SAS宏工具简介21. SAS宏工具的基本概念和功能扩展定制 SAS操作 减少文本 输入量文本操作工具SAS编程更加 灵活高效32. 两个新的工作对象宏:以%标识 功能较复杂 文本替换功能 宏变量:以&标识 功能较简单43. SAS宏工具的功能结构语法规则宏语言宏处理器工作单元SAS其它 功能模块54. SAS宏标识符(宏触发器)宏变量解析 宏变量引用宏调用 宏操作 宏语句 宏函数65. SAS宏运行机制文本替 换操作 宏触发 器&和%SAS程序词语扫描器不包含任 何宏代码SAS宏工具SAS编译器7二,SAS宏工具主要功能单元81. 宏变量91.1 宏变量的定义及其基本特性%let mv01=height var001; data test; 宏变量 input sex &mv01; 宏变量值 datalines; …… ; run; proc print data=test; var &mv01; run;是由SAS名字标识的字符串. 取值类型及变量长度. 宏变量值的恒定性. 与SAS数据集变量的区别. 宏变量的应用场合.101.2 用户定义宏变量与自动宏变量%let dataset=sashelp.class; %let time=20050727; %put _user_;用户自定义宏变量%put _automatic_; title "Report produced at &sysdate9., &sysday";自动宏变量111.3 局部宏变量与全局宏变量局部宏变量. %macro test; %let localvar=12345; %put _user_; %mend; %test 全局宏变量. %let globalvar=2005; %global sasvar; %put _user_;局部宏变量 局部符号表全局宏变量全局符号表121.4 宏变量的使用%let var=weight; 宏变量引用 %let data=sashelp.class; 字符常量中引 proc print data=&data; 用宏变量,须 var &var; 使用双引号 title "Contents of dataset &data for variable &var"; run; %let i=10; 字符与宏变量 %let j=5; 使用分隔符连接 可直接连接 %let t1=text in line&j; 字符与宏变量. %let t2=text in line&j.page&i.underscored; %let lib=sashelp; 宏变量引用后圆点符号的使用 %let data=&lib..class;131.5 宏变量的间接引用%macro test; 创建一系列宏变 data _null_; 量,lev1, lev2, … set sashelp.class end=last; call symput(("lev"||compress(_n_)),age); if last then call symput("levn",compress(_n_)); 存储上述宏变量 run; 总个数的宏变量 %do i=1 %to &levn; 宏变量间接引用 %put lev&i=&&lev&i; %end; 在各级别的宏变量名称 %mend test; 前添加2的k-1次方个&14宏变量间接引用的工作机制文本字符串 文本替换 宏处理器 &字符扫描&&lev&i&lev114151.6 应用宏函数处理宏变量值%let a=weight/height/sex; %let b=%scan(&a,2,/); %let c=%substr(&a,8,6); %let i=9; %let j=%eval(&i*2+1); %let k=%scan(&a,1,/)is%eval(&i*7-3)kg;宏函数可与字 符混合使用, 也可同时使用 多个函数,且 其前后顺序可 任意排列162 宏的定义与调用172.1 宏的概念与功能宏调用 宏:已编译程序段 特定代码文本可接受宏参数可执行逻辑控制 等各项操作功能182.2 宏的定义与调用以%macro语句为开始 宏 的 定 义%macro mtest(times); %do i=1 %to × %put putting process is performed for &i times; %end; %mend mtest;以%mend语句为结尾宏 调 用%mtest(10)192.3 宏参数位置参数当前宏的局 部宏变量 带默认值的关键字%macro paratest(pos1,pos2,key1=default1,key2=default2); %put the first positional parameter is &pos1; %put the second positional parameter is &pos2; %put the first keyword is &key1; %put the second keyword is &key2; %mend paratest; /*仅有两个位置参数,关键字将取默认值*/ %paratest(para1,para2) /*位置参数变换位置,关键字取给定值*/ %paratest(para2,para1,key1=keyword1,key2=keyword2) /*关键字变换位置,不影响输出结果*/ %paratest(para1,para2,key2=keyword2,key1=keyword1)20。
很全的sas基础知识(一)5.1SAS表达式简介1.SAS常数表达式(1)数值常数如: 1.23、-5、0.5E-10。
(2)字符常数如: name1='TOME'、name2='MARY'、name3='JOHN'。
(3)日期(d)、时间(t)、日时(dt)常数如: d1='01JAN80'd、t1='9:25:19't、dt1='18JAN80:9:27:05'dt。
(4)16进制常数(略)2.SAS运算符(1)前缀算符与后缀算符前缀算符, 即正号或负号; 如: +Y; -25; -COS(30); +(X*Y); 后缀算符,即两个运算对象之间的运算符号, 如: 1+9; 4-2; 6<8。
(2)只含一个运算符的简单表达式(Ⅰ组)和含有多于一个运算符的复合表达式(Ⅱ组)Ⅰ组, 如: A+B; C-D; E*F; G/H; Ⅱ组, 如: 1-EXP(N/(N-1));100-LOG(N*(N+1));(3)操作运算的顺序求一个复合表达式的值时, 其操作运算的顺序和优先级遵从如下的规则(见表5.1): 表5.1SAS的运算符及其在运算顺序上的优先级━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━优先级组别运算符号等价表示运算符号含义之说明━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━第0 组()括号第 1 组**+-乘方, 正数, 负数^><<>NOT MIN MAX逻辑非, 最小, 最大第 2 组*/乘, 除第 3 组+-加, 减第 4 组‖或||字串连接第 5 组<<=LT LE小于, 小于等于=^=EQ NE等于, 不等于>=>GE GT大于等于, 大于IN等于一列元数中的某一个第 6 组&AND逻辑与第7 组|或|OR逻辑或━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━各组的计算顺序分别为: 第0组由内向外;其他各组均自左至右。
The little SAS book 学习笔记第七章使用SAS宏功能灵活写代码7.1 宏概述宏以前被认为是经验老道的SAS程序员使用的高级技术。
但现在新手也能够了解一些。
幸运的是,宏的基本功能不是那么难理解。
本章介绍的最普遍使用的SAS宏语言的特征。
宏处理器标准SAS程序中,提交程序后,SAS就编译并立即执行。
但宏语句多了一步,在提交之后,SAS会将宏语句传送到宏处理器上,将其转变为SAS标准代码,通常叫做“变换代码”(meta-programming.)宏和宏变量SAS宏代码包括两个基本部分:宏命令和宏变量。
宏变量通常加一个“&”作为前缀,而宏命令通常加一个“%”作为前缀。
局部VS全局宏变量有局部宏变量和全局宏变量。
如果在宏的内部定义则为局部宏变量,只能在内部使用。
如果在开放代码中定义则为全局宏变量。
避免两种错误:在宏之外(开放代码)使用局部变量;创建同名的局部变量和全局变量。
启动宏处理器使用宏指令之前必须将宏系统选项打开,尽管有时默认是打开的。
可以用下面代码查看是否打开:PROC OPTIONS OPTION=MACRO; RUN;查看日志,如果看到MACRO,则打开了;如果看到NOMACRO,则没有打开。
避免宏错误宏会让人很头痛,可以通过分段形式避免。
首先,用SAS标准语言写下程序;接着,将其转变为宏代码。
7.2 用宏变量提交文本用%let创建一个宏变量最简单给宏变量分配一个值的方法是%let,基本形式为:%LET macro-variable-name=value;宏变量名必须符合SAS命名法则,(少于等于32字节、以字母或下划线开头、只能包括字母、数字和下划线),下面创建了宏变量:%LET iterations=10;%LET country=New Zealand;当赋值字符串时,不需要加引号。
除非在开头和结尾有空格,否则从等号到分号的全部内容都是变量值。
使用宏变量宏变量前面要加前缀&,注意宏处理器找不到单引号内的宏变量,只能用双引号。
第10章SAS宏功能10.1 概述SAS系统的MACRO处理器可以让程序更简洁更明了及更容易维护,帮助用户在使用SAS系统时更方便更自动化,具体来说,它具有以下功能:1.获取SAS的系统信息;2.有条件地执行数据步和过程步;3.开发交互式系统;4.在不同的数据步和过程步之间传递数据;5.重复执行SAS代码等等。
.SAS宏语言的管理1.MACRO变量2.MACRO程序语句3.MACRO表达式和函数10.2 SAS宏变量的使用与定义宏变量(有时也称符号变量)属于SAS宏语言的范畴,和数据步中的变量的概念是不一样的。
除了数据行外,你可以在SAS程序的任何地方定义和使用宏变量。
数据步变量是和数据集相联系的,而宏变量是独立于数据集的。
数据集变量的值取决于正在处理的观测,而一个宏变量的值总是不变,直到被明确改变。
宏变量类似于一般变量的命名方法。
程序中以&宏名来引用MACRO变量(有时为了清晰起见,也可以通过&宏名. 来引用MACRO变量)SAS宏变量共有两种:1.系统宏变量2.用户自定义的宏变量。
10.2.1 系统宏变量 一些系统宏变量01 /* Program_10-l-l.sas */02 DA TA _NULL_;03 PUT 'SYSDATE=' "&SYSDA TE"; /* 执行时的日期 */04 PUT 'SYSDAY='"&SYSDAY"; /* 执行时是星期几 */05 PUT 'SYSENV='"&SYSENV"; /* 交互模式或批次模式 */06 PUT 'SYSSCP='"&SYSSCP"; /* 返回正在用的操作系统 */07 PUT 'SYSJOBID = '"&SYSJOBID"; /* 程序的操作执行代码 */08 PUT 'SYSERR='"&SYSERR"; /* 程序执行的错误码 */ 09 PUT 'SYSRC='"&SYSRC";/*程序执行的回复码 */ 10 PUT 'SYSLIBRC='"&SYSLIBRC"; /* 使用LIBNAME 时设置是否正确 */11 PUT 'SYSFILRC='"&SYSFILRC"; /*使用FILENAME 时设置是否正确*/12 RUN;使用宏语句 %put _automatic_; 可以查看所有的系统宏变量,结果显示在LOG窗口。
SAS宏:9步法SAS宏主要包括两部分:宏变量和宏函数通过使用SAS宏,可以更加容易维护SAS代码,是程序更加灵活,动态执行。
一般来说,通过写宏函数执行代码需要9个步骤第1步:写好程序,并且确保程序能够正确运行proc means data=expenses mean;var RoomRate;run;proc print data=expenses;title 'Lowest Priced Hotels in theEXPENSES Data Set';footnote 'On June 1, 2003';var ResortName RoomRate Food;where RoomRate<=221.109;run;宏功能使程序每次能够自动根据数据集的变化进行改变第2 步:使用宏变量帮助文本替换宏变量提供文本替换,这样可以使用简单的单词或者词组,不需要大段的代码。
宏变量包括:自动宏变量,用户自定义宏变量%let,在数据步或者sql过程步使用的用户自定义宏变量call symput。
不管是如何创建宏变量,在程序中引用宏变量通过&。
options symbolgen;%let dsn=expenses;%let varlist=ResortName RoomRate Food;proc means data=&dsn mean;var RoomRate;run;%let average=221.109;proc print data=&dsn;title "Lowest Priced Hotels in the &dsnData Set";footnote "On &sysdate9";var &varlist;where RoomRate<=&average;run;SYMBOLGEN在日志窗口中记录宏变量是如何解析的。
SAS讲义-第十一课宏语言SAS宏的功能:将一个变量,一段程序或者一个文本命名,供以后调用,是用于扩充和制做用户化SAS系统的工具;利用宏功能用户可以减少在完成一些共同任务时必须输入的文本量。
简单地说,就是把重复性的工作模块化!一、宏变量宏变量的定义方法是:%let 宏变量名=宏变量值;宏变量的引用方法是:&来引用。
例1 %let x=30;data a;m=&x;run;当SAS程序提交后,在编译阶段,系统对程序逐词扫描过程中,凡遇到%或&开始的词,就启动宏语言处理器对此进行处理。
例2 data score;input math@@;cards;71 81 91;run;%let exa=score;data temp;set &exa;if math>80;run;二、宏程序宏程序简称宏,是一个被存储的文本,最终都会被编译并执行。
但是宏不是一个简单的文本,它可以通过控制和循环语句来控制文本的输出。
另外,宏还包含参数,通过调用不同的参数值可以多次重复使用宏,从而简化程序的开发工作。
一个宏程序最终被系统的编译器执行,中间需要经过三个步骤:1)定义宏:创建一段程序文本。
2)编译宏:运行这段文本;运行的结果将存储到SAS宏目录。
该阶段系统只编译不解析。
3)调用宏:从宏目录中调用一个宏名字。
系统解析宏程序,将解析结果传至编译器,执行具体的程序语句。
1、宏定义的格式:%macro test;Data a;X=1;Run;%mend test;在格式中,%macro是定义宏的关键字,test是宏的名字,%mend是宏定义结束的标志。
夹在%macro和%mend的文本是宏的主体信息,该例子实际上定义了一个名为test的宏,主体信息是一个data步。
2、调用宏的格式如果调用上例的宏,即为:%test;3、宏内宏一个宏内可以再嵌套一个宏。
例3%macro test;Data a;X=1;Run;%mend test; /*定义了一个名为test的宏*/%macro prt;Proc print data=sashelp.class;run;%mend prt; /*定义了一个名为prt的宏*/%macro nest;%test;%prt;%mend nest; /*定义了一个名为nest的宏,其主体是调用另外两个宏*/%nest; /*调用名为nest的宏*/三、宏参数从上面看似乎宏只是一些文本的堆彻,其实不是,宏参数将发挥重要的作用。
SAS编程技术教程SAS(Statistical Analysis System)是一种流行的数据分析工具和编程语言,广泛应用于统计学、商业和医学等领域。
SAS提供了许多强大的功能和技术,帮助用户进行数据处理、数据分析和报表生成等工作。
本教程将介绍一些常用的SAS编程技术,帮助读者快速掌握SAS的使用方法。
1.SAS语言基础SAS语言基础是学习SAS编程的基础。
了解SAS语言的语法和规则非常重要。
SAS语言的基本结构包括数据步(data step)和过程步(procedure step)。
数据步用于数据导入、转换和保存,过程步用于数据分析和报表生成。
学习SAS语言的关键是熟悉SAS语句的使用方法,如DATA语句、SET语句、IF语句等。
2.数据处理技术数据处理是SAS编程的一项核心任务。
SAS提供了丰富的数据处理功能,如数据导入、数据清洗、数据转换和数据合并等。
学习SAS的数据处理技术对于处理大量数据非常有用。
例如,使用INPUT语句将外部文件导入SAS数据集,使用FORMAT语句设置数据格式,使用RENAME语句修改变量名等。
3.数据分析技术数据分析是SAS编程的另一个重要任务。
SAS提供了许多数据分析技术,如描述性统计、回归分析、聚类分析和时间序列分析等。
学习SAS的数据分析技术对于理解数据和发现数据中的规律非常有用。
例如,使用PROCMEANS进行描述性统计分析,使用PROCREG进行线性回归分析,使用PROCCLUSTER进行聚类分析等。
4.报表生成技术报表生成是SAS编程的另一个重要任务。
SAS提供了强大的报表生成功能,可以生成各种类型的报表,如表格、图表和交互式报表等。
学习SAS的报表生成技术对于将分析结果呈现给他人非常有用。
例如,使用PROCREPORT生成表格报表,使用PROCGCHART生成图表报表,使用PROCTABULATE生成交互式报表等。
5.宏编程技术宏编程是SAS编程的高级技术。
SAS Macros WorkshopI.Why use SAS Macros?A SAS macro is way of defining parts of or collections of SAS statements which can be carried out repeatedly or which can substitute names of datasets or variables with symbolic names. SAS macro language also gives you the opportunity to insert programming steps inside a SAS code.SAS Macro Advantages:▪Reduce coding time▪Reduce programming errors by not having to edit so many lines of code ▪In some cases, it could be even more time efficient in executionSAS Macro Disadvantages:▪Harder to understand if multiple people work on it▪Harder to debug▪Some of the macro features (call symput) do not resolve in execution in the log file until the very end of a data step▪Not easily adaptableAll the usual programming elements: if-then-else statements, loops for I=1 to N do, and other similar operators can be used in SAS macros.II.Overview of elements of the macro languageThe three different main elements of the macro language are:▪macro variables;▪macro program statements;▪macro functions.III.Macro variablesMacro variables are tools that enable you to modify text in a SAS program through a symbolic substitution. It assigns a value (either string or integer) to a variable that you can invoke several times in a program after that.To define a macro variable you can use the %let statement.EXAMPLE 1:For example to assign the value 24 to the variable named sto, you do:%let sto=24;SYNTAX:%<Name of MACRO Variable> = Macro variable value;The variable sto will take this value every time it gets invoked until anothermacro variable statement changes it. This code can be placed anywhere in theprogram except within data lines.To invoke a macro variable place a & before its name. The macro processorresolves this reference to the variable by replacing &sto by the value of sto.%let sto=year;proc means data=&sto;So, for example,%let sto=1;Proc means data = temp&sto;Run;Will realy resolve toProc means data = temp1;Run;EXAMPLE 2:Macro variables that contain entire sections of a SAS program can also be created (with the use of the str macro function):%let sto2=%str(proc means data=year;var rainfall;run;);Will resolve to the proc means step running every time the sto2 macro variable is invoked.IV.Macro program statementsA macro program is a text identified by a name. These lines of codes can be invoked several times by using this name. So, in its most simple form, a macro program isequivalent to a macro variable. However, unlike a macro variable, a macro program can include more complex functionalities, such as if-then loops, etc.The next example is one of a simple macro that could also be defined by a macro variable:EXAMPLE 3 (Simple macro template)%macro example;proc means data=year;var rainfall;%mend example;The definition of a macro must begin by a %macro statement followed by thename of the macro. Here, our macro has been named example. The statementmust end by a %mend statement. When it is invoked, the macro processor willrun the lines of text between the %macro and %mend statements.To invoke a macro program, place a % sign before its name. The macroexample will be invoked in the following way:%example;This line of text can be included at any time in the program. For example:EXAMPLE 4:Proc plot data=year;plot rainfall*temperature;%example;Proc print data=year;The processor will execute the following lines:Proc plot data=year;plot rainfall*temperature;Proc means data=year;var rainfall;Proc print data=year;MACROS WITHIN MACROSMacro variables can be invoked inside a macro program. In fact, a macro program can even be invoked inside another macro program:EXAMPLE 5:%let var1=rainfall;%let var2=temperature;%macro design;proc plot data=result;plot &var1*&var2;%mend design;%macro compile;data result;set year;keep &var1 &var2;%design;%mend compile;If elsewhere in the program, compile is invoked by the statement %compile, theprocessor will replace these lines by:data result;set year;keep rainfall temperature;proc plot data=result;plot rainfall*temperature;MACRO WITH PARAMETERSThere is an easier solution than invoking macro variables inside the definition of a macro program: you can use parameters in the definition of your macro.This is perhaps the most widely used form of the macro features.For example, to redefine the macro design with parameters, type the followinglines:EXAMPLE 6:%macro design1(para1,para2);proc plot data=year;plot ¶1*¶2;%mend design1;To invoke it, we will type: %design1(rainfall,temperature);This gives the parameter para1 the value rainfall and para2 the valuetemperature (the processor assigns the values to the parameters in the orderentered). The result of this line of code will be equivalent to the %design usedpreviously, without having to define the macro variables var1 and var2. MACROS WITHIN DATA STEPS%DO StatementIf you want to perform procedures on a range of consecutive integer values for acertain variable or a set of variables, you can use a do loop. The followingexample introduces the use of do-loops with a macro.EXAMPLE 7:%macro year;%do i=75 %to 99;proc means data=year&i;var rainfall;%end;%mend year;A %do statement will always be terminated by a %end statement. The counter isthen referenced by a &i inside the macro.%IF %THEN %DO STATEMENTThis tool is used to insert conditional statements in a macro program. To illustrate this new tool, an extension of the previous example is used.Suppose that it is necessary to obtain the average rainfall for every year, but thatyou need graphs only for the years after 1990, then type the following macro:EXAMPLE 8:%macro analyze;%do i=75 %to 99;proc means data=year&i;var rainfall;%if i>=90 %then %do;proc plot data= year&i;plot rainfall*temperature;%end;%end;%mend analyze;%do %while and %do %until statements exist.LOOPS ON SERIES OF MACRO VARIABLESSuppose a series of macro variables m1, m2, m3…m25 has already been defined.If they represent the rainfall predictions produced by a model, it is interesting to compute the difference between the real value and the prediction. This can bedone using a loop on these macro variables:EXAMPLE 9:%do j=1 %to 25;data compare&j;set year&j;dif=rainfall-&&m&j;%end;You can see that this can be done by placing two & before the name of themacro variable.The processor resolves it in the following way:If for example j=3, it replaces first &&m&j by &m3, and then scans it again to replace &m3 by the value it has been previously assigned.V.Macro functionsMacro functions process macro expressions, called arguments, to produce a new expression. While DATA step functions are applied to values on a vector of variables, macro functions are used to create, modify, and work with text strings. Initially this may seem like a minor difference, but because macro functions deal with text, they can be used to build SAS code. This becomes the powerful advantage of the macro language. Macro functions can be divided into three categories:▪character functions;▪evaluation functions;▪quoting functions.MACRO CHARACTER FUNCTIONSThis type of macro function provides information about the string it takes asargument (see following example: the %length function). For a more extensivelist and more detailed information, see the ‘SAS Guide to Macro Processing’ (on the shelf in my cubicle).Some of the macro character functions that have analogous DATA step functions include:An important distinction between the use of macro functions and data stepequivalents is:▪DATA step functions work on character strings, numeric values, and DATA step variable values.▪Macro functions are applied to text strings that NEVER contain the values of DATA step variables.Several of these functions have two forms, with and without a Q at the start of the function name. Functions with names that start with Q (quoting) remove the meaning from special characters including the ampersand (&), percent sign (%), and mnemonic operators in returned values.%LENGTHThe %length function returns the length of the string it takes as an argument.In the following example the objective is to determine if the length of a variablename is smaller or longer than 8 characters (some softwares don’t accept variable names longer than 8, so it can be necessary to change the names before exporting the data set) and replace the variable by the same one but with a new name.EXAMPLE 10:%macro export (name,newname);%if %length(&name)>8 %then %do;data year;set year;&newname=&name;drop &name;%end;%mend limit;%INDEXSYNTAX%INDEX(argument1,argument2)The %INDEX function searches the first argument (ARGUMENT1) for the firstoccurrence of the text string which is contained in the second argument(ARGUMENT2). If the target string is found, the position of its first character isreturned as the function’s response (0 if not found).EXAMPLE 11This example stores three words in the macro variable &X. The %INDEXfunction is then used to search in &X for the string TALL and the result is then displayed using the %PUT statement.%LET X=LONG TALL SALLY;%LET Y=%INDEX(&X,TALL);%PUT TALL CAN BE FOUND AT POSITION &Y;Notice that the TALL as the second argument is not in quotes. The %PUTresults in the following text being written to the LOG:TALL CAN BE FOUND AT POSITION 6%LENGTHThe %LENGTH function determines the length (number of characters) of it’sargument. The number of detected characters is then returned. When the argument is a null string the value of 0 is returned.SYNTAX%LENGTH (argument)EXAMPLE 12In the macro %LOOK the name of the incoming data set is checked to see if itexceeds 8 characters.%MACRO LOOK(dsn,obs); %put &wscan &wqscan;%if %length(&dsn) gt 8 %then%put Name is too long - &dsn;%else %do;PROC CONTENTS DATA=&dsn;TITLE "DATA SET &dsn";RUN;PROC PRINT DATA=&dsn (OBS=&obs);TITLE2 "FIRST &obs OBSERVATIONS";RUN;%end;%MEND LOOK;The LOG shows that the following data set nameexceeds 8 characters:53 %look(demographics, 5)Name is too long - demographics%SCAN and %QSCANSYNTAX%SCAN(argument1,argument2[,delimiters])%QSCAN(argument1,argument2[,delimiters])The %SCAN and %QSCAN functions both search a text string (ARGUMENT1) for the n th word (ARGUMENT2) and returns its value. If ARGUMENT3 is nototherwise specified the same word delimiters are used as in the DATA stepSCAN function. For an ASCII system these include the following (for EBCDICthe ¬ is substituted for the ^):blank . < ( + | & ! $ * ) ; ^ - / , % > \%QSCAN removes the significance of all special characters in the returned value.EXAMPLE 13The macro variable &X below can be broken up using the %SCAN function.%LET X=XYZ.ABC/XYY;%LET WORD=%SCAN(&X,3);%LET PART=%SCAN(&X,1,Z);%PUT WORD IS &WORD AND PART IS &PART;The %PUT returns the following:WORD IS XYY AND PART IS XYNotice that the word delimiter (third argument) is not enclosed in quotes as itwould be in the DATA step SCAN function.The %QSCAN function is needed when you want to return a value that contains an ampersand or percent sign. This is demonstrated below:%let dsn = clinics;%let string =%nrstr(*&stuff*&dsn*&morestuff);%put &wscan &wqscan;The %PUT writes:clinics &dsnBoth functions return the value &DSN, but since the meaning of the & is notmasked by %SCAN, the &DSN in &WSCAN is resolved to clinics.EXAMPLE 14%macro a;aaaaaa%mend a;%macro b;bbbbbb%mend b;%macro c;cccccc%mend c;%let x=%nrstr(%a*%b*%c);%put X: &x;%put The third word in X, with SCAN: %scan(&x,3,*);%put The third word in X, with QSCAN: %qscan(&x,3,*);The %PUT statement writes this line:X: %a*%b*%cThe third word in X, with SCAN: ccccccThe third word in X, with QSCAN: %c%SUBSTR and %QSUBSTRLike the DATA step SUBSTR function these macro functions return a portion of the string in the first ARGUMENT. The substring starts at the POSITION in the second argument and optionally has a LENGTH of the third argument.SYNTAX%SUBSTR (argument,position[,length])%QSUBSTR (argument,position[,length])As is the case with most other macro functions, each of the three arguments can be a text string, macro variable, expression, or a macro call. If a value forLENGTH is not specified, a string containing the characters from POSITION to the end of the argument is produced.EXAMPLE 14%LET CLINIC=BETHESDA;%IF %SUBSTR(&CLINIC,5,4) = ESDA %THEN%PUT *** MATCH ***;%ELSE %PUT *** NOMATCH ***;The LOG would contain *** MATCH *** since &CLINIC has the value ESDA in characters 5 through 8.As is shown in the following example, the %QSUBSTR function allows you toreturn unresolved references to macros and macro variables.EXAMPLE 15%let dsn = clinics;%let string =%nrstr(*&stuff*&dsn*&morestuff);%let sub = %substr(&string,9,5);%let qsub = %qsubstr(&string,9,5);%put &sub &qsub;The %PUT will write clinics* &dsn* in the LOG.%UPCASEThe %UPCASE macro function converts all characters in the ARGUMENT toupper case. This function is especially useful when comparing text strings thatmay have inconsistent case.Syntax%UPCASE(argument)EXAMPLE 16The following code allows the user to differentially include a KEEP= option in the PROC PRINT statement.The %UPCASE function is used to control for variations in the text that issupplied by the user in the macro call.%macro printit(dsn);* use a KEEP for CLINICS;%if %upcase(&dsn)=CLINICS %then%let keep=(keep=lname fname ssn);%else %let keep=;proc print data=&dsn &keep;title "Listing of %upcase(&dsn)";run;%mend printit;%printit(cLinICs)The macro call to %PRINTIT produces the followingcode.proc print data=cLinICs (keep=lname fnamessn);title "Listing of CLINICS";run;MACRO EVALUATION FUNCTIONSThe macro evaluation functions evaluate arithmetic and logical expressions in the macro language. They only perform integer arithmetic.The evaluation functions are the▪%eval and▪%sysevalf%EVALIn the following example, we assume that a certain procedure produces an integer stored in the macro variable base (for example, a prediction of the number ofyears required for a specific analysis). If 3 is added to this integer, we couldobtain the year up to which proc means have to be run so as to remove thepossible estimation errors in the parameter base.EXAMPLE 17:%macro add(base);%let result=%eval(&base+3);%do i=75 %to &result;proc means data=year&i;var rainfall;%end;%mend add;We see that once the macro expression is evaluated, the result can be stored inanother macro and you can use it immediately.Logical expression can also be evaluated:EXAMPLE 18:%macro biggest(a,b);%let logic=%eval(&a>&b);%mend biggest;%SYSEVALFYou can use this function to perform non-integer arithmetic and the function will even return a non-integer result from an arithmetic operation.SYNTAX%SYSEVALF(expression[,conversion-type])The EXPRESSION is any arithmetic or logical expression which is to beevaluated and it may contain macro references.The second argument, CONVERSION-TYPE, is an optional conversion to apply to the value returned by %SYSEVALF. Since this function can return non-integer values, problems could occur in other macro statements that use this function but expect integers.When you need the result of this function to be an integer, use one of theCONVERSION-TYPEs. A specification of the CONVERSION-TYPE converts a value returned by %SYSEVALF to an integer or Boolean value so it can be used in other expressions that require a value of that type. CONVERSION-TYPE canbe:▪BOOLEAN 0 if the result of the expression is 0 or missing, 1 if the result is any other value.▪CEIL round to next largest whole integer▪FLOOR round to next smallest whole integer▪INTEGER truncate decimal fractionThe CEIL, FLOOR, and INTEGER conversion types act on the expression in the same way as the DATA step functions of the same (or similar) names i.e. CEIL,FLOOR, and INT.EXAMPLE 19The following table shows a few calls to %SYSEVALF and the resulting values:MACRO QUOTING FUNCTIONSQuoting functions allow the user to pass macro arguments while selectivelyremoving the special meaning from characters such as &, %, ;, ‘, and “. Most ofthese functions are not commonly used and are even less commonly understood.Although they are powerful and can even be necessary, programming solutionsare usually available that do not require the use of the quoting functions.All quoting functions are not alike. Consult the documentation to get the gorydetails, however the following three functions should solve most of your quotingproblems.%STRThe most commonly used macro quoting function is %STR. Often it is used along with the %LET statement to mask semicolons that would otherwise terminate the %LET.In the following example we want to create a macro variable &P that contains two SAS statements;%LET P=PROC PRINT DATA=DSN; RUN;Because the semicolon following DSN terminates the %LET statement, the macro variable &P contains PROC PRINT DATA=DSN which will almost certainlyresult in a syntax error due to the missing semicolon.The %STR function masks the semicolon by quoting it.%LET P=%STR(PROC PRINT DATA=DSN; RUN;);This results in the macro variable &P being correctly assigned the two statements.PROC PRINT DATA=DSN; RUN;%BQUOTEThe %BQUOTE function is probably the best choice as an overall quotingfunction. It eliminates many of the limitations of the %STR function, and it willalso remove the meaning from unmatched symbols that are normally found inpairs such as quotes and parentheses. The following %LET will cause all sorts of problems because the apostrophe will be interpreted as an unmatched quote.Example 20:%let a = Sue's new truck;The %STR function will not help because %STR does not mask quote marks,however %BQUOTE does.%let a = %bquote(Sue's new truck);%put &a;This will correctly resolve to assigning “Sue’s new truck” to the macro variablea.%UNQUOTEOnce a quoting function has been used, the text remains quoted. Since these"quotes" are hard to see, even in the LOG, this can cause problems for theprogrammer that does not anticipate that quoting functions may have been used.If you need to remove or change the effects of any of the other quotingfunctions, the %UNQUOTE is used.Three macro variables are defined below, but the second, &OTH, is defined using the %NRSTR function.This means that &CITY can not be resolved when &OTH is resolved. When the%UNQUOTE function is applied to &OTH its value (&CITY) is seen as a macro variable which is also resolved.Example 21:%let city = miami;%let oth = %nrstr(&city);%let unq = %unquote(&oth);%put &city &oth &unq;The LOG shows:miami &city miamiAlthough &OTH looks like any other macro variable in the %PUT statement, itwill not be fully resolved because it is quoted, thus preventing &CITY from being resolved.ING DATA STEP FUNCTIONS IN THE MACRO LANGUAGETwo macro tools allow the user to execute virtually all of the functions androutines available in the DATA step as part of the macro language. The%SYSCALL macro statement calls DATA step routines and the %SYSFUNCmacro function executes DATA step functions.SYNTAX%SYSFUNC(function-name(functionarguments)[,format])%QSYSFUNC(function-name(functionarguments)[,format])EXAMPLE 22The following example shows three ways to add the current date to a TITLE.The automatic macro variable &SYSDATE is easy to use but cannot beformatted.Prior to Release 6.12 most users created a DATA _NULL_ step with anassignment statement and a CALL SYMPUT to create a formatted macrovariable. The DATA step can now be avoided by using the %SYSFUNC macro function.data _null_;today = put(date(),worddate18.);call symput('dtnull',today);run;title1 "Automatic Macro Variable SYSDATE&sysdate";title2 "From a DATA _NULL_ &dtnull";title3 "Using SYSFUNC%sysfunc(date(),worddate18.)";The following three titles are produced:Automatic Macro Variable SYSDATE 10APR00From a DATA _NULL_ April 10, 2000Using SYSFUNC April 10, 2000The leading spaces before the date in the second two titles is caused by the date string being right justified. The LEFT and TRIM functions can be used to remove the space, however care must be exercised or a couple of problems can beencountered.The first is that function calls cannot be nested within a %SYSFUNC. Fortunately this is rather easily handled because %SYSFUNC requests can be nested.Secondly the resolved values of interior calls to %SYSFUNC are used asarguments to the outer calls. When the resolved value contains special characters (especially commas), they can be misinterpreted. The following revised TITLE3 will not work because the interior %SYSFUNC uses a formatted value whichcontains a comma.EXAMPLE 23:title3 "Using SYSFUNC%sysfunc(left(%sysfunc(date(),worddate18.)))";After the inner %SYSFUNC is executed the result is:title3 "Using SYSFUNC %sysfunc(left(April 10, 2000))";Because of the comma, the LEFT function will see two arguments (it isexpecting exactly one), and the message 'too many arguments' is generated.The %QSYSFUNC function can be used to mask special characters in the text string that is passed to the next function. Rewriting the TITLE statement using %QSYSFUNC as is shown below eliminates the problem with the comma.title3 "Using SYSFUNC%sysfunc(left(%qsysfunc(date(),worddate18.)))";TITLE3 from above becomes:Using SYSFUNC April 10, 2000VII.AUTOCALL MACROS THAT MIMIC FUNCTIONS The AUTOCALL facility allows the user to call macros that have been definedoutside of the execution of the current program. A number of these macros areprovided with the base macro language and are described in the Macro Language Elements section of the SAS® Macro Language: Reference, First Editionreference manual. Although these are, strictly speaking, macros, they act likefunctions.Commonly used Autocall macros include:%CMPRES%LEFT%LOWCASE%TRIM%VERIFY%LEFTThis macro can be used to left justify a macro argument.In the earlier example for %QSYSFUNC the DATA stepLEFT function was used, this title can be furthersimplified by using %LEFT.EXAMPLE 25:title3 "Using SYSFUNC%left(%qsysfunc(date(),worddate18.))";%VERIFYWhile %INDEX and its variations search for specific strings, %VERIFYdetermines the position of the first character that is NOT in a text string.The following example subsets a string starting at the first character that is not a number.EXAMPLE 26:%let code = 2000SUGI25;%let part =%substr(&code,%verify(&code,1234567890));&PART will contain:SUGI25%CMPRESThe %CMPRES macro removes multiple blanks (as well as leading andtrailing blanks) from a text string. This macro is similar to the COMPBLDATA step function. In the following example a numeric value is placedinto a macro variable using the SYMPUT routine. In the conversionprocess a series of leading blanks are added to &FIVE.EXAMPLE 27:data _null_;x=5;call symput('five',x);run;%put *&five*;%let five = *%cmpres(&five)*;%put &five;The resulting LOG shows:138139 %put *&five*;* 5*140 %let five = *%cmpres(&five)*;141 %put &five;*5*VIII.FROM DATA STEPS TO A MACRO VARIABLE: CALL SYMPUTCALL SYMPUT is a SAS language routine that assigns a value produced in a DATA step to a macro variable. It is one of the DATA step interface tools that provides a dynamic link for communication between the SAS language and the macro facility.SyntaxCALL SYMPUT(argument-1,argument-2);argument-1: specifies a character expression that identifies the macrovariable that is assigned a value. If the macro variable does not exist,the routine creates it.argument-2: specifies a character expression that contains the valuethat is assigned.Call symput takes a value from a data step and assigns it to a macro variable.You can then use this macro variable in later steps.EXAMPLE 28:If AGE >=21 THEN CALL SYMPUT (“status”, “adult”);Else call symput (“status”, “minor”);These statements create a macro variable named &status and assign it a value of either Adult or Minor depending on the variable age.EXAMPLE 29:When performing logistic regression, we often need to create dummyvariables based on all possible values of another variable. For instance,we want to create dummy variables for the variable CON which has over400 different integer values from 1 to 506. Basically we need to do thefollowing:IF CON = 1 THEN CON1 = 1; ELSE CON1 = 0;IF CON = 2 THEN CON2 = 1; ELSE CON2 = 0;. . . . . .IF CON = 506 THEN CON506 = 1; ELSE CON506 = 0;It is not practical to write this many statements. Our goal is to use the SYMPUT routine to obtain this code automatically.In the following program, a sample data set TESTDATA with 12 observations and 1 variable is first created in step (1). Then in step (2), a data set UNIQUE is created containing 8 unique CON values. In step (3), the SYMPUT routine assigns the largest value of CON to the macro variable N. CALL SYMPUT is executed once when the DATA step reaches the end of the data set. In step (4), the macro variable N’s value is retrieved and CALL SYMPUT is executed 506 times to create 506 macro variables M1-M506 with the initial value 0. The PUT function is used to eliminate a note that numeric values have been converted to character values. The LEFT function is used to left-align the value of the index variable, I, to avoid creating macro variable names with blanks. In step (5), CALL SYMPUT is executed 8 times and the values of the 8 macro variables created in step (4) are updated with the values of the corresponding CON. The 498 macro variables without the corresponding CON values will remain the initial value 0. Step (6) is a macro that generates all dummy variables for all possible values of CON. By using the %GOTO statement and statement label, the dummy variables without the corresponding CON values will not be created. Note that the double ampersand is necessary to cause the macro processor to scan the text twice first to generate the reference and then to resolve it. Step (7) invokes the macro GETCON to create the dummy variables for every observation in the data set TESTDATA. The last step prints the output data set with dummy variables shown in Table 1./* (1) Create a sample data set TESTDATA. */DATA TESTDATA;INPUT CON;CARDS;1734115714873450657743。