BookmarkSubscribeRSS Feed
Ae204
Calcite | Level 5

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_havezip_code_want
91600916
3732237322
345203452
5701-401205701
  
  
  
  
9868298682
1295312953
4631146311
1234; 1234; 23456-444401234; 01234; 23456
84032; 84095; 84065; 8406584032; 84095; 84065; 84065

 

Any suggestions would be greatly appreciated!  Thanks in advance!

 

3 REPLIES 3
ballardw
Super User

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;

 

Ae204
Calcite | Level 5

This worked perfectly - thank you so much!

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

Mastering the WHERE Clause in PROC SQL

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.

Discussion stats
  • 3 replies
  • 582 views
  • 0 likes
  • 3 in conversation