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!
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
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!
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.
Ready to level-up your skills? Choose your own adventure.