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

Hi Everyone:

 

I posted below an example data set along with a column that I would like to create. In this data set, I have different people (personid) and for some observations, an event is present (1) and for some it is not (0). The data are sorted by personid and date, which I did not show. I want to create a new column (want):

-whenever, event=0, it should be 0.

-for a given personid: for the first event=1, it should be 1, and should stay as 1 as long as event=1.

-for a given personid: each time, the event transitions from 0 to 1, its value increases by 1.

 

I do not know how exactly I should go about this. I would very much appreciate your help.

Thank you

 

personid event want
1    0    0
1    0    0
1    0    0
1    0    0
1    0    0
1    1    1
1    1    1
1    1    1
1    1    1
1    1    1
1    0    0
1    0    0
1    1    2
1    1    2
1    1    2
1    0    0
1    1    3
2    1    1
2    1    1
2    0    0
2    0    0
2    0    0
2    0    0
2    1    2
2    1    2
2    1    2
2    0    0
2    0    0
2    1    3
2    1    3
2    1    3
2    0    0
2    1    4

1 ACCEPTED SOLUTION

Accepted Solutions
art297
Opal | Level 21

The following will do what you want:

data want (drop=_:);
  set have;
  by personid;
  _last_event=ifn(not first.personid,lag(event),0);
  if first.personid then _hold=0;
  if event eq 1 and _last_event eq 0 then _hold+1;
  want=ifn(event eq 0,0,_hold);
run;

Art, CEO, AnalystFinder.com

View solution in original post

3 REPLIES 3
art297
Opal | Level 21

The following will do what you want:

data want (drop=_:);
  set have;
  by personid;
  _last_event=ifn(not first.personid,lag(event),0);
  if first.personid then _hold=0;
  if event eq 1 and _last_event eq 0 then _hold+1;
  want=ifn(event eq 0,0,_hold);
run;

Art, CEO, AnalystFinder.com

Astounding
PROC Star

One possibility:

 

data want;

set have;

by personid event notsorted;

if first.personid then event_counter=0;

if first.event and event=1 then event_counter + 1;

if event=0 then want=0;

else want = event_counter;

drop event_counter;

run;

 

finans_sas
Quartz | Level 8

Thank you so much for your help! I love this forum.

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

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
  • 976 views
  • 2 likes
  • 3 in conversation