SAS(九)DATA步--运行语句
上一篇我么讲解了SAS DATA步的文件操作语句,这篇我们来讲解一下DATA步的运行语句
赋值语句和累加语句
- 赋值Variable = expression
例:x=a + b;
- 累加 Variable + expression
例:if x=5 then n+1;
例:n+(-1)
- 累加语句中的变量必须是数值型变量,初始值为0
Delete和lostcard语句
- Delete语句告诉SAS系统停止处理当前的观测,并且返回到这个Data步的开头处理其他观测
- 当SAS系统遇到用几个记录表示一个观测的时候,数据中有丢失记录时,使用Lostcard语句来重新对准输入数据
Delete语句
data jn;
input a b c;
file print;
put _n_;
if a>3 then delete;
*put _n_;
*total=a+b;
cards;
1 2 3
3 3 2
5 3 1
3 3 3
;
proc print data=jn;
run;
data ins;
input id 1-3 reject 8-10 #2 idc 1-3 pass;
if id ne idc then lostcard;
/*如果是delete语句,
则input语句对应的两条记录同时删除*/
cards;
301 32
301 61432
302 53
302 83171
400 92845
411 46
411 99551
411 123
;
proc print data=ins;
title '每个观测包括两个数据行';
run;
lostcard语句
Stop和abort语句
- 用stop语句来停止处理data步,正被处理的那个观测没有添加到SAS数据集中,stop语句不影响后面的任意data步或proc步的执行
- 用abort语句来中止SAS系统执行当前DATA步,return选项关闭SAS并返回操作系统。
- Stop与abort的区别在于abort语句置_error_变量为1
stop例子
data check;
input ssn 1-3 pay;
if ssn=222 then stop;/*abort return;stop*/
put _all_;
cards;
111 100
222 200
444 300
;
data a;
input b;
cards;
12345
;
proc print data=a;
run;
abort例子,SAS被强行关闭
data check;
input ssn 1-3 pay;
if ssn=222 then abort return;
put _all_;
cards;
111 100
222 200
444 300
;
data a;
input b;
cards;
12345
;
proc print data=a;
run;
Where语句
- 从已存在的SAS数据集选择子集,在把观测读入之前规定数据必须满足一个条件
- Where 语句与if语句相比在读取数据时更为高效,因其在移动所有观测到子集之前先选择数据。
- Where语句丰富的表达式
data aa;
set peixun.fly;
where salary>1000;
*where industry='Food';
*where employs between 50 and 70;
*where employs in (61,62);
*where employs is missing;
*where industry ? 'Ele'; /* ? means "contains"*/
*where industry like '%t%'; /* % can substitute many char*/
*where industry like 'O_l'; /* _ can substitute one char*/
run;
proc print data=aa;
run;
output语句
DATA步的每次迭代,后台自动使用output语句,但如果程序中主动加上output语句,即相当于取消自动output语句,变成在条件符合时输出。
data aaaaa;
input a b;
if a=1 then output;
put _n_;
cards;
2 3
1 5
2 4
1 6
;
run;
proc print data=aaaaa;
run;
- 用到output语句其他情况:output123例
1.从一个输入的数据文件中,创建几个SAS数据集
2.从输入的每个数据行中,创建二个或更多个观测
3.把几个输入观测组合并成为一个观测
- 后面接名字表示输出到指定数据集,但名字必须也在DATA后出现
data year81 year82 year83;
input year x1-x2;
if year=1981 then output year81;
else if year=1982 then output year82;
else if year=1983 then output year83;
cards;
1981 1 2
1982 2 3
1983 3 4
;
run;
proc print data= year81 year82 year83;
run;
Call语句
- 调用其他子程序
call routine (parameter-1 < ,…parameter-n>)
如SAS提供一系列随机数子程序
- 发布操作系统命令
call system (command)
data a;
seed1=161321804;/*赋予随机数种子初始值*/
seed2=135279821;
do i=1 to 5;
x1=ranuni(seed1);
x2=ranuni(seed2);
output;
end;
proc print data=a;
title '使用随机数函数';
run;
data b;
seed3=161321804;
seed4=936674311;
do i=1 to 5;
call ranuni(seed3,x3);/*seed3存放种子值,x3为随机数变量名*/
call ranuni(seed4,x4);
output;
end;
proc print data=b;
title '调用随机数子程序,产生2个
随机数流,并能观测到当前随机数种子值';
run;
data _null_;
call system('dir *.*');
run;