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!
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With