BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
altijani
Quartz | Level 8

Hi Community

 

I have the following dataset:

 

ID year event 

1  2014  0

1  2015  0

1  2016  1

2  2014  0

2  2015  1

2  2016  1

3  2014  1

3  2015  1

3  2016  1

 

I need to create an indicator that shows me the year the event happend, even for the years that the event was 0, as follows:

 

ID year event  year_event 

1  2014  0        2016

1  2015  0        2016

1  2016  1        2016

2  2014  0        2015

2  2015  1        2015

2  2016  1        2015

3  2014  1        2014

3  2015  1        2014

3  2016  1        2014

 

Any help is highly appreciated. Sorry if it is too simple.

 

Thanks!

1 ACCEPTED SOLUTION

Accepted Solutions
PaigeMiller
Diamond | Level 26

UNTESTED CODE

data first;
set have;
prev_event=lag(event);
prev_id=lag(id);
if id=prev_id and event=1 and prev_event=0 then output;
run;
data want;
merge have first(rename=(year=year_event) drop=prev_event prev_id);
by id;
run;

Assumes data is sorted by ID and year.

 

--
Paige Miller

View solution in original post

3 REPLIES 3
PaigeMiller
Diamond | Level 26

UNTESTED CODE

data first;
set have;
prev_event=lag(event);
prev_id=lag(id);
if id=prev_id and event=1 and prev_event=0 then output;
run;
data want;
merge have first(rename=(year=year_event) drop=prev_event prev_id);
by id;
run;

Assumes data is sorted by ID and year.

 

--
Paige Miller
ShrutiD
Fluorite | Level 6

TESTED CODE:

 

data count(rename= Year=Year_event);
set records;
by ID;
if first.ID then count=0;
if event eq 1 then count+1;
if count eq 1 then output;
drop event;
run;

 

data result;
merge records count;
by ID;
drop count;
run;
proc print data=result;
run;

 

Ksharp
Super User
data have;
input ID year event ;
cards;
1  2014  0
1  2015  0
1  2016  1
2  2014  0
2  2015  1
2  2016  1
3  2014  1
3  2015  1
3  2016  1
;
run;
data want;
 do until(last.id);
   set have;
   by id;
   if event and not found then do;new_year=year;found=1;end;
 end;
 do until(last.id);
   set have;
   by id;
   output;
 end;
 drop found;
run;

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

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
  • 3 replies
  • 1216 views
  • 2 likes
  • 4 in conversation