BookmarkSubscribeRSS Feed
StickyRoll
Fluorite | Level 6

Is there a way to convert a macro variable with multiple values (in a long string) into multiple macro variables?

I have a macro variable as below.

%let carbrand = bmw ford lincoln honda toyota nissan;

I want to convert it to multiple macro variables as below.

Reading &carbrand. and create new macro variables:
car1=bmw
car2=ford
car3=lincoln
....
....
car6=nissan

all carN are macro variables

So, I can only think of assigning the long string of &carbrand. into a datastep, and by using scan function, assign it into multiple rows in a datastep. Then, using proc sql select into to assign it back to Macro Variables (carN). However, I am sure there is a simpler and faster function to perform that.

 

Seeking for further advice.

3 REPLIES 3
Astounding
PROC Star
Macro language supports that type of a loop. For example, inside a macro definition you could code:

%do n=1 %to 6;
%let car&n = %scan(&carbrand, &n);
%end;

There could be small issues along the way. For example you may need to add inside the loop:

%global car&n;
ballardw
Super User

One way:

%macro dummy;
%let carbrand = bmw ford lincoln honda toyota nissan;

%do i=1 %to %sysfunc(countw(&carbrand));
   %global car&i;
   %let car&i = %scan(&carbrand.,&i);
%end;

%mend;

%dummy;

If you have "words" that include a space you need to use a delimiter in your list and tell the COUNTW and %SCAN functions to use that delimiter.

I have a %global so the variables persist outside of this specific macro. If you need them outside of the macro I would suggest providing the result of count as well as a macro variable so it is available if needed.

Tom
Super User Tom
Super User

There is usually no need to create so many macro variables. 

 

Just use one macro variable to hold the current word from the list.

%let carbrand = bmw ford lincoln honda toyota nissan;
%do index=1 %to %sysfunc(countw(&carbrand,%str( )));
  %let car=%scan(&carbrand,&index,%str( ));
  %* code that uses &CAR for something ;
%end;

 

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 3 replies
  • 618 views
  • 2 likes
  • 4 in conversation