Hi experts,
I need to create a sequence number by group in SAS and accumulate by group.
I have a dataset with a column that it says if an event occurs o not as well as the time in case of occurrence. I also have initial datetime and end datetime which I don't represent in my example data.
Example data:
| Event | Time |
0 | 0 |
| 0 | 0 |
| 1 | 0.3 |
| 1 | 0.4 |
| 1 | 0.4 |
| 0 | 0 |
| 0 | 0 |
| 1 | 0.1 |
| 1 | 0.5 |
I need to assign a sequence number for each group where the event happens and create a cumulative.
It should look something like:
Result data:
| Event | Time | Group | Cumulative |
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 |
I was using the retain function with no luck.
Thanks for your suggestions.
Regards
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;
Result:
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 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;
Result:
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
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
Check out this tutorial series to learn how to build your own steps in SAS Studio.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.