簡體   English   中英

如何在 SAS 中找到最后一組的第一行,排序很重要?

[英]How do I find first row of last group in SAS, where ordering matters?

我想在這方面尋求幫助,因為我是 SAS 的新手,但也可以使用 PROC SQL 方法。

我的數據集有 ID、時間變量和標志。 在我按 id 和時間排序后,我需要找到最后一個標記組/條紋的第一個標記觀察。 如:

ID TIME FLAG
1   2    1
1   3    1
1   4    1
1   5    0
1   6    1
1   7    0
1   8    1
1   9    1
1  10    1
2   2    0
2   3    1
2   4    1
2   5    1
2   6    1
2   7    1

在這里,我希望我的腳本返回 ID 1 的時間為 8 的行,因為它是最后一個“連續”或標記組的第一個觀察結果。 對於 ID 2,它應該是時間為 3 的地方。

期望的輸出:

ID TIME FLAG
1   8    1
2   3    1

我試圖首先使用。 最后。 在這里,但我想這里的問題是我將時間上移位的標記組/條紋視為不同的組,而 SAS 將它們視為僅由標志分隔,因此簡單的“先取。從最后”。 是不夠的。

我還考慮將標志折疊為字符串並使用正則表達式前瞻,但我無法想出方法或模式。

我只想編寫一個雙 DOW 循環。 第一個將讓您計算要輸出的此 ID 的觀察值,第二個將再次讀取記錄並輸出選定的觀察值。

您可以在 BY 語句上使用 NOTSORTED 關鍵字讓 SAS 計算 FIRST.FLAG 變量。

data have;
  input ID TIME FLAG;
cards;
1   2    1
1   3    1
1   4    1
1   5    0
1   6    1
1   7    0
1   8    1
1   9    1
1  10    1
2   2    0
2   3    1
2   4    1
2   5    1
2   6    1
2   7    1
;

data want;
  do obs=1 by 1 until(last.id);
    set have;
    by id flag notsorted;
    if first.flag then want=obs;
  end;
  do obs=1 to obs;
    set have;
    if obs=want then output;
  end;
  drop obs want;
run;

按 id 遍歷數據集。 使用滯后函數查看標志的當前值和先前值。 如果當前值為 1 而前一個值為 0,或者它是該 ID 的第一個觀察值,則將時間值寫入保留變量。 只輸出每個 id 的最后一次觀察。 保留變量應包含最后一個標記組的第一個標記觀察的時間:

data result;
 set have;
 by id;
 retain firstflagged;
 prevflag = lag(flag);
 if first.id and flag = 1 then firstflagged = time;
 else if first.id and flag = 0 then firstflagged = .;
 else if flag = 1 and prevflag = 0 then firstflagged = time;
 if last.id then output;
 keep id firstflagged flag;
 rename firstflagged = time;
run;

暫無
暫無

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

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