菜鸟求索~~
这两天看书的时候遇到这样一段程序
data retain2;
input id flag cde$ @@;
cards;
10 1 a 10 0b 10 0 c
20 1 a 20 0. 20 0 .
30 1 . 30 0.
;
proc sortdata= chapt4.retain2;by id descending flag;run;
data test2;
set retain2;
by id descending flag;
retain new;
if first.id thendo;
if cde eq "" then new="null";
else new=cde;
end;
if cde ne "" then new=cde;
run;
需求如下:
根据每一个id编号对应的标识变量flag(只取1和0两个值),如果:
1、flag=1对应的cde变量值非空,且flag=0对应的cde也非空,则对应的cde取值不变;如id=10有三条记录,cde值不变。
2、flag=1对应的cde变量值非空,且flag=0对应的cde取值为空,则对应的cde取值都为flag=1的值。如id=20有三条记录,由于flag=1对应的值为非空,但flag=0的值为空,故要把flag=0对应的cde值都变为a。
3、flag=1对应的cde变量为空,则该id下所有的cde都置为空。
整个理解下来,这段代码没有问题,但是当把数据集稍微做下改动时,这段代码就实现不了需求。改动如下:
cards;
10 1 a 10 0b 10 0 c
20 1 a 20 0. 20 0 .
30 1 . 30 0c
;
就是让id=30时,flag=1时,cde为空;而flag=0时,cde非空。
对于这个问题,如果对代码也进行了一下改动,就可以再次实现需求了,整体改动如下:
data retain2;
input id flag cde$ @@;
cards;
10 1 a 10 0b 10 0 c
20 1 a 20 0. 20 0 .
30 1 . 30 0c
;
proc sortdata= chapt4.retain2;by id descending flag;run;
data test1;
set retain2;
by id descending flag;
retain new m;
if first.id thendo;
m=cde;
if cde eq "" then new="null";
else new=cde;
end;
if m eq "" & cde ne "" then new="null";
/* if m eq "" & cde eq"" then new="null";*/
if m ne "" & cde ne "" then new=cde;
/* if m ne "" & cde eq ""then new=m;*/
run;
这里菜鸟想再一下大牛两个问题:
1、对于需求的实现,注释的语句是可有可无的,我知道这是跟retain语句有关,但是到底是怎么个运行逻辑,有点转不过来;
2、我想知道自己对原代码和需求的理解是不是存在什么问题,想问一下这样的改写合理吗?是不是还有更简便的改写?
写得有点多,谢各位大牛耐心解读!!