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;