Re: [程式] SAS中LAG程式無法用在if...then
※ 引述《faceoflove56 (1234567)》之銘言:
: [軟體程式類別]:
: SAS
: [程式問題]:
: 目前遇到一個問題
: lag函數無法用再if...then語法中
: 但我想把資料整理成
: Name Nth
: ---------------------
: ID1 0
: ID1 1
: ID1 2
: ID2 0
: ID2 1
: ID2 2
: ID2 3
: 我原先使用的語法為
: data
: set
: if first.name then Nth=0;
: if Name=lag(Name) then Nth=Lag(Nth)+1;
: run;
: 想請問該如何修改,感謝。
: [軟體熟悉度]:
: 低(1~3個月)
: [問題敘述]:
: Lag函數無法應用於if...then
: [程式範例]:
: 已貼在程式問題
: -----------------------------------------------------------------------------
提供更精簡的寫法如下:
(注意:要用 first.name 之前,你必須先 sort by name,以確保你的 name 變數
已經按照字母順序排序)
proc sort data=A;
by name;
run;
data A;
set A;
by name; /* enable first.name */
Nth + 1; /* equivalent to: retain (carry) lag(Nth) and then assign
Nth = lag(Nth) + 1 */
if first.name then Nth = 0; /* reset Nth = 0 when name is changed */
run;
然後回到您原本的問題,如果要明確的呼叫 lag 函數,
我建議標準作法如下:
===================================================
lag_x = lag(x); /* 執行 if 前,先把變數值給抓出來,存成 lag 開頭的暫存變數 */
/* 然後再於下面程式碼內使用 lag_x */
/* 原則:只對一個變數呼叫一次 lag(),且必在if之外 */
if condition then do;
/* statement if yes */
end;
else do;
/* statement if no */
end;
==================================================
統一命名 lag_xxxx 的好處在於,
如果你有很多個 lag_ 暫存變數,
最後可以以 data set option (drop=lag_:) 的語法,
一次性捨棄所有名稱以 lag_ 開頭的變數,以減低程式維護之負擔。例如:
data A (drop=lag_:);
/* your data step statement */
run;
希望對您有幫助!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.27.20.239
※ 文章網址: https://www.ptt.cc/bbs/Statistics/M.1434536805.A.CC1.html
p.s. tested on SAS 9.4 , win7 x64
※ 編輯: realtemper (114.27.20.239), 06/17/2015 19:03:30
推
06/18 13:01, , 1F
06/18 13:01, 1F
→
06/20 07:35, , 2F
06/20 07:35, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):