DATA Step, Macro, Functions and more

Extract all characters from a variable

Accepted Solution Solved
Reply
Contributor
Posts: 52
Accepted Solution

Extract all characters from a variable

Hello!

I have a (macro) variable with a value in the form

"AB";"AG";"FZ","IE"

of variable length.

I would like to create a new variable with all the characters from my (macro) variable and blanks in between, i.e.

AB AG FZ IE

I tried the SCAN function in a do loop in the DATA step but I got an error because of the ;s in the value of the (macro) variable.

How can I get it done?

Thx,

Stefan


Accepted Solutions
Solution
‎08-16-2012 06:22 AM
Super Contributor
Posts: 349

Re: Extract all characters from a variable

Hi ,

Try this..Hope it helps...

%let x=%str("AB";"AG";"FZ","IE");

%let xx1 =%sysfunc(compbl(%sysfunc(translate(&x,' ','" ; ,'))));

Thanks,

Shiva

View solution in original post


All Replies
Solution
‎08-16-2012 06:22 AM
Super Contributor
Posts: 349

Re: Extract all characters from a variable

Hi ,

Try this..Hope it helps...

%let x=%str("AB";"AG";"FZ","IE");

%let xx1 =%sysfunc(compbl(%sysfunc(translate(&x,' ','" ; ,'))));

Thanks,

Shiva

Contributor
Posts: 52

Re: Extract all characters from a variable

Thx, Shiva! What works! What does it do?

Cheers, Stefan

Valued Guide
Posts: 632

Re: Extract all characters from a variable

In this solution the TRANSLATE function is changing the special characters to blanks, and then the COMPBL function converts multiple blanks to a single blank.  There are other functions that could have also been used COMPRESS and DEQUOTE among them.

Also this soution uses single quotes to delineate the text strings in the TRANSLATE function.  When using macro language elements this technique can have unintended consequences.  Macro language quoting functions such as %STR and %BQUOTE, shown below, do not have these issues.

     %let xx2 =%sysfunc(compbl(%sysfunc(translate(&x,%str( ),%bquote(" ; ,)))));

I once had got a number of consulting hours to debug a program, ultimately the problem was found in the following code fragment

     %scan(&name, &i, ' ')

which works fine unless the &name contains an apostrophe such as O'Conner

Contributor
Posts: 52

Re: Extract all characters from a variable

Thx!

☑ This topic is solved.

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

Discussion stats
  • 4 replies
  • 273 views
  • 1 like
  • 3 in conversation