I have a dataset that has census tract fips codes, but the leading 0 is getting cut off. I was able to put a leading 0 in front of the county fips code using substr and length, but the same thing is not working for census tract. I keep getting errors.
Basically, I have ct fips that look like this:
1001020100
1001020200
24006840030
24007850040
And I want it to look like this (notice that the last two remain the same as they already have 11 digits);
01001020100
01001020200
24006840030
24007850040
I want to leave these as character variables. In the code, I put
data want;
set have;
ct = substr(ctfips, length(ctfips)-10, 11);
drop ctfips;
rename ct = ctfips;
run;
Not sure if that's what I need to be doing, but it's not giving the leading zero for a total length of 11. Thanks!
Modified previous solution to fit what you are doing. https://communities.sas.com/t5/SAS-Procedures/how-to-pad-character-variable-with-leading-zeroes/td-p...
data test;
length charvar $ 11 padded $ 11;
infile datalines;
input charvar;
/* read charvar as number, then format with leading zeroes */
/* then put result into padded */
padded = put(input(charvar,best11.),z11.);
datalines;
1001020100
1001020200
24006840030
24007850040
;
run;
Modified previous solution to fit what you are doing. https://communities.sas.com/t5/SAS-Procedures/how-to-pad-character-variable-with-leading-zeroes/td-p...
data test;
length charvar $ 11 padded $ 11;
infile datalines;
input charvar;
/* read charvar as number, then format with leading zeroes */
/* then put result into padded */
padded = put(input(charvar,best11.),z11.);
datalines;
1001020100
1001020200
24006840030
24007850040
;
run;
Oh yes indeed. Honestly, I didn't pay attention to whether the OP wants the same input variable value to be modified rather than a new assignment. Very good and important point
If the values can actually be converted to integers then you can use the Z format to convert it back with leading zeros. So use INPUT() to convert to a number and PUT() to convert back to string.
ctfips = put(input(ctfips,11.),Z11.);
Now if the values either contain non-digit characters, or there are more than 15 characters then you will want to use character operations instead. Such as moving the spaces to the front and replacing them with zeros.
ctfips = translate(right(substr(ctfips,1,11)),'0',' ');
Or prefixing zeros.
if length(ctfips) < 11 then ctfips = repeat('0',11-length(ctfips)-1)||ctfips;
Or
ctfips = reverse(substr(reverse(cats(repeat('0',11-1),ctfips)),1,11));
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.