DATA Step, Macro, Functions and more

Working with Strings

Reply
Occasional Contributor
Posts: 11

Working with Strings

Hi, 

 

I have these observations under the variable "var1":

Members United Swaps With Defendants
Members United Swaps With Other Parties
Southwest Swaps With Defendants
Southwest Swaps With Other Parties
WesCorp Swaps With Defendants
WesCorp Swaps With Other Parties
U.S. Central Swaps With Defendants
U.S. Central Swaps With Other Parties

 

Basically I would like to create a variable "var2" based on "var1"  that looks like this:

With Defendants
With Other Parties
With Defendants
With Other Parties
With Defendants
With Other Parties
With Defendants
With Other Parties

 

Can someone help me out?

 

Thanks.

Frequent Contributor
Posts: 107

Re: Working with Strings

Posted in reply to jrdykstr93
if index(var1,"With Defendants") > 0 then var2="With Defendants";
else var2="With Other Parties";

index() is a character function where the first argument is the string/column you want to search, and second argument is what you want to search for. If that second argument is found, the function returns a number equal to the starting position. Else, it returns 0. So the above looks to see if it contains defendants, and if not, assumes it contains parties. You could add other if else/else logic if necessary.

Trusted Advisor
Posts: 1,848

Re: Working with Strings

Posted in reply to jrdykstr93

 

data want;
 set have;
       length var2 $20;  /* adapt to max length expected */
       var2 = substr(var1, index(var1,'with'));
run;

Check weather you need to check case (upcase / lowcase) of 'with' letters. 

Highlighted
Respected Advisor
Posts: 3,179

Re: Working with Strings

Posted in reply to jrdykstr93

This is to extract and thing after 'with' including 'with',

 

data test;
infile cards truncover ;
input var1 $100.;
new_var=prxchange('s/.+(with.+)/$1/io',-1,var1);
cards;
Members United Swaps With Defendants
Members United Swaps With Other Parties
Southwest Swaps With Defendants
Southwest Swaps With Other Parties
WesCorp Swaps With Defendants
WesCorp Swaps With Other Parties
U.S. Central Swaps With Defendants
U.S. Central Swaps With Other Parties
;
run;
Super Contributor
Posts: 328

Re: Working with Strings

Posted in reply to jrdykstr93

You may also use the @'character' column pointer.

data test;
infile cards truncover ;
input @'Swaps' new_var &$20.;
cards;
Members United Swaps With Defendants
Members United Swaps With Other Parties
Southwest Swaps With Defendants
Southwest Swaps With Other Parties
WesCorp Swaps With Defendants
WesCorp Swaps With Other Parties
U.S. Central Swaps With Defendants
U.S. Central Swaps With Other Parties
;
run;

Cheers.

Super User
Posts: 10,844

Re: Working with Strings

Posted in reply to jrdykstr93

Better to use FINDW()  function .

Ask a Question
Discussion stats
  • 5 replies
  • 82 views
  • 7 likes
  • 6 in conversation