我遇到的数据集问题如下所示。这是不同地点/周的库存数量:
data have;
input itm location $ week inv;
cards;
3 x 1 30
3 x 2 20
3 x 3 0
3 x 4 5
3 y 1 100
3 y 2 90
3 y 3 0
3 y 4 6
4 x 1 30
4 x 2 0
4 x 3 40
4 x 4 10
;
run;
问题是......一旦特定位置/项目组合的库存达到0,我希望该组合的所有剩余周数都用0来估算。我想要的输出如下:
data want;
input itm location $ week inv;
cards;
3 x 1 30
3 x 2 20
3 x 3 0
3 x 4 0
3 y 1 100
3 y 2 90
3 y 3 0
3 y 4 0
4 x 1 30
4 x 2 0
4 x 3 0
4 x 4 0
;
run;
我对SAS很新,不知道怎么做。帮助?!
谢谢!
答案 0 :(得分:5)
您可以通过以下步骤执行此操作:
by
语句表示顺序(输入数据集必须相应地排序)retain
语句将控制变量(reset
)的值传递给以下行reset=0
)reset=1
)以获取inv 代码:
data want (drop=reset);
set have;
by itm location week;
retain reset;
if first.location then reset=0;
if (inv = 0) then reset=1;
else if (reset = 1) then inv=0;
run;
reset
的值在行之间保持不变,直到明确修改。
by语句中存在变量week
只是为了检查输入数据是按时间顺序排序的。
答案 1 :(得分:3)
以下内容将使用proc sql
来提供所需结果。我已经评论了为什么我会采取不同的步骤。
proc sql;
/* First of all fetch all observations where the inventory is depleated.*/
create table work.zero_inv as
select *, min(week) as min_zero_inv_week
from work.have where inv = 0
/* If your example data set had included several zero inventory weeks, without the follwing "commented" code you would got duplicates. I'll leave the excercise to explain this to you. Just alter your have data set and see the difference.*/
/*group by itm, location
having (calculated min_zero_inv_week) = week*/;
create table work.want_calculated as
/* Since we have fetched all weeks with zero inventories, we can use a left join and only update weeks that follows those with zeros and leave the inventory untouched for the rest.*/
select t1.itm, t1.location, t1.week,
/* Since we use a left join, we can check if the second data sets includes any rows at all for the specific item at the given location. */
case when t2.itm is missing or t1.week <= t2.week then t1.inv else t2.inv end as inv
from work.have as t1
left join work.zero_inv as t2
on t1.itm = t2.itm and t1.location = t2.location
/* proc sql does not promise to keep the order in your dataset, therefore it is good to sort it.*/
order by t1.itm, t1.location, t1.week;
run;
proc compare base=work.want compare=work.want_calculated;
title 'Hopefully no differences';
run;
请记住,stackoverflow不是&#34;给我代码&#34;论坛,习惯上先自己尝试一些解决方案。因为这是你的第一个问题,我会给你一些懈怠;欢迎来到SO:D。