The REPEAT function can be really helpful, especially when you want to add 0’s before a character variable. The REPEAT function, REPEAT(argument, n), returns a character value consisting of the first argument REPEATed n times.
So first, a simple example on how to use the REPEAT function:
data temp;
x=REPEAT('Merry Christmas ', 1);
put x=;
run;
The REPEAT function returns a character value that consist of the first argument repeated n+1 time, hence this output:
![pic1.png pic1.png](https://communities.sas.com/t5/image/serverpage/image-id/52352i6E3826DA1D931059/image-size/large?v=v2&px=999)
The second demonstration show an example on how to add 0’s before a numeric variable ‘y’:
data numeric;
input x y;
cards;
7896 44
5431 243
8934 1
6541 675
;
run;
data temp;
set numeric;
yy = put(y, z5.);
run;
The z5. is adding ‘k’ zeros before the variable y, so the total length of the new variable ‘yy’ is 5. The ‘k’ is calculated as 5 - number of values in the variable ‘y’, and gives us the following results:
![pic2.png pic2.png](https://communities.sas.com/t5/image/serverpage/image-id/52353iBBB1724DD68CA82E/image-size/large?v=v2&px=999)
The Zw.d format doesn’t work on a character variable, so the last example show how to add 0’s before a character variable ‘y’:
data character;
input x y$;
cards;
7896 A44
5431 A243
8934 A1
6541 A675
;
run;
data temp;
set character;
yy = cats(REPEAT('0',5-length(y)-1), y);
run;
The CATS function concatenates 0’s with the variable 'y', while the REPEAT function calculates the repeat of 0’s. The repeat of 0’s is calculated as: 5 - number of letters and values in the variable y - 1. This SAS code gives the following output:
![pic3.png pic3.png](https://communities.sas.com/t5/image/serverpage/image-id/52354i23E2D8D6B81A5516/image-size/large?v=v2&px=999)
Take a look at the autumn/winter 2020 program and events for FANS and other SAS users!
www.sas.com/fans | #SASFANS #sasnordicusers