假设我有一个有三个变量的数据集:
身份证年度状况
1.2017年
1 2017年净氮
1 2018年N
2018年12月1日
2.2017年
2 2017年再发
2 2018年N
2 2018年N
我想创建一个名为NEW的第四列,它有三个可能的值('Yonly‘'Nonly’和'yesno')。在上面的例子中,输出将是:
二、二、四、二、
1将于2017年将.
1准2017年面额面额
1.2018年./#.
1 2018年
2.2017年.
2 2017年准转轨转轨
2.2018年.
2.2018年
注意:可能有丢失的数据。到目前为止,我的解决方案是错误的:
retain tmp '';
by ID Year;
if Status='Y' then tmp='Yonly';
if Status='N' then tmp='Nonly';
if tmp='Yonly' and Status='N' then tmp='yesno';
if tmp='Nonly' and Status='Y' then tmp='yesno';
if last.Year=1 then NEW=tmp;请帮帮忙?任何方法都可以,您不必使用RETAIN。
发布于 2017-02-24 15:09:30
确保定义TMP的长度。您的当前代码将TMP的长度设置为1,因为第一次使用是statement语句中列出的初始值。
在启动新组时,您遗漏了初始化步骤。
if first.year then tmp=' ';您的方法只能在每个组的最后一个记录上设置结果。如果你想要一组中的所有观测都有相同的值,那么我建议使用双道环。第一个循环可以用来查看是否存在'Y‘或'N’状态。然后你可以计算你的新变量。然后,第二个循环将再次读取组的数据,并将值写入。因为一个组的所有观察都是在一个数据步骤迭代中处理的,所以不需要使用need。
data want ;
do until (last.year) ;
set have ;
by id year ;
y = y or (status='Y');
n = n or (status='N');
end;
length new $8;
if Y and N then new='yesno';
else if Y then new='yesonly';
else if N then new='noonly';
else new='none';
drop y n ;
do until (last.year) ;
set have ;
by id year ;
output ;
end;
run;发布于 2017-02-24 15:09:26
这是你所做的事情,但更好的条件是这样做。
data want;
set have;
by id year;
retain last_status;
if first.year then last_status = status;
if last.year then do;
if status = last_status or missing(last_status) then new=cats(status,'only');
else if missing(status) then new=cats(last_status,'only');
else new='yesno';
end;
run;retain来自第一行的值,然后在最后一行只考虑基于这两个变量应该做什么--这样很简单。
https://stackoverflow.com/questions/42441348
复制相似问题