SAS按组生成序列号

  • 本文关键字:序列号 SAS sas
  • 更新时间 :
  • 英文 :


我需要在SAS中按组创建序列号并按组累积。

我有一个数据集,其中一列表示事件是否发生以及发生的时间。我也有初始日期时间和结束日期时间,我没有表示在我的示例数据。

<表类> 事件时间 tbody><<tr>000010.310.410.4000010.110.5

试试这个

data have;
input Event Time;
datalines;
0 0
0 0
1 0.3
1 0.4
1 0.4
0 0
0 0
1 0.1
1 0.5
;
data want(drop = c g);
c = 0;
do _N_ = 1 by 1 until (last.event);
set have;
by event notsorted;
c + time;
if first.event and event then g + 1;
end;

do _N_ = 1 to _N_;
set have;
group = ifn(event, g, 0);
cumulative = ifn(_N_ = 1, c, 0);
output;
end;
run;

结果:

Event  Time  group  cumulative
0      0.0   0      0.0
0      0.0   0      0.0
1      0.3   1      1.1
1      0.4   1      0.0
1      0.4   1      0.0
0      0.0   0      0.0
0      0.0   0      0.0
1      0.1   2      0.6
1      0.5   2      0.0

希望这对你有帮助。我不敢肯定这件事能一次完成。

输入数据:

data a;
input event time;
cards;
0 0
0 0
1 0.3
1 0.4
1 0.4
0 0
0 0
1 0.1
1 0.5
;
run;

代码:

data group (keep=event time group) cum(keep=group_cnt total_time index=(group_cnt));
retain group_cnt 0 total_time 0;
set a end=end_ds;
if ( not event and lag(event) ) then
output cum;
if ( event and not lag(event) ) then
group_cnt+1;
if ( not event ) then do;
total_time=0;
group=0;
end;
else do;
total_time=sum(total_time, time);
group=group_cnt;
end;
output group;
if ( end_ds and event ) then
output cum;
run;
data want;
keep event time group total_time;
set group;
group_cnt=group;
if ( group and not lag (group)) then
set cum key=group_cnt;
else total_time=0;
run;

结果:

0   0   0   0
0   0   0   0
1   0.3 1   1.1
1   0.4 1   0
1   0.4 1   0
0   0   0   0
0   0   0   0
1   0.1 2   0.6
1   0.5 2   0

最新更新