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

Dear SAS users,

 

I'm trying to capture change as well as the order of change in a do loop. But I can't get the code to work. Below is my hypothetical data and code.  I want to create a "censor" variable for the observations to flag those who got category=2 and never got category=4 with the rest of the days. So for example, id=1 should get censor=1, but id=2 or id=3 shouldn't  because it got category=4 afterwards. 

 

With my current code, I'm only able to code id=1 and id=3 correctly. I realize I shouldn't use do until but I can't get do while to work. I also don't have to stick to the do loop if that's not the appropriate approach. Any suggestion is appreciated.

 

Thanks in advance!

data have;
input ID days category;
datalines;

1 89 4
1 79 3
1 60 2
1 2 1
2 88 3
2 72 2
2 70 1
2 50 4
3 88 2
3 35 4
;
run;

proc sort data=have ;
by ID descending days;
run;

data have2;
do until(last.ID);
set have;
by ID category notsorted;
if lag(category)^=4 and category=2 then censor=1;
end;
run;

 

1 ACCEPTED SOLUTION

Accepted Solutions
SASKiwi
PROC Star

How about this? Don't think you need a DO loop.

data have;
input ID days category;
datalines;
1 89 4
1 79 3
1 60 2
1 2 1
2 88 3
2 72 2
2 70 1
2 50 4
3 88 2
3 35 4
;
run;

proc sort data=have ;
by ID descending days;
run;

data have2;
  set have;
  by ID;
  if first.id then censor = 0;
  retain censor;
  if category = 2 then censor = 1;
  if censor = 1 and category = 4 then censor = 0;
run;

 

View solution in original post

2 REPLIES 2
SASKiwi
PROC Star

How about this? Don't think you need a DO loop.

data have;
input ID days category;
datalines;
1 89 4
1 79 3
1 60 2
1 2 1
2 88 3
2 72 2
2 70 1
2 50 4
3 88 2
3 35 4
;
run;

proc sort data=have ;
by ID descending days;
run;

data have2;
  set have;
  by ID;
  if first.id then censor = 0;
  retain censor;
  if category = 2 then censor = 1;
  if censor = 1 and category = 4 then censor = 0;
run;

 

sdaniels429
Fluorite | Level 6

thank you @SASKiwi very much! That resolved my problem! I appreciate your help!

 

SAS Innovate 2025: Register Now

Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
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
  • 2 replies
  • 578 views
  • 0 likes
  • 2 in conversation