I trying to figure out the following: I have SAS dataset 'ids' with character variable with different length such as idnum3, idnum897 or idnum2342345. Need to create each ID with the same length and add leading zeros to have soething like '000000idnum3','0000idnum897', idnum2342345. I tried many options but it seems nothing works. Any suggestions please. Thanks!
-
can you edit your question to show what you've tried? – Ro Yo Mi May 24 '16 at 02:14
3 Answers
Two general approaches are useful here.
First, if the field is entirely numeric, you use the Zw.d
format.
idnum=put(input(idnum,8.),z8.);
If it's not entirely numeric, then you use repeat()
to generate the zeros. Use length()
to find out how many you need. Repeat
takes two arguments - the character to be repeated, and the number of repeats to add to the original. That number will be one less than the intuitive number: repeat('0',3)
= 0000
.
So:
if length(idnum) lt 8 then idnum = cats(repeat('0',8-1-length(idnum)),idnum);
Make sure your ID number variable has enough length to fit the full ID, also, or this won't work.
Longer example:
data have;
input idnum $8.;
datalines;
idn2
idn234
idn23456
;;;;
run;
data want;
set have;
if length(idnum) lt 8 then idnum = cats(repeat('0',8-1-length(idnum)),idnum);
run;

- 62,789
- 6
- 49
- 67
-
Thanks. The code did not produced desired outcome. For example for the 'idnum3' instead of creating '000000idnum3' it produced only '000000'. Please advise. – Marla_learning_sas May 23 '16 at 19:44
-
-
Excellent, great solution, it is exactly what I was looking for. I completely forgot to assign the length --- after that I got the desired output. Thanks! – Marla_learning_sas May 23 '16 at 20:14
I have this issue on a daily basis. The format of Zn. should give you what you need. For example, lets say you have SSN (character numbers) where an individual has a social of 000012345
. If you were to read this in from excel or a text file, you might end up with 12345
. You can use the format of Zn.
to create your leading zeroes -
Data Want;
Set Have;
SSN = PUT(VALUE,Z9.);
RUN;

- 470
- 1
- 4
- 19
-
2Thanks, but this is a character variable, mix of letters and numbers. Z format gives an error "the format $Z was not found or could not be loaded". – Marla_learning_sas May 23 '16 at 19:14
If it's more intuitive, you can also use translate in conjunction with the right function. The idea is that you right-align the values in a field and replace the spaces created with zeros.
data have;
input id $16.;
datalines;
idnum3
idnum897
idnum2342345
;
run;
data want;
set have;
want = translate(right(id), "0", " ");
run;

- 1,120
- 1
- 8
- 14
-
Good idea, I like this one more than the `repeat` function, as long as there aren't meaningful spaces in the ID variable. – Joe May 23 '16 at 19:49