I want the variable 'change' to be set to 1 for first 3 patients, 2 for second 3 patients and so on.
data have;
input subject change;
datalines;
12345 1
12345 1
12345 1
23456 1
23456 1
23456 1
23456 1
34567 1
34567 1
34567 1
34567 1
45678 2
45678 2
45678 2
45678 2
run;
Instead of creating a variable to count the number of subjects read, you can loop for each subject, so that you can use the _N_ variable:
data want;
change+mod(_N_,3)=1;
do until(last.subject);
set have;
by subject;
output;
end;
run;
data have;
input subject ;
datalines;
12345 1
12345 1
12345 1
23456 1
23456 1
23456 1
23456 1
34567 1
34567 1
34567 1
34567 1
45678 2
45678 2
45678 2
45678 2
run;
data want;
set have;
by subject;
retain change 1;
if first.subject then patient+1;
if mod(patient,3)=0 and last.subject then do; output;change+1;end;
else output;
drop patient;
run;
data xxx;
retain count id 0 ;
set yyy;
count=count+1;
if mod(count,3)=1 then id=id+1;
run;
?
@pau13rown Neat!!!!!
@pau13rown You're increenting count with every observation, but I think you intend to increment only with every new subject:
data want; set have; by subject; if first.subject then do; count+1; id+(mod(count,3)=1); end; run;
And one can even get away without creating the count variable, via a conditional use of lag. I don't particularly recommend it, but it's a good demonstration that lag functions don't do "look-backs", but rather they manage queues:
data want;
set have;
by subject;
retain id 1;
if first.subject then id+(lag3(id)=id);
run;
Instead of creating a variable to count the number of subjects read, you can loop for each subject, so that you can use the _N_ variable:
data want;
change+mod(_N_,3)=1;
do until(last.subject);
set have;
by subject;
output;
end;
run;
Thank you this solution works too.
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!
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.