Re-coding variables to match the first instance of that variable for a given record

Reply
Occasional Contributor
Posts: 15

Re-coding variables to match the first instance of that variable for a given record

******REPOST******* I had posted this in the Base SAS programming community, but it was suggested that it might be more helpful over here. Here is the link to the original thread: https://communities.sas.com/t5/Base-SAS-Programming/re-coding-multiple-records-to-match-the-first-in...

 

In short. I had multiple records per individual,  all with the potential to have different postal codes. I needed all of the postal codes to match up to the first postal code recorded for each individual (seq_no = 1).

 

I managed to figure it out and thought I would post the answer just in case anyone has the same issue. 

 

Here's the code: 

 

input

data have;
input patient_id Seq_num post_code $;
cards;1 4 M4F
1 2 M4R
1 3 M4R
1 1 AAA
2 1 BBB
2 3 M4X
2 2 M4T
3 1 CCC
3 2 M4M
4 1 DDD;
run;

proc sort;
by patient_id seq_no;
run;

data work.sorted;
set work.have;
by patient_id;
retain pcfixed;
if first.patient_id then pcfixed=post_code;
run; 

Which produces an output of:

Patient_ID Seq_no Post_code pcfixed
       1      4      M4F       AAA
       1      2      M4R       AAA
       1      3      M4R       AAA
       1      1      AAA       AAA
       2      1      BBB       BBB
       2      3      M4X       BBB
       2      2      M4T       BBB
       3      1      CCC       CCC
       3      2      M4M       CCC
       4      1      DDD       DDD

hopefully this helps someone trying to do a similar thing in the future! 

 

Mike 

Super User
Posts: 10,313

Re: Re-coding variables to match the first instance of that variable for a given record

Posted in reply to righcoastmike
An alternative way.





data have;
input patient_id Seq_num post_code $;
cards;
1 4 M4F
1 2 M4R
1 3 M4R
1 1 AAA
2 1 BBB
2 3 M4X
2 2 M4T
3 1 CCC
3 2 M4M
4 1 DDD
;
run;
data want;
 merge have have(keep=patient_id Seq_num post_code
rename=(Seq_num=_seq post_code=pcfixed ) where=(_seq=1));
by patient_id;
drop _:;
run;


Ask a Question
Discussion stats
  • 1 reply
  • 99 views
  • 2 likes
  • 2 in conversation