SAS 中用于检查先前值的滞后函数
Lag function in SAS for checking previous value
在SAS中,我想创建一个标签来检查之前的卖出指标:如果之前时间段的卖出指标是1/0而当前是0/1(意味着它已经改变)然后我将值 1 分配给 ind 变量。
数据集如下所示:
Customer Time Sell_Ind
1 2 1
1 3 0
1 4 0
2 23 0
2 24 0
2 30 0
5 12 1
5 11 0
以此类推
我的预期输出是
Customer Time Sell_Ind Ind
1 2 1 0
1 3 0 1
1 4 0 0
2 23 0 0
2 24 0 0
2 30 0 0
5 12 1 0
5 11 0 1
previous/current勾选是客户的意思。
我试过如下
data mydata;
set original;
By customer;
Lag_sell_ind=lag(sell_ind);
If first.customer then Lag_sell_ind=.;
Run;
但它没有 return 预期的输出。
在 sql 中,随着时间的推移,我可能会使用按客户划分的分区,但我不知道如何在 SAS 中执行相同的操作。
你说到一半了,你只需要加一个if语句就可以得到想要的输出了。
data want;
set have;
by customer;
lag=lag(sell_ind);
if first.customer then lag=.;
if sell_ind ne lag and lag ne . then ind = 1;
else ind = 0;
drop lag;
run;
您可以使用如下所示的 IFN 函数简化此过程。
data have;
input Customer Time Sell_Ind;
datalines;
1 2 1
1 3 0
1 4 0
2 23 0
2 24 0
2 30 0
5 12 1
5 11 0
;
data want;
set have;
by customer;
Lag_sell_ind = ifn(first.customer, 0, lag(sell_ind));
Run;
在SAS中,我想创建一个标签来检查之前的卖出指标:如果之前时间段的卖出指标是1/0而当前是0/1(意味着它已经改变)然后我将值 1 分配给 ind 变量。
数据集如下所示:
Customer Time Sell_Ind
1 2 1
1 3 0
1 4 0
2 23 0
2 24 0
2 30 0
5 12 1
5 11 0
以此类推
我的预期输出是
Customer Time Sell_Ind Ind
1 2 1 0
1 3 0 1
1 4 0 0
2 23 0 0
2 24 0 0
2 30 0 0
5 12 1 0
5 11 0 1
previous/current勾选是客户的意思。
我试过如下
data mydata;
set original;
By customer;
Lag_sell_ind=lag(sell_ind);
If first.customer then Lag_sell_ind=.;
Run;
但它没有 return 预期的输出。 在 sql 中,随着时间的推移,我可能会使用按客户划分的分区,但我不知道如何在 SAS 中执行相同的操作。
你说到一半了,你只需要加一个if语句就可以得到想要的输出了。
data want;
set have;
by customer;
lag=lag(sell_ind);
if first.customer then lag=.;
if sell_ind ne lag and lag ne . then ind = 1;
else ind = 0;
drop lag;
run;
您可以使用如下所示的 IFN 函数简化此过程。
data have;
input Customer Time Sell_Ind;
datalines;
1 2 1
1 3 0
1 4 0
2 23 0
2 24 0
2 30 0
5 12 1
5 11 0
;
data want;
set have;
by customer;
Lag_sell_ind = ifn(first.customer, 0, lag(sell_ind));
Run;