Search This Blog

Loading...

Friday, February 5, 2010

How to add leading zeros to numeric variables

Have you ever asked to create a variable with leading zeros? I mean 1 to 001 and 2 to 002. If you were, do you know how....

SAS has a special numeric format Zw.d. which can include leading zeros.

Zw.d Format in which,
w : Width of variable.

d : Decimal Point.
Zw.d format writes standard numeric data with leading 0's. The Zw.d format is similar to the w.d format except that Zw.d pads right-aligned output with 0s instead of blanks. (Ref: SAS 9.2 Language Reference : Dictionary, 4th edition);


Let me give you a scenario where this can be very useful:

You have a variable called site with the numbers as 101, 999, 1001 and 1200. If you want to create a USUBJID variable with fixed length for all the subjects, we need to modify the site variable variables to fixed length. (length=4). You can do that using Z4.d format.

Note: As this is a numeric format, this can be applied to numeric variables only.

*z4.format is used to add the leading zeros to site variable;


data have;
     length site $4;
site='101';  subject='1001';output;
site='129';  subject='1002';output;
site='999';  subject='1003';output;
site='1000'; subject='1004';output;
site='1010'; subject='1005';output;
site='1011'; subject='1006';output;
run;

data want;
length usubjid $19;
set have(rename=(site=sitec));
studyid='ABC10049';
site=put(sitec+0,z4.); *Z4. format is applied after converting the character variable sitec to site; 
usubjid=catx('-',studyid,site,subject);
        keep usubjid site;
run;



Output:


USUBJID                         SITE
ABC10049-0101-1001 0101
ABC10049-0129-1002 0129
ABC10049-0999-1003 0999
ABC10049-1000-1004 1000
ABC10049-1010-1005 1010
ABC10049-1011-1006 1011


You could also use REPEAT function also:

Here is how...

site=catt(repeat('0',3-length(sitec)),sitec);

Please note that the 3 reference to the minimum length of site variable. I have used 3 because the minimum length in the given example is 3.




4 comments:

Anonymous said...

I have Id values like 1 to 100 and i want to add leading zeros 001-099 but not for 100,then how do u add leading zeros.

sarath said...

use length statement.

if num lt 100 then newnum=put(num,z3.);

Anonymous said...

newnum=put(num,z3.);

would work just as well. We don't need to use
'if num lt 100' as by defauly (num,z3) will remain unchanged for a variable that is already length 3

Anonymous said...

It will add 0 only when length is not 3, for 100 length is already 3..you can use newnum=put(num,z3.); directly

Post a Comment

ShareThis