Help using Base SAS procedures

Adding leading zeroes to character variable

Accepted Solution Solved
Reply
Contributor
Posts: 61
Accepted Solution

Adding leading zeroes to character variable

Dear All, 

 

I have a large dataset with diagnosis codes that are up to four digits. I need to make them more uniform by adding zeros preceding the first digit (letter) to make them 4 digits but in a character format. 

 

I've tried this but I end up with all zeros.

 

data diagnosis;

input diagnosis;

datalines;

094

16

E4

;

run;

 

data diagnosis;

set diagnosis;

diagnose=translate(right(diagnosis),'0',' ');

;

run;

 

My desired output would be this:

0094
0016
00E4

 


Accepted Solutions
Solution
‎07-19-2017 06:58 AM
Super User
Posts: 7,758

Re: Adding leading zeroes to character variable

First of all, your first data step won't really work, as you try to create a numeric variable, so add a dollar sign:

data diagnosis;
input diagnosis $;
datalines;
094
16
E4
;
run;

Then try this:

data diagnosis;
set diagnosis;
length newdiag $4;
newdiag = '0000';
substr(newdiag,5-length(diagnosis)) = diagnosis;
drop diagnosis;
rename newdiag=diagnosis;
run;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers

View solution in original post


All Replies
Solution
‎07-19-2017 06:58 AM
Super User
Posts: 7,758

Re: Adding leading zeroes to character variable

First of all, your first data step won't really work, as you try to create a numeric variable, so add a dollar sign:

data diagnosis;
input diagnosis $;
datalines;
094
16
E4
;
run;

Then try this:

data diagnosis;
set diagnosis;
length newdiag $4;
newdiag = '0000';
substr(newdiag,5-length(diagnosis)) = diagnosis;
drop diagnosis;
rename newdiag=diagnosis;
run;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
Contributor
Posts: 61

Re: Adding leading zeroes to character variable

Posted in reply to KurtBremser

Perfect. This works well. 

Super User
Super User
Posts: 7,942

Re: Adding leading zeroes to character variable

data want;
  var="E4";
  want=cats(repeat('0',3-lengthn(var)),var);
run;
Super User
Posts: 10,018

Re: Adding leading zeroes to character variable

data diagnosis;
input diagnosis $;
datalines;
094
16
E4
;
run;
data diagnosis;
set diagnosis;
length newdiag $4;
newdiag = diagnosis;
newdiag= translate(right(newdiag),'0',' ');
run;
☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 289 views
  • 0 likes
  • 4 in conversation