12. SAS宏简介
第10章 SAS宏功能
第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窗口。
第51章 SAS宏简介
%宏名称(参数值 1,参数值 2,…) 每个参数值将代入宏定义中相应位置的参数。
带参数的宏可以把宏变量和宏结合在一起,成为宏功能编程的强有力的方法。如:
%hb(outp1,e11);
%mean(data=zu4,var=stand,label=身高,title=4 组 1 个变量-身高,pair=Y,ci=y,cn=y);
%put &&city&n SAS 解析上述语句时,把&&解析成&,而把 city 作为文本,把&n 解析成 6,这样就返 回了一个宏变量引用&city6,最后%put 语句显示出宏变量 city6 的值。 例SASTJFX51_1.SAS:
%let city1=shanghai;%let city2=beijing; %macro listthem;
文本; %END; 例 SASTJFX51_4.SAS:
%macro aa; %let i=1; %do %while(&i.<=10); %put &i.; %let i=&i.+1; %end;
%mend aa; %aa;
提交这段 SAS 程序后,在 SAS 的 Log 窗口显示如下结果:
在%DO %UNTIL 循环中先提交文本进行处理,然后对表达式赋值,当表达式成立时就 停止重复提交文本。
3. 宏循环语句的进一步讨论 类似于数据步带条件的循环语句 DO WHILE 和 DO UNTIL,宏程序中也有功能类似的 %DO %WHILE 和%DO %UNTIL。它们的一般形式为: %DO %WHILE(表达式);
文本; %END; 例如: 在%DO %WHILE 循环开始对表达式赋值,当表达式成立时就重复提交文本进行处理。 %DO %UNTIL(表达式);
第10章SAS宏功能解析
第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编程技术教程 (12)
宏调用宏:
%macro analyze(dat, year, pr,price,year1); %create; /*产生数据集TEMP*/ %plot; /*作图*/ %mend analyze; 运行宏:
%analyze(stk000002, 2000, 收盘价 ,clpr,2000); run;
例14.14 通过给宏参数赋值来调用宏。 %plot(stk000002, 收盘价,clpr);
例中,运行时,宏处理器把第一个值(stk000002)赋 给第一个宏参数DAT,第二个值(收盘价)赋给第二 个宏变量PR,以此类推。
使用宏参数的优点:
§ 可以少写几个%let语句; § 保证该宏参数变量在宏之外的程序部分不被 引用; § 调用宏时并不需要知道这些宏参数的名字, 只要知道相应的取值。
宏参数赋值
例14.16 创建宏参数时直接赋值。 %macro plot(dat=stk000002, pr=收盘价,price=clpr); proc gplot data=ResDat.&dat; title2 "&pr 时序图"; plot &price*date=1; symbol1 v=star i=join r=1 c=red; %mend plot; %plot; run;
l 在宏的引用过程中,当词段扫描器识别一个宏变量名称时,从&开 始直到遇到一个SAS名称中不允许出现的字符为止。所以空格等一些 不允许出现在SAS名称中的字符就可以作为分隔符出现,但是为了不 显示这些分隔符,一般使用句号来作为分隔符使用。
例14.7 隔开宏变量引用和文本。
%let name=Resdat;
%do i=1 %to 3 ; %put &&data&i;/*&data&i不能用*/ %end; %mend test; %test
SAS_MACRO_简介
SAS自带的Macro变量
SYSMENV macro execution environment SYSMSG message displayed with %DISPLAY SYSPARM value passed from SYSPARM in JCL SYSPROD indicates whether a SAS product is licensed SYSPBUFF all macro parameters passed SYSRC return code from macro processor SYSSCP operating system where SAS is running SYSTIME starting time of job SYSVER SAS version Example: FOOTNOTE "THIS REPORT WAS RUN ON &SYSDAY, &SYSDATE"; Resolves to: FOOTNOTE "THIS REPORT WAS RUN ON FRIDAY, 26MAR99";
显示 Macro 变量
%PUT 在编译程序时把macro 变量显示在 log 窗口里. 语法: %PUT text macrovariables ; %PUT _all_;
举例: %PUT ***** &SYSDATE *****; Partial SAS Log: ***** 26MAR07 *****
Exercise 2 部分输出
创建和使用用户定义的macro 变量
问题: 假如在一个程序中需要多次提到一个SAS数据集合,
DATA PAYROLL; INPUT EMP$ RATE; DATALINES; TOM 10 JIM 10 ; PROC PRINT DATA=PAYROLL; TITLE "PRINT OF DATASET PAYROLL"; RUN; 如何只在一个地方改动名字,并且让数据集合名称出现在标题中? 解答: • 使用Macro变量.
SAS技巧(宏、transpose、ODS产生excel、logistic)
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 看到的语句是:
DATA MEWBOUGHT; SET SAVE.BOUGHT; more SAS statements IF NUM>1000;
RUN;
注意:宏变量引用不需要连接操作符,SAS系统会自动 构造结果字符,这与数据步不一样。
◆
有时我们要在文本中对宏变量定界, 看下面一段语句:
%let mmm=bought;
data &mmm1 &mmm2; set in&mmm.temp; run; ◆ 这时SAS并不会使用BOUGHT1和BOUGHT2两个数据 集,而且给出错误信息。这是因为SAS把MMM1和 MMM2当成了两个合法的宏变量名,而不是引用宏 变量MMM。在这种情况下,我们要使用宏变量引 用定界“.”,上面第二条语句正确的写法应该
表22.2 宏功能中的保留字
ABEND ABORT ACT ACTIVATE BQUOTE BY CLEAR CLOSE CMS COMANDR COPY DEACT DEL DELETE DISPLAY DMIDSPLY DMISPLIT DO EDIT ELSE END EVAL FILE GLOBAL GO GOTO IF INC INCLUDE INDEX INFILE INPUT KEYDEF LENGTH LET LIST LISTM LOCAL MACRO MEND METASYM NRBQUOTE NRQUOTE NRSTR ON OPEN PAUSE PUT QSCAN QSUBST QUOTE QSYSFUNC QUPCASE RESOLVE RETURN RUN SAVE SCAN STOP STR SUBSTR SUPERQ SYSCALL SYSEVALF SYSEXEC SYSFUNC SYSGET SYSRPUT THAN TO TSO UNQUOTE UNSTR UNTIL UPCASE WHILE WINDOW
SAS软件及部分常用功能简介
使用适当的颜色和字体,使图表更加美观和 专业。
动态数据可视化
交互式图表
允许用户通过点击或拖动来交互地查看数据。
时间序列动画
展示随时间变化的数据趋势。
动态更新
随着数据的改变,图表能够自动更新。
数据筛选
允许用户根据特定条件筛选数据,并实时反 映在图表上。
05
编程与自定义功能
SAS编程语言基础
SAS软件及部分常用功能简介
• SAS软件概述 • 数据导入与处理 • 统计分析功能 • 数据可视化功能 • 编程与自定义功能
01
SAS软件概述
SAS软件简介
SAS(Statistical Analysis System)软件是由美国北卡罗来纳大学于1966年开发的统计分析软件,最初 主要用于农业领域的数据分析。经过多年的发展,SAS已成为全球领先的数据分析和统计分析解决方案提 供商。
SAS软件采用模块化设计,用户可以根据需要选择不同的模块进行数据处理、统计分析、数据挖掘、 预测建模等。
SAS软件的特点与优势
强大的数据处理能力
SAS提供了丰富的数据导入、导出和转换工具,支持多种 数据格式和数据库系统,能够高效地处理大规模数据集。
灵活的数据挖掘功能
SAS的数据挖掘工具能够帮助用户发现隐藏在数据中的模 式和关联,支持多种数据挖掘算法,如决策树、神经网络 、聚类等。
饼图
用于表示各部分在整体中所占的比 例。
03
02
折线图
用于展示时间序列数据或连续变量 的变化趋势。
散点图
用于展示两个变量之间的关系。
04
图表制作与美化
选择数据
确保数据准确无误,是制作图表的基础。
sas中 macro的存储与调用
在SAS(Statistical Analysis System)中,macro是一种非常重要的功能,可以帮助用户简化重复性的工作、提高代码的重用性、减少代码的维护成本,并且能够增加代码的灵活性和可读性。
在SAS中,我们可以将编写好的macro存储起来,并在需要的时候调用它们,这为SAS编程带来了极大的便利和效率提升。
在本篇文章中,我们将深入探讨SAS中macro的存储与调用的相关内容,以及它们在实际工作中的应用价值。
通过逐步介绍,你将对这一主题有个全面、深刻和灵活的理解。
1. 存储macro:在SAS中,我们可以将编写好的macro存储起来以备后用。
存储macro有两种常见的方式:一种是将macro存储在一个独立的文件中,然后在需要的时候通过%include语句引入;另一种方式是将macro直接存储在SAS数据集中。
将macro存储在独立文件中的好处是可以方便地进行版本管理和共享,而将macro存储在数据集中则可以更好地与数据进行整合和同步。
2. 调用macro:一旦macro被存储起来,我们就可以在需要的时候调用它们。
在SAS 中,我们可以使用%macro和%mend语句来定义一个macro,并在需要的时候使用%macro_name的方式进行调用。
通过调用存储的macro,我们可以大大减少重复编写相似代码的工作量,提高代码的重用性和可维护性。
3. 应用案例:在实际工作中,存储和调用macro能够极大地提高我们的工作效率。
在数据清洗和数据分析过程中,我们经常会遇到一些重复性的操作,比如计算变量、生成报表等。
通过编写和存储相应的macro,我们可以在需要的时候轻松调用它们,从而大大减少重复编写代码的时间,提高工作效率。
4. 个人观点:对于SAS中macro的存储与调用,我个人认为是一个非常实用的功能。
通过将常用的操作存储为macro,并在需要的时候进行调用,不仅能够提高工作效率,还能够减少错误和提高代码的可读性。
sas宏(2),运行中创建宏与使用宏,多个宏触发器的引用规则、procsql创建宏,scl。。。
sas宏(2),运⾏中创建宏与使⽤宏,多个宏触发器的引⽤规则、procsql创建宏,scl。
1:在程序运⾏中进⾏宏定义CALL routines that enable you to transfer information between an executing DATA step and the macro processor.You can use the SYMPUT routine to create a macro variable and to assign to that variable any value that is available in the DATA step.When you use the SYMPUT routine to create a macro variable in a DATA step, the macro variable is not actually created and assigned a value until the DATA step is executed.options symbolgen pagesize=30;%let crsnum=3;data revenue;set sasuser.all end=final;where course_number=&crsnum;total+1;if paid='Y'then paidup+1;if final then do;if paidup<total then do;call symput('foot','Some Fees Are Unpaid'); /*symput函数能达到运⾏时给宏赋值的效果*//*%let foot=Some Fees Are Unpaid; */ /*使⽤let不能达到想要的效果,let会被宏处理器先执⾏,优先于data步*/end;else do;call symput('foot','All Students Have Paid');/*%let foot=All Students Have Paid;*/end;end;run;symput函数⾥⾯的参数为表达式的情况⾥⾯引⽤的函数不需要使⽤%这种宏函数的记号trim去右尾 left去左尾call symput('numpaid',trim(left(paidup)));CALL SYMPUTX(macro-variable, value <,symbol-table> );默认去双尾空⽩,其他效果和symput⼀样随后⼀个参数表⽰宏储存的位置'L'=local 'G'=globalThe SYMPUT routine and the SYMPUTX routine can only create a local macro variable if a local symbol table already exists. If no local symbol table exists when the SYMPUT routine or SYMPUTX routine executes, it will create a global macro variable.依据变量名建⽴宏data _null_;set sasuser.courses;call symput(course_code, trim(course_title));/*每⼀个observation中的两个变量分别对于宏值与宏变量*/run;%put _user_;多个宏触发器的扫描规则宏处理器将两个&当做⼀个看待,所以第⼀次扫描&&&lv2被处理成&(&lv2)->&lv1,第⼆次扫描就得出res,先将重复的两个变成1个,然后记住扫描的位置,继续扫⾯后⾯的。
很全的sas基础知识(二)
的是给郴等于0的其他初值(不用此语句变量的初值为0)。 11.RENAME 语句(换名语句) 格式为∶RENAME 旧变量名=新变量名……;
在 DATA 步中用此语句对正创建的数据集中的变量给出新名字。
12.WINDOW 语句(窗口语句)
格式为∶WINDOW 窗口名 [选择项] [域……] [GROUP=组[域……]]……;
值变量的长度在3到8之间。
5.LABEL 语句(标记语句) 格式为∶LABEL 变量名='标记内容,包括空格最多 40 个字符'; 如∶
LABEL compound='TYPE OF PRUG'; LABEL n='SAMPLE SIZE'; 6.ATTRIB 语句(属性语句) 格式为∶ATTRIB 变量名 [FORMAT=格式] [INFORMAT=输入格式] [LABEL='标记内容
等修改后再
提交给 SAS 系统执行,需对倒数第2行进行如下修改∶
IF x=7 THEN DM "INCLUDE 'a:d2p7.prg' "; Ⅴ.用在 PROC 步的语句
1.PROC 语句(过程语句) 格式为∶PROC 过程名 [选择项];
如∶PROC MEANS DATA=aa MAXDEC=3 MEAN;
DATA _null_;
CARDS;
INFORMAT DEFAULT=3.1;
11 22 33 44 55
INPUT x1-x5;
;
PUT x1-x5;
RUN;
这个 DATA 步提交后在 LOG 窗口输出的结果为∶1.1 2.2 3.3 4.4 5.5。
3.FORMAT 语句(格式语句)
SAS系统和数据分析SAS宏功能简介
第十八课SAS宏功能简介SAS系统提供了强大的宏功能(macro facility),通过创建宏变量和宏能方便地完成:●重复分析任务,大大精减了程序量●从系统获取一些如SAS启动时间、日期、版本号等信息●有条件地执行数据步和过程步●保持程序的独立性和移植性,产生与数据无关的程序●用宏变量在不同数据步和过程步之间传递数据一、SAS宏变量宏变量(也称符号变量)属于SAS宏语言的范畴,和数据步中的变量概念是不一样的。
除了数据行外,可以在SAS程序的任何地方定义和使用宏变量。
数据步变量是和数据集相联系的,而宏变量是独立于数据集的。
数据集变量的值取决于正在处理的观测,而一个宏变量的值总是保持不变,直到被明确改变。
1.宏变量的定义定义一个宏变量的最简单方法是使用宏语句%LET,它的一般形式如下:%LET宏变量名=值;宏变量的命名遵从一般的SAS命名规则。
宏变量的值不需要加引号,如果值加入引号,则引号被作为宏变量值的一部分。
宏变量的值可以是固定的字符串、其他宏变量的引用、宏函数和宏调用。
2.宏变量的引用为了引用一个宏变量的值,在宏变量前加上一个符号&,格式如下:&宏变量名宏变量被引用的效果就是用宏变量的内容直接替代宏变量名。
3.宏变量的使用举例例如,我们想要打印、图示和分析几个数据集,但又希望避免重复键入每一个数据集名字以修改相同的程序代码。
解决方法是用%LET语句创建一个宏变量DSNAME,该宏变量赋值了一个数据集名SURVEY。
然后,这个宏变量在PROC PRINT等许多过程和TITLE语句中被引用。
程序如下:%Let dsname=survey ;Proc print data=&dsname ;Var name sex bdate income ;Title “Display of Data Set &dsname” ;Run ;要注意标题语句Title平时既可以用单引号又可以用双引号围住标题,但如果有宏变量引用,则必须用双引号,否则用单引号将当作字符串处理。
SAS语言的宏功能
本章教学目的: 本章教学目的:
了解SAS宏的功能和特点 了解 宏的功能和特点 掌握SAS宏变量的定义与调用 掌握 宏变量的定义与调用 掌握SAS宏及宏参数的定义与调用 掌握 宏及宏参数的定义与调用 掌握SAS宏语言的流程控制结构 掌握 宏语言的流程控制结构 了解宏与数据步的信息交换子程序
注意如果宏变量dsn已经存在则其值会被替换掉 已经存在则其值会被替换掉. 注意如果宏变量 已经存在则其值会被替换掉
2.2引用宏变量 引用宏变量
宏变量定义以后,可以通过在其名称前使用 来对其引用 来对其引用。 宏变量定义以后,可以通过在其名称前使用&来对其引用。 的程序段: 例1:引用宏变量 的程序段: :引用宏变量a的程序段
5.1 宏do循环语句 循环语句
2).直到型循环 直到型循环 格式: 表达式); 格式:%Do %Until (表达式 ; 表达式 循环体; 循环体; %End; ; 3).当型循环 当型循环 格式: 表达式); 格式:%Do %While (表达式 ; 表达式 循环体; 循环体; %End; ; 注:当型循环和直到型循环需自己设置一个宏变量作为循 环变量,对循环变量累加赋值时需使用函数 函数%eval( )来计 环变量,对循环变量累加赋值时需使用函数 来计 算算术表达式的值,见程序。 算算术表达式的值,见程序。
6.宏与数据步的信息交换 宏与数据步的信息交换
SAS利用宏在不同的数据步、过程步之间传递信息。 利用宏在不同的数据步、过程步之间传递信息。 利用宏在不同的数据步 数据步的symput是一个特殊的子程序:它能利用数据步 是一个特殊的子程序: 数据步的 是一个特殊的子程序 运行中的变量值给一个宏变量赋值。 运行中的变量值给一个宏变量赋值。 Symget也用于数据步中,作用和symput相反,可以在数 也用于数据步中,作用和 相反, 也用于数据步中 相反 据步执行时得到宏变量的值。 据步执行时得到宏变量的值。 注意到这两个子程序需用call语句调用。Symget用得相对 语句调用。 注意到这两个子程序需用 语句调用 用得相对 少些,只要求理解 子程序。 少些,只要求理解symput子程序。 子程序
SAS系统和数据分析SAS宏功能简介
第十八课SAS宏功能简介SAS系统提供了强大的宏功能(macro facility),通过创建宏变量和宏能方便地完成:●重复分析任务,大大精减了程序量●从系统获取一些如SAS启动时间、日期、版本号等信息●有条件地执行数据步和过程步●保持程序的独立性和移植性,产生与数据无关的程序●用宏变量在不同数据步和过程步之间传递数据一、SAS宏变量宏变量(也称符号变量)属于SAS宏语言的范畴,和数据步中的变量概念是不一样的。
除了数据行外,可以在SAS程序的任何地方定义和使用宏变量。
数据步变量是和数据集相联系的,而宏变量是独立于数据集的。
数据集变量的值取决于正在处理的观测,而一个宏变量的值总是保持不变,直到被明确改变。
1.宏变量的定义定义一个宏变量的最简单方法是使用宏语句%LET,它的一般形式如下:%LET宏变量名=值;宏变量的命名遵从一般的SAS命名规则。
宏变量的值不需要加引号,如果值加入引号,则引号被作为宏变量值的一部分。
宏变量的值可以是固定的字符串、其他宏变量的引用、宏函数和宏调用。
2.宏变量的引用为了引用一个宏变量的值,在宏变量前加上一个符号&,格式如下:&宏变量名宏变量被引用的效果就是用宏变量的内容直接替代宏变量名。
3.宏变量的使用举例例如,我们想要打印、图示和分析几个数据集,但又希望避免重复键入每一个数据集名字以修改相同的程序代码。
解决方法是用%LET语句创建一个宏变量DSNAME,该宏变量赋值了一个数据集名SURVEY。
然后,这个宏变量在PROC PRINT等许多过程和TITLE语句中被引用。
程序如下:%Let dsname=survey ;Proc print data=&dsname ;Var name sex bdate income ;Title “Display of Data Set &dsname” ;Run ;要注意标题语句Title平时既可以用单引号又可以用双引号围住标题,但如果有宏变量引用,则必须用双引号,否则用单引号将当作字符串处理。
sas宏参数
sas宏参数SAS宏参数的使用是SAS软件中非常重要的功能之一,它可以帮助用户更加灵活地进行数据分析和处理。
在本文中,我们将从不同的角度介绍SAS宏参数的一些特点和用法,希望能够帮助读者更好地理解和应用这一功能。
我们来了解一下SAS宏参数的基本概念。
SAS宏参数是一种特殊的变量,用于在宏定义和宏调用之间传递数值或字符值。
通过使用宏参数,用户可以根据具体的需求,动态地改变宏的行为和输出结果。
SAS宏参数的定义和使用非常简单,只需要在宏定义的过程中使用%let语句对宏参数进行赋值,并在宏调用的过程中使用&符号引用宏参数即可。
在实际应用中,SAS宏参数可以用于很多方面。
首先,它可以用来控制宏的行为。
比如,在数据分析中,我们经常需要对不同的数据集进行相同的操作,只是其中的一些参数不同。
这时,我们可以定义一个宏来完成这个操作,并在宏定义的过程中使用宏参数来表示这些不同的参数。
这样,我们在每次调用宏的时候,只需要改变宏参数的值,就可以得到相应的结果。
SAS宏参数还可以用来传递数据。
在某些情况下,我们可能需要在宏调用的过程中传递一些数据给宏。
这时,我们可以使用宏参数来接收这些数据,并在宏定义的过程中进行相应的处理。
通过这种方式,我们可以在宏调用的地方直接传递数据,而不需要通过其他的方式进行数据传递。
除了上述的基本用法之外,SAS宏参数还可以与其他SAS功能结合使用,进一步发挥其作用。
比如,我们可以使用SAS宏参数来控制数据集的选择和处理,然后再将处理结果传递给其他的SAS过程进行进一步的分析。
这样,我们可以通过宏参数的灵活运用,实现复杂的数据分析和处理的自动化。
总的来说,SAS宏参数是一种非常有用的功能,它可以帮助用户更好地应对不同的数据分析和处理需求。
通过合理地使用宏参数,用户可以提高工作效率,减少重复劳动,并且能够灵活地应对各种不同的数据情况。
因此,在使用SAS软件进行数据分析和处理的过程中,我们应该充分发挥SAS宏参数的作用,提高工作效率,提升数据分析的质量。
sas_180412_哈佛的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。
SAS编程简介PPT课件
数据类型转换
使用`PROC FORMAT`过程,将数值型数 据转换为字符型数据,或将字符型数据转 换为数值型数据。
数据排序
使用`PROC SORT`过程,根据指定的列对 数据进行排序。
数据合并
使用`PROC SQL`过程,通过`UNION`语 句将两个或多个数据集合并为一个新的数 据集。
使用PROC SQL对数据集进行高级操作
THANKS
感谢您的观看
SAS程序通常由数据步和过程步组成,数据步用于读取和操作数据 ,过程步用于执行统计分析或数据挖掘任务。
SAS语法规则
SAS编程语言遵循严格的语法规则,包括变量声明、赋值、循环、 条件语句等。
SAS函数和宏
SAS提供了大量的内置函数和宏,用于执行各种数据处理和统计分 析任务。
SAS编程的应用领域
数据分析
SAS编程语法及语 句
数据步基本语法及语句
数据步定义
数据步是SAS程序中最基本的单元,用于 创建、操作和管理数据。
数据筛选和排序
在数据步中,可以对数据进行筛选和排序 ,以便后续的数据分析。
数据步语句
数据步语句包括变量声明、数据输入和转 换、数据筛选和排序等。
数据输入和转换
在数据步中,可以通过读入外部数据文件 或使用已有的数据集,进行数据转换和清 洗。
SAS编程简介PPT课 件
汇报人:
日期:
目录
CONTENTS
• SAS编程概述 • SAS编程语法及语句 • SAS编程实战案例 • SAS编程进阶内容 • SAS编程常见问题及解决方案 • SAS编程未来发展趋势和展望
01
SAS编程概述
SAS简介
SAS公司概况
SAS是一家总部位于美国北卡罗来纳州的公 司,专门从事统计分析软件的开发和销售。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Slide 29
宏函数
宏功能包括很多宏程序语句和宏函数, 下面列出几个
函数名 %Eval 说明 计算算术和逻辑表达式 整数格式
%put _user_; %put _automatic_; %put _all_; 显示用户定义的宏变量 显示系统提供的自动宏变量 显示所有宏变量
显示指定宏变量的值 %put &宏变量名;
例如
%put &hello; %put &dsn; %put this is my test: &dsn;
%end; %mend;
/*调用宏*/ %test2
Slide 24
2) 条件判断语句
格式: %If 表达式 %THEN 语句1; % ELSE 语句2;
或复合语句 %If 表达式 %THEN %DO; 语句组; %END; % ELSE %DO; 语句组; %END;
Slide 25
例子,根据输入选择性输出
引用: %宏名称(参数1,参数2,….)
说明:每个参数值将赋予宏定义中相应位置的参数。
Slide 16
例如,宏参数的定义与调用
/*定义*/ %macro myprint(dataset,varlist); proc print data=&dataset; var &varlist; run; %mend; /*引用,指定参数*/ %myprint(sashelp.class,name sex) 说明:参数与参数之间以逗号分隔,引用时,第二个 参数varlist的值为:name sex。
%SYSEVAL 计算算术和逻辑表达式 浮点格式 F %SYSFUNC 调用数据步函数,功能强大 %SYSFUNC(数据步函数(参数),<输出格式>)
Slide 30
例如,宏变量计算
%let x=100; %let y=%eval(&x+200); %let z=&x+200; %put y=&y z=&z; %put %sysevalf(&x+12.35); %put %sysfunc(today(),mmddyy10.); Log窗口显示的结果为: y=300 z=100+200 112.35 11-25-2015 浮点计算需要用%sysevalf函数 %sysfunc函数调用数据步函数today(),获取当前日期
title "我的标题:This is my first macro variable"; proc print data = SASHELP.CLASS; run;
实质上,SAS在运行时,将宏变量的值替代到了 相应的位置上 即,&hello换成了This is my first macro variable &DSN换成了SASHELP.CLASS
自动宏变量:
SAS系统提供的可以引用的宏变量
Slide 4
1) 自定义宏变量
自定义宏变量格式,使用%let语句
%LET 宏变量名 = 宏变量值;
例如: %let hello = This is my first macro variable;
%let DSN = SASHELP.CLASS;
Slide 28
例子,将数据集观测总数赋给宏变量Total
data _null_; set sashelp.class nobs=i; call symput('Total',i); run;
用数据步计算1到Total之间的自然数之和,赋给宏变量 Ntotal,用%put语句显示宏变量Ntotal的值
%macro test3(Res=Y); %if &Res=Y %then %put Yes, you are right!; %else %put No, you are wrong!; %mend; %test3(res=n) %macro test4(Num=Y,dsn=sashelp.class); proc print data=&dsn; %if &Num=Y %then %do; var _numeric_; 根据Num的值判断输出 %end; Y:输出全部数值变量 %else %do; 其它,输出所有变量 var _all_; %end; run; %mend; %test4(Num=Y)
Slide 10
4) 宏变量与后续文本的分隔
当宏变量跟后续文本紧密同时使用时,需要界定宏变量的 结束位置
例如
title1 “&hello1 第一个程序”;
title2 “&hello2 第二个程序”; 此时,SAS会认为宏变量名为hello1和hello2,而实际上宏 变量为hello 解决办法:在宏变量结束的地方加一个英文句号(.),如下
Slide 22
1) 宏do循环语句
直到型循环 %Do %Until(表达式); 循环体; %End; 当型循环 %Do %While(表达式); 循环体; %End; 注:当型循环和直到型循环需自己设置一个宏变量作为 循环变量,对循环变量累加赋值时需使用函数%eval( )来 计算算术表达式的值
Slide 26
6. 宏与数据步的信息交换
常用的两个子程序或函数
子程序 SYMPUT子程序 说明 在数据步中,将变量的值传给宏变量 使用语法: Call symput(‘宏变量名’,变量名); 在数据步中,获取宏变量的值 使用语法: Y=symget(‘宏变量名’);
SYMGET函数
Slide 27
SAS宏简介
Slide 1
主要内容:
1.概述 2.宏变量
3.宏
4.宏参数 5.宏内流程控制结构 6.宏与数据步的信息交换 7.宏语句与宏函数
Slide 2
1.概述
SAS宏工具是SAS系统的重要编程工具,功能强大 可以给一个变量、一段程序、一段文本命名,供以后调用 是编制用户化的SAS系统的重要工具 使用宏工具来完成以下任务:
DO: DO: DO: DO: DO: 1 2 3 4 5
Slide 21
&i;
生成重复文本
%macro dsn(name, num); %do i=1 %to # &name&i %end; %mend;
在DATA语句中调用宏dsn: data %dsn(AB, 5); run;
产生下列data步语句: DATA AB1 AB2 AB3 AB4 AB5;
%let k = 1;
Slide 5
2)引用宏变量
引用宏变量的方式:在宏变量名前使用&
&宏变量名
例如,
title "我的标题:&hello"; proc print data = &DSN; run;
注意:只有在双引号中,宏变量才能被引用; 单引号不会引用!
Slide 6
等价的SAS数据步程序
title1 “&hello.1 第一个程序”;
title2 “&hello.2 第二个程序”;
Slide 11
5) 间接引用宏变量
“&宏变量名”来引用宏的方式是直接引用 如果引用的宏变量名是通过宏产生的,则需要间接引用, 此时需要用:&& 例如,有三个宏变量:data1,data2, data3,只是末尾数字不 同。采用下列方式引用时,需用间接引用方式。
例子,
%let mynum=36; data a; input x@@; call symput('px',x); y=symget('mynum'); cards; 1234 ; run;
创建宏变量mynum,取值为36 在数据步中,通过symget()函数获取宏变量的值,赋给变量Y 在数据步中,通过symput()子过程创建宏变量px,将变量x的值 赋给宏变量
Slide 7
多次引用宏变量
title "我的标题:&HELLO"; title2 "打印的数据集是&DSN"; PROC PRINT DATA = &DSN; RUN;; DATA A; SET &DSN; IF SEX="M"; RUN; 三次引用宏变量DSN
PROC PRINT DATA=A; RUN;
Slide 14
宏的调用
调用宏的格式,使用%
%宏名称
例如,调用上面建立的宏myprint
%myprint 其作用就是执行下面SAS程序 proc p: %macro 宏名称(参数1,参数2,….); 宏文本 %mend;
说明:其中参数列是逗号分开的参数名,参数列中提到 的参数在宏文本中作为宏变量引用
Slide 23
例子,%DO %WHILE
%macro test2; %let i=1; %do %while(&i<10); %put this is a test for DO WHILE: &i; %let i=%eval(&i+1);
/*函数%eval()将整数值宏文本转换成数值进行算术运算*/ /*函数%sysevalf()将带小数的文本转换成数值进行算术运算*/
Slide 17
关键字参数的定义与调用