I would like to add trailing zeros to character data in the following way - to fill up to maximum of 7 characters:
133P. -> 133P.00
39B.. -> 39B..00
22EG.-> 22EG.00
R0832 -> R083200
Is there a way to do this?
Many thanks in advance.
Put the length statement before the set statement.
Have you tried my suggested code. The following contains it and a slight variant of @Reeza's code:
data have; input old_var $; cards; 133P. 39B.. 22EG. R0832 ; data want; Length new_var1 new_var2 $7; set have; new_var1='0000000'; substr(new_var1,1,length(old_var))=substr(old_var,1,length(old_var)); new_var2 = substr(Catt(old_var, '0000000'),1,7); run;
Art, CEO, AnalystFinder.com
Length new_var $7;
new_var = Catt(old_var, '0000000');
Add 7 zeroes to the end, but assign a length of 7. This causes the variable to truncate after 7th char meaning you get the variable plus the 0s, as desired.
@Dani08 wrote:
Thank you for your reply.
is it important where I put the length statement?
If I place it before the set statement, the new_var is blank,
if I place it after the set statement, I get 7 trailing '0's at the end...
please let me know if I am doing something wrong.
Did you include a $ sign? If not then your new_var was numeric and wouldn't hold the result of a character value very well.
data want; length New_var $ 7; set yourdataset; New_var = substr(translate(code,'0',''),1,7); run;
Another approach.
Why do you have characters in it? This makes the problem far more complicated than necessary. Instead of just putting the number to Zx. format, you now need to check length and repeat and concat:
data have; have="33p."; want=cats(have,repeat("0",5-lengthn(have))); run;
It is necessary to have characters in this variable. They are medical read codes.
The following should work:
data want; input have $; want='0000000'; substr(want,1,length(have))=substr(have,1,length(have)); cards; 133P. 39B.. 22EG. R0832 ;
HTH,
Art, CEO, AnalystFinder.com
Put the length statement before the set statement.
Have you tried my suggested code. The following contains it and a slight variant of @Reeza's code:
data have; input old_var $; cards; 133P. 39B.. 22EG. R0832 ; data want; Length new_var1 new_var2 $7; set have; new_var1='0000000'; substr(new_var1,1,length(old_var))=substr(old_var,1,length(old_var)); new_var2 = substr(Catt(old_var, '0000000'),1,7); run;
Art, CEO, AnalystFinder.com
Not sure what your question is. The above approaches are all designed to do the task for all of the records in the file.
Art, CEO, AnalystFinder.com
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.