簡體   English   中英

如何在 SAS 企業指南中的 PROC SQL 中創建標志通知 ID 上的兩列是否有變化?

[英]How to create flag inform whether was some change in two columns on ID in PROC SQL in SAS Enterprise Guide?

我在 SAS 企業指南中有如下表:

ID  | val1| val2
----|-----|-----
123 | M   | M
123 | M   | P
123 | P   | P
444 | PR  | PR
444 | PR  | PR
567 | PR  | M
567 | M   | M
99  | PR  | P

我需要創建值為 0/1 的新列“col1”:

  • 如果某個 ID 從未將值 PR 從列“val1”更改為列“val2”中的 M 或 P 的值,則此 ID 為 1,否則為 0

因此,我需要如下所示的內容:

ID  | val1| val2| col1
----|-----|-----|----
123 | M   | M   | 1
123 | M   | P   | 1
123 | P   | P   | 1
444 | PR  | PR  | 1
444 | PR  | PR  | 1
567 | PR  | M   | 0
567 | M   | M   | 0
99  | PR  | P   | 0

因為:

  • 123 - 在“col1”中有 1,因為從未將 PR 更改為 M 或 P
  • 444 - 在“col1”中有 1,因為從未將 PR 更改為 M 或 P
  • 567 - 為 0,因為將 PR 更改為 M
  • 99 - 為 0,因為將 PR 更改為 P

如何在 SAS 企業指南中的 PROC SQL 中做到這一點?

因此,您想要將 ID 級別的單個值復制到該 ID 級別的所有觀察值上嗎? PROC SQL 使這很容易,因為它會自動將聚合值重新合並回詳細觀察。

聽起來你想要的測試是

val1='PR' and val2 in ('M' 'P')

然后,當該表達式永遠不為真時,您希望整體結果為 1 (TRUE)。

data have ;
  input ID val1 $ val2 $ EXPECT ;
cards;
123  M    M    1
123  M    P    1
123  P    P    1
444  PR   PR   1
444  PR   PR   1
567  PR   M    0
567  M    M    0
99   PR   P    0
;

proc sql;
  create table want as 
    select *
         , min(not (val1='PR' and val2 in ('M' 'P'))) as COL1
    from have
    group by id
  ;
quit;

結果:

Obs     ID    val1    val2    EXPECT    COL1

 1      99     PR      P         0        0
 2     123     P       P         1        1
 3     123     M       M         1        1
 4     123     M       P         1        1
 5     444     PR      PR        1        1
 6     444     PR      PR        1        1
 7     567     M       M         0        0
 8     567     PR      M         0        0

如果可以更改的解決方案:

proc sort data=have;
    by ID;
run;
data want;
    * for every ID, read the data you have twice *;
    set have (in=first_pass) have (in=last_pass);
    by ID;
    
    * From the first pass, remember if any observation "changed" from PR to P or M *;
    retain col1;
    if first.ID then col1 = 0;
    if val1 eq 'PR' and val2 in ('P', 'M') then col1 = 1;
    
    * only output the results from the second pass *;
    if last_pass;
run;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM