I have a very simple problem. I'm looking to pad the front of a character value with 0's until it hits a certain length (8). And I do NOT want to use the "z." format. I figured it would be simple like this:
data hello_world;
infile datalines;
input ID $;
cards;
12
234
3456
;;
run;
data hallow_world;
set hello_world;
do while(length(ID)<8);
cats('0',ID);
end;
run;
but is throwing an error. Seems like the only part I have wrong is what is within the do while loop.
So please help - someone can I do this within a "do while"? Also tried like this new_var=cats('0',ID); but it seemed to go into an infinite loop.
Most of the solutions I see online already use the "z." format and I want to avoid this.
Thank you
Or if you want to LOOP
data hello_world;
infile datalines;
input ID $;
cards;
12
234
3456
;;
run;
data want;
set hello_world;
length want_id $8;
want_id=id;
do while(length(want_id)<8);
want_id=cats('0',want_id);
end;
run;
Simple arithmetic
data hello_world;
infile datalines;
input ID $;
cards;
12
234
3456
;;
run;
data want;
set hello_world;
length want_id $8;
want_id=cats(repeat('0',7-length(id)),id);
run;
Or if you want to LOOP
data hello_world;
infile datalines;
input ID $;
cards;
12
234
3456
;;
run;
data want;
set hello_world;
length want_id $8;
want_id=id;
do while(length(want_id)<8);
want_id=cats('0',want_id);
end;
run;
No need for a loop. How about this?
id_zero = cats(substr("00000000", 1, 8-length(id)), id);
Hope this helps,
-- Jan.
If you make ID a numeric variable, this is simple.
data hello_world;
infile datalines;
input ID;
format id z8.;
cards;
12
234
3456
;
data hello_world;
infile datalines;
input ID $;
cards;
12
234
3456
;;
run;
data want;
set hello_world;
length want_id $8;
want_id=id;
want_id=translate(right(want_id),'0',' ');
run;
@Ksharp This ended up being the only one that worked with my real data actually. Thanks!
Hello,
Another solution.
new_ID="00000000";
substr(new_id,9-length(id))=id;
Edit : If some ids have leading blanks :
substr(new_id,9-length(strip(id)))=strip(id);
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.