I'm writing code to flag data. In this one dataset, we have medical kits supplied to different subjects. each subject comes in somewhere between 1 to 8 times, and each visit is labeled as V1-V8. i need to make sure that the id number on a medical kit given to a subject on his last visit, matches the same one he received on his prior visits.
ex:
Kit# Subject Visit
22 01 V1
22 01 V2
44 02 V1
45 02 V2
in the example, subject one would be fine, because they were given the same medical kit.
Subject 2 would flag, because they were given a different medical kit than in previous visits.
Hello @Rcrowder
Assuming I understand your requirement
data have;
input Kit Subject Visit $;
datalines;
22 01 V1
22 01 V2
44 02 V1
45 02 V2
;
proc sql;
create table want as
select *,count( distinct kit)>1 as Flag
from have
group by subject;
quit;
Welcome to the SAS Community 🙂
Here is one way
data have;
input Kit Subject Visit $;
datalines;
22 01 V1
22 01 V2
44 02 V1
45 02 V2
;
data want(drop=_:);
do _iorc_=1 by 1 until (last.Subject);
set have;
by Subject;
if _iorc_=1 then _Kit=Kit;
flag=max(ifn(_Kit=Kit, 0, 1), flag);
end;
do until (last.Subject);
set have;
by Subject;
output;
end;
run;
Hello @Rcrowder
Assuming I understand your requirement
data have;
input Kit Subject Visit $;
datalines;
22 01 V1
22 01 V2
44 02 V1
45 02 V2
;
proc sql;
create table want as
select *,count( distinct kit)>1 as Flag
from have
group by subject;
quit;
Start by putting things in order (in case they're not already):
proc sort data=have;
by subject visit;
run;
Now we can compare to the previous observation:
data want;
set have;
by subject;
retain flag;
if first.subject then flag = 0;
if lag(kit_number) ne kit_number and not first.subject then flag = 1;
if last.subject and flag then output;
run;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.