Hello,
I am attempting to count a variable up until a certain point. I have attached the code I have been trying to use below and have attached the table I have gotten thus far. Whenever I run this code, it will continue running and creating way more observations that I have.
DATA DisProj.Count;
SET WORK.Loop;
BY Person;
LENGTH count 8;
RETAIN count;
DO UNTIL (Outpatient_MOUD = 1);
IF FIRST.Person THEN count = 1;
ELSE count = count+1;
END;
RUN;
For example, I would like to count the outpatient_MOUD variable UNTIL it reaches zero, and then stop counting. I only want the sum up to the first zero.
Any help is greatly appreciated! Thank you.
Your DATA step keeps on processing the same observation over and over again. To break out of that, try it this way:
DATA DisProj.Count;
SET WORK.No_Loop_needed;
BY Person;
retain increment;
if first.person then do;
increment = Outpatient_MOUD;
count = 0;
end;
else if Outpatient_MOUD = 0 then increment = 0;
count + increment;
run;
Optionally, to get just the final count per person, add this statement before the RUN statement:
if last.person;
There is nothing in your DO loop that could possible change the value of that variable.
What is it you want to count?
Do you just want to count the number of people until you find the first one that is an outpatient?
data count;
set have;
by person;
count+first.person;
if outpatient=1 then do;
output;
put _n_= count= ;
stop;
end;
keep count;
run;
Your DATA step keeps on processing the same observation over and over again. To break out of that, try it this way:
DATA DisProj.Count;
SET WORK.No_Loop_needed;
BY Person;
retain increment;
if first.person then do;
increment = Outpatient_MOUD;
count = 0;
end;
else if Outpatient_MOUD = 0 then increment = 0;
count + increment;
run;
Optionally, to get just the final count per person, add this statement before the RUN statement:
if last.person;
Thank you so much! It worked exactly how I needed it to. @Astounding
You should remove the ELSE so it counts properly when the first value is zero.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.