BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
ghosh
Barite | Level 11

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!

1 ACCEPTED SOLUTION

Accepted Solutions
Tom
Super User Tom
Super User

You could use the REPEAT function.

length _id $5;
_id='K'||repeat('0',3-length(kid))||kid;

View solution in original post

3 REPLIES 3
Tom
Super User Tom
Super User

You could use the REPEAT function.

length _id $5;
_id='K'||repeat('0',3-length(kid))||kid;
ghosh
Barite | Level 11
Thanks Tom! Great solution, plus I can adapt it for longer strings.
Ksharp
Super User
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
;

SAS Innovate 2025: Call for Content

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!

Submit your idea!

How to Concatenate Values

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 3 replies
  • 2586 views
  • 2 likes
  • 3 in conversation