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
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
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.