1:where和If最本質的區別,以及一些小的區別
1.1:The WHERE statement examines what is in the input page buffer and selects observations before they are loaded in the program data vector, which results in a savings in CPU operations(Where從buffer中進行篩選再讀入pdv)
The subsetting IF statement loads all observations sequentially into the program data vector. If the statement finds a match and the statement is true, then the data is processed and is written to the output page buffer(If先讀入pdv再進行篩選)
1.2:if可以從input的數據和sas數據集的數據中進行篩選,where只能篩選sas數據集的數據
if可以if語句的條件條件選擇子句,where不能
where比if高效
where中能用contains的地方一律考慮用like
if語句<可執行語句>
IF statement tells SAS which observations to include, the DELETE statement tells SAS which observations to exclude
IF Sex = 'f'; IF Sex = 'm' THEN DELETE; 作用一樣!
data b;
set sashelp.class; if _n_ le 4; *如果if為真,則繼續執行if后面的語句,最后輸出滿足if的條件的觀測,如果if為假則立刻返回到data步開頭繼續執行下一條set語句; y = 'now';
/*
y = 'now';
if _n_ le 4;也能得出同樣的結果,但是效率相對來說較低,因為要重復執行y的賦值語句
*/ run;
if的另外兩種格式
if x=3 then y=4; 對於要表達的只有一條數據就用then
if x=3 then do y=4;z=5;end; 對於要表達的有多條語句就用then do end;
NOTE: 從數據集 SASHELP.CLASS. 讀取了 19 個觀測
NOTE: 數據集 WORK.B 有 4 個觀測和 6 個變量。
NOTE: “DATA 語句”所用時間(總處理時間):
實際時間 0.03 秒
CPU 時間 0.03 秒 日志中讀入了19個觀測,證明是全部讀入再一個個判斷是否滿足條件
data a;
input x y@@;
cards;
1 10 1 20 0 200 2 30 2 40
3 50 3 60 4 70 3 80 4 400 ; run; proc sort data=a;by x;run; data b; set a; *where x ; *后面不添加條件是篩選x不為0和不為缺失值的數值型數據,只適用於數值型; where x is not missing; *篩選x不為缺失值的數據包括0,適用於數值型和字符型; run; proc print data=b noobs;
where和if的最重要的幾點區別
1:where不可執行、if可執行
2:where有自己特定的表達式,if是是通用表達式 例如where x is missing;
3:where只能從現有的sas數據集中選擇觀測,if語句還可以用input語句產生的觀測中選擇。*商用的一般都是現有的sas數據集;
4:where的效率比if高
5:何時使用if何時使用where?如果需要對pdv觀測進行處理才能決定哪條觀測,只能使用if。其余能使用where
2:select 、if else if的選擇
For numeric variables, SELECT statements should always be slightly more efficient (use less CPU time) than IF-THEN/ELSE statements. The performance gap between IF-THEN/ELSE and SELECT statements gradually widens as the number of conditions increases
For character variables, IF-THEN/ELSE statements are always more efficient than SELECT statements. The performance gap widens quickly between the two techniques as the number of conditions increases.
使用兩種選擇方式的最佳情況
Use IF-THEN/ELSE statements when
1:the data values are character values
2:the data values are not uniformly distributed
3:there are few conditions to check.
Use SELECT statements when
1:you have a long series of mutually exclusive numeric conditions
2:data values are uniformly distributed.
3:where和obs/firstobs連用,來選擇需要的觀測行
記住,obs/firstobs是邏輯上選擇觀測值,並不是實際選擇也就意味着不會去除其他的觀測值
where在obs/firstobs前執行
4:讀入外部數據時選擇需要的obs
先看一張外部數據讀入后sas程序內部的流程圖
這里不能用where來截取子集,因為where不能用於篩選外部數據。
這里將if放在input后篩選讀入pdv的觀測行來減少cpu的運行時間
I/O的次數指的是外部data和buffers之間的通信的次數,減少的方式肯定是不能通過where/if等語句,只可能通過bufno、bufsize、sasfile等選項
5:keep/drop
下圖展示keep和drop對於數據的作用環節
buffer后的keep、drop可以減少輸入pdv中的變量個數從而減少CPU time
buffer前的keep、drop可以減少讀入buffer中的變量個數也就是讀入數據的總大小,從而減少I/O次數