AlJones1816
AlJones1816

Reputation: 45

How to remove suffixes from a set of addresses

I have a data set containing a list of street addresses. Some of these addresses end in a suffix like "AVE" or "ROAD". I want to remove any of these suffixes that appear in the list of addresses. My approach is to use a Do loop to step through a list.

%macro suffixes(field=,newfield=);
%let suffix = AV AVE AVENUE BEACH BLUFF BLVD BOULEVARD;

%let nwords=%sysfunc(countw(&suffix));

%do i=1 %to &nwords;
%let suff=%scan(&suffix,&i);
%let sufflen=%length(&suff);
%if %substr(&field,%length(&field)-&sufflen)=&suff
    %then &newfield=%substr(&field,1,%length(&field)-&sufflen+1);

%end;
%mend;

data addresses_no_suffix;
set addresses_full;

%suffixes(field=addresses,newfield=new_addr);

run;

I'm kind of stuck, as the above approach doesn't work, even though all the individual "pieces" seem to work on their own (the "if/then" logic works in the datastep outside of the macro, for instance). Any ideas about how to make this work better or help me understand where I'm going wrong would be appreciated.

An example input dataset might look like this:

enter image description here

And the expected output for the above would look like this:

new_addr
123 Brookfield
234 Wonderland
456 Pickup Stix

Edited to correct the macro code I've been trying.

Upvotes: 1

Views: 82

Answers (2)

Shenglin Chen
Shenglin Chen

Reputation: 4554

Not use macro loop:

%let suffix =AV AVE AVENUE BEACH BLUFF BLVD BOULEVARD;

data want;
  set have;
  word=scan(address,-1);
  if findw("&suffix",word,' ','RI')>0 then New_address=tranwrd(address,strip(word),'');
  else New_address=address;
  drop word;
run;

Upvotes: 1

Tom
Tom

Reputation: 51566

Your macro is not generating any lines of SAS code to add to your data step.

You need to replace this macro logic

%if %substr(&field,%length(&field)-&sufflen)=&suff %then &newfield='test';

With some actual SAS code. Probably something like:

if substrn(&field,length(&field)-&sufflen)="&suff" then &newfield='test';

You can turn on the MPRINT option to see in your SAS log the lines of SAS code that your macro generates.

Upvotes: 2

Related Questions