BookmarkSubscribeRSS Feed
mdwilson
Fluorite | Level 6

I have a large data set with multiple births per mother. I'm studying the occurrence of an adverse event for the infant. I was to know if the number of infants that had the adverse event previously for a given mother affects the chance of the adverse event happening for subsequent births. The first birth for each mother should always have 0 previous events, but I need to include sum the number of events after that, including if the event happens on the first birth. 

 

So I have:

 

data have;
input mom_id event ;
datalines;
1 0
1 1
1 0
2 1
2 1
2 0
3 0
3 0
3 0
4 1
4 1
4 1
;
run;

 

These are the data I want:


data want;
input mom_id event prev_events;
datalines;
1 0 0
1 1 0
1 0 1
2 1 0
2 1 1
2 0 2
3 0 0
3 0 0
3 0 0
4 1 0
4 1 1
4 1 2

;

run;

 

I have a lot of experience with SAS, but not with macros or loops. Thanks for your help!

1 REPLY 1
PeterClemmensen
Tourmaline | Level 20

I think this is what you want

 

data have;
input mom_id event ;
datalines;
1 0
1 1
1 0
2 1
2 1
2 0
3 0
3 0
3 0
4 1
4 1
4 1
;

data want;
   set have;
   by mom_id;
   if first.mom_id then prev_events = 0;
   prev_events + ifn(first.mom_id, ., lag(event));
run;

 

Result:

 

mom_id  event  prev_events
1       0      0
1       1      0
1       0      1
2       1      0
2       1      1
2       0      2
3       0      0
3       0      0
3       0      0
4       1      0
4       1      1
4       1      2

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

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
  • 552 views
  • 0 likes
  • 2 in conversation