BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
MM88
Calcite | Level 5

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:

EventTime

0

0
00
10.3
10.4
10.4
00
00
10.1
10.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:

EventTimeGroupCumulative

0

000
0000
10.311.1
10.410
10.410
0000
0000
10.120.6
10.520

 

I was using the retain function with no luck.

Thanks for your suggestions.
Regards

1 ACCEPTED SOLUTION

Accepted Solutions
PeterClemmensen
Tourmaline | Level 20
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

 

View solution in original post

1 REPLY 1
PeterClemmensen
Tourmaline | Level 20
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

 

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

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!

Register Now

Creating Custom Steps in SAS Studio

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 1 reply
  • 1142 views
  • 0 likes
  • 2 in conversation