Hello,
I have what is probably a very basic question, but I am new to SAS and would love some help figuring it out. I have a file with a list of zip codes, but there could be multiple zip codes associated with each row of data. (If there are multiple zip codes in a row they are separated by a semi-colon.) The way the data currently looks is demonstrated in the column below labeled "zip_code_have" and is a CHAR variable. I need to: 1) add missing zeros to the zip codes that do not have them (in some cases it could be one zero, and others it could be two because there are some territory zip codes in there) and 2) remove the "-" and last four digits of the zip codes that have them. (So it looks like the column "zip_code_want". )
| zip_code_have | zip_code_want |
| 916 | 00916 |
| 37322 | 37322 |
| 3452 | 03452 |
| 5701-4012 | 05701 |
| 98682 | 98682 |
| 12953 | 12953 |
| 46311 | 46311 |
| 1234; 1234; 23456-4444 | 01234; 01234; 23456 |
| 84032; 84095; 84065; 84065 | 84032; 84095; 84065; 84065 |
Any suggestions would be greatly appreciated! Thanks in advance!
First, if possible provide the starting data in the form of data step code as shown below.
Second paste the code in a text box as sometimes code pasted into the main message windows will not run because of reformatting done by the forum software.
This works for your example data:
data have;
infile datalines truncover;
input zip_code_have $30.;
datalines4;
916
37322
3452
5701-4012
98682
12953
46311
1234; 1234; 23456-4444
84032; 84095; 84065; 84065
;;;;
data want;
set have;
/* need to define a length for the zip_code_want
long enough to hold multiple inserted characters
such as missing leading 0 plus the delimiters
*/
length zip_code_want $ 50 z_temp $ 10.;
/* get number of zip codes in file*/
do i=1 to countw(zip_code_have,';');
/* get ONE zip*/
z_temp=scan(zip_code_have,i,';');
if index(z_temp,'-')>0 then z_temp=scan(z_temp,1,'-');
z_temp =put(input(strip(z_temp),5.),z5.);
zip_code_want=catx('; ',zip_code_want,z_temp);
end;
drop z_temp i;
run;
This worked perfectly - thank you so much!
While you're at it, consider splitting those multiple entries into multiple observations. Maxim 19: Long Beats Wide.
Nearly 200 sessions are now available on demand in the Innovate Hub.
Watch Now →SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.