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.
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.
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;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.