proc sort data=have; by usubjid AVISITN vistyp; run; data want; set have; by usubjid AVISITN; if first.usubjid then flag = "" if first.AVISITN then flag = ""; if vistyp = 1 and first.AVISITN then flag = "Yes"; else if vistyp ne 1 and first.AVISITN then flag = "Yes"; else if vistyp = 1 and flag = "" then flag = "Yes"; if last.AVISITN then output; drop visdup; run; proc print data=want; run; Hope this should work This code first sorts the have dataset by usubjid, AVISITN, and vistyp. Then, it processes the data by groups of usubjid and AVISITN. Within each group, it sets the flag variable based on the specified conditions. Finally, it keeps only the first record per visit (AVISITN) and drops the unnecessary Try and let me know if it doesn't work
... View more