Hello,
I'm trying to perform an operation where if a certain variable has a missing value, it ends up getting the value of some other variable. But in addition to that, the new value created should be filled up with leading zeros to make the size of the missing variable a certain length.
For eg., the value of my variable id (char 19.) is null, so it needs to get the value of its corresponding 'prod'(num 12.) which in this case is 123. so my id value should be 0000000000000000123.
To do this, I'm using this logic:
if id = null then
id=cats(repeat('0',19-length(prod)-1), prod);
However, since the output I'm getting is 0000000123 instead of 0000000000000000123 because the defined length of the 'prod' var is 12. which is set based on the max size of 'prod'. So the length function comes out to be 12 instead of the true length of 'prod' which could be anything upto 12. How do I make my code to see the true length of each prod value rather than the defined length?
Or if there is a better way to perform this operation, I'd appreciate learning about it.
Thank you.
Hello @AJ_Brien,
@AJ_Brien wrote:
Or if there is a better way to perform this operation, I'd appreciate learning about it.
The standard way of writing numeric values with leading zeros is to use the Zw.d format (see example below). An explicit numeric-to-character conversion using the PUT function avoids the annoying "NOTE: Numeric values have been converted to character values ..." in the log.
Also, the IF condition "id = null" will produce a log message "NOTE: Variable null is uninitialized." and a new variable (null), unless null is an existing variable. To check if character variable id is missing, you can use one of several functions (including MISSING, CMISS and LENGTHN) or compare id to a blank character constant:
if id=' ' then id=put(prod, z19.);
It seems you are working very hard to do something you don't need to do. To produce a string with leading zeros from a number use the Z format.
if missing(id) then id=put(prod,z19.);
Or use the COALESCEC() function and eliminate the IF/THEN.
id=coalescec(id,put(prod,z19.));
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.