作者realtemper (一觉醒来傅钟前)
看板Statistics
标题Re: [程式] SAS中LAG程式无法用在if...then
时间Wed Jun 17 18:26:30 2015
※ 引述《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://webptt.com/cn.aspx?n=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
1F:推 faceoflove56: 太详细了 感谢前辈指导 06/18 13:01
2F:→ realtemper: 好说!曾经受过帮助,稍微回馈一下板上而已~ 06/20 07:35