☑ This topic is solved.
Need further help from the community? Please
sign in and ask a new question.
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
Posted 05-06-2022 02:36 AM
(982 views)
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
1 ACCEPTED SOLUTION
Accepted Solutions
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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
1 REPLY 1
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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