sas條件判斷語句where,if的區別,以及where選項


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高效

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個觀測,證明是全部讀入再一個個判斷是否滿足條件

 where語句(where=選項)<不可執行語句>

 是在系統准備把觀測讀入pdv之前制定數據必須滿足的一個條件。

WHERE where-expression-1<logical-operator where-expression-n>;

logical-operator can be AND, AND NOT, OR, or OR NOT

where表達式的算符:between and、is missing (is null)、contain (?)、like、same and、in

TIPS:

  1:where語句不能與自動變量連用以及新創建的變量連用,因為where語句在pdv之前執行

    2:使用where語句時,必須保證讀入數據集的完整性,不能使用firstobs=2等不能完整讀入數據集的選項

  3:當where選項與where語句同時作用於一個數據集的時候,系統只會考慮where選項,where選項可以只對某一個數據集起作用,而where語句是對所有的數據集起作用。

  4:當data步包含where語句和by語句時,where語句先於by語句之前被執行,by組對執行完畢后的數據集重新定義first/last變量。

  5:能用contains的地方都能用like、所以首先考慮用like。where x like a_b%; '_'表示正好有一個字符與之匹配,'%'表示可以替代任意多個字符

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM