Remove letters in zip code

Accepted Solution Solved
Reply
Frequent Contributor
Posts: 122
Accepted Solution

Remove letters in zip code

I have a variable zipcode in my file. I want to do two things. First, there are some observations that start with States, for example, CA 92126. I want to get rid of CA to show only 92126. Second, there are some zip codes that include four digits sub zip, for example, 33180-3123. I want to get rid of the last four digits, only keep 33180. Please help. Thanks.perl


Accepted Solutions
Solution
‎10-13-2013 01:40 PM
PROC Star
Posts: 7,356

Re: Remove letters in zip code

Another way might be:

data have;

  informat zip $12.;

  input zip &;

  cards;

CA 92126

33180-3123

15217

;

data want;

  set have;

  zip=substr(compress(zip,,'kd'),1,5);

run;

View solution in original post


All Replies
Contributor
Posts: 64

Re: Remove letters in zip code

Data want;

set have;

Pin1=input(substr('CA 92126', 3),best12.);

pin2=input(scan('33180-3123',1,'-'));

If pin1=. then pin1=pin2;

run;

Solution
‎10-13-2013 01:40 PM
PROC Star
Posts: 7,356

Re: Remove letters in zip code

Another way might be:

data have;

  informat zip $12.;

  input zip &;

  cards;

CA 92126

33180-3123

15217

;

data want;

  set have;

  zip=substr(compress(zip,,'kd'),1,5);

run;

Frequent Contributor
Posts: 122

Re: Remove letters in zip code

Thanks for the answer. One more question, the second argument in compress (space here) will eliminate spaces everywhere, including beginning and ending ones?

PROC Star
Posts: 7,356

Re: Remove letters in zip code

Kind of .. sort of.  Yes they are removed by the second argument but SAS will right pad with spaces anyhow to fill the length of the field.  If you really don't want any spaces, and all of your entries will have 5 characters, I would simply use the code to create a new variable with a length of $5.

data have;

  informat zip $12.;

  input zip &;

  cards;

CA 92126

33180-3123

15217

;

data want (drop=_Smiley Happy;

length zip $5;

  set have (rename=(zip=_zip));

  zip=substr(compress(_zip,,'kd'),1,5);

run;

Frequent Contributor
Posts: 122

Re: Remove letters in zip code

Thanks. Then there will be a question if I want to merge by some name variables. For example, I have a name James Bond in set 1, and James Bond in set 2. I want to merge them together. But name variable in set 1 is $20. and name variable in set 2 is $30. Will SAS treat this name observation James Bond as match?

PROC Star
Posts: 7,356

Re: Remove letters in zip code

Typically, probably.  However, if the file with the shorter lengths is specified first in the merge, you will get a warning:

WARNING: Multiple lengths were specified for the BY variable name by input data sets. This may

         cause unexpected results.

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 6 replies
  • 690 views
  • 4 likes
  • 3 in conversation