I would like to convert a char variable (KID) consisting of one or two digits and sometimes a letter appended to it, into a 5 digit character string starting with the letter K followed by the existing variable with zeroes inserted in between (_ID). Ideally I would like to use a user-defined format to do the conversion or perhaps a more efficient approach than what I currently have:
Select;
When (length(KID)=1) Pad='000';
When (length(KID)=2) Pad='00';
otherwise Pad='0';
End;
_ID = cats('K',Pad,KID);
Here are the Have (KIDS) and Want (_ID) variables:
KID _ID
1a K001a
1b K001b
2a K002a
2b K002b
3 K0003
4 K0004
5 K0005
6 K0006
7 K0007
8 K0008
9 K0009
10 K0010
11 K0011
11a K011a
11b K011b
12a K012a
12b K012b
Thanks!
You could use the REPEAT function.
length _id $5;
_id='K'||repeat('0',3-length(kid))||kid;
You could use the REPEAT function.
length _id $5;
_id='K'||repeat('0',3-length(kid))||kid;
data have;
input KID $ _ID $;
length temp $ 4;
temp=kid;
want=cats('K',translate(right(temp),'0',' '));
cards;
1a K001a
1b K001b
2a K002a
2b K002b
3 K0003
4 K0004
5 K0005
6 K0006
7 K0007
8 K0008
9 K0009
10 K0010
11 K0011
11a K011a
11b K011b
12a K012a
12b K012b
;
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.