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

Hello!

 

I have a dataset with a sorted ID variable and unsorted month variable that resets to 1 every so often.

 

IDMonth
10011
10012
10013
10011
10012
10021
10022
10023
10024
10031
10031
10032
10033
10031
10032
10031
10032
10033
10034
10035

 

I want to include another variable (Episode) which acts as an indicator for the number of series of months resets back to 1 for each ID.

 

IDMonthEpisode
100111
100121
100131
100112
100122
100211
100221
100231
100241
100311
100312
100322
100332
100313
100323
100314
100324
100334
100344
100354

 

I've found many examples of posts with a similar problem but none of them are successful in doing what I need. I've tried first.variable and do loops, among others. I know there has to be a simple solution. 

 

Here are two things I've tried that get close:

data want;
set have;
retain episode;
by ID month notsorted;
if month=1 then episode+1;
run;

data want;
set have;
by ID;
retain episode;
if month=1 then episode+1
run;

Thank you!

 

1 ACCEPTED SOLUTION

Accepted Solutions
PaigeMiller
Diamond | Level 26
data want;
    set have;
    by id;
    if first.id then episode=1;
    if not first.id and month=1 then episode+1;
run;
--
Paige Miller

View solution in original post

3 REPLIES 3
PaigeMiller
Diamond | Level 26
data want;
    set have;
    by id;
    if first.id then episode=1;
    if not first.id and month=1 then episode+1;
run;
--
Paige Miller
Jrstanek12
Calcite | Level 5

Thank you! This works perfectly. This is in the realm of what I was trying but still wasn't working, the first.id wasn't working properly.  The episode counter wasn't resetting back to 1 for every subsequent ID and was just counting increasingly.  My issue was I had other things going on in the data step prior to the by statement that were messing with the "by variable" logic so once I took that out it worked perfectly.  

 

 

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

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
  • 878 views
  • 4 likes
  • 3 in conversation