Hello,
User need to define a list of variables in a macro variable called List_Vars.
I want to create a new macro variable called List_Vars2 that will be same as List_Vars1 but with comma between names.
I want to create a new macro variable called List_Vars3 that will be same as List_Vars1 but before any name there will be "b."
when we Run %put &List_Vars2 we will get wealth,age
when we Run %put &List_Vars3 we will get b.wealth, b.age
What is the way to create List_Vars2 and List_Vars3 automatically?
Please note that in real world the user write many varaibles in List_Vars macro varaible and it will be more efficient that macro varaibles List_Vars2 and List_Vars3 be created automaticaly.
%let List_Vars=wealth age;
Do it in a DATA _NULL_:
%let List_Vars=wealth age;
data _null_;
list_vars = "&list_vars.";
length list_vars2 list_vars3 $1000;
list_vars2 = translate(trim(list_vars),","," ");
do i = 1 to countw(list_vars);
list_vars3 = catx(",",list_vars3,"b."!!scan(list_vars,i));
end;
call symputx("list_vars2",list_vars2,"g");
call symputx("list_vars3",list_vars3,"g");
run;
%put &=list_vars2.;
%put &=list_vars3.;
Do it in a DATA _NULL_:
%let List_Vars=wealth age;
data _null_;
list_vars = "&list_vars.";
length list_vars2 list_vars3 $1000;
list_vars2 = translate(trim(list_vars),","," ");
do i = 1 to countw(list_vars);
list_vars3 = catx(",",list_vars3,"b."!!scan(list_vars,i));
end;
call symputx("list_vars2",list_vars2,"g");
call symputx("list_vars3",list_vars3,"g");
run;
%put &=list_vars2.;
%put &=list_vars3.;
As usually, Maxim 1: Read the Documentation.
Take a look at CALL SYMPUTX Routine
"g" makes sure that the newly created macro variable ends up in the global symbol table (useful if the data_null_ step might be run inside a macro).
Absolutely. But if you later wrap that code in a macro, you might not get your expected behavior.
OTOH, you might want to keep the macro variable within the macro, so you would replace the parameter with "L". Just do not forget about the scope of macro variables.
There are many macros and macro libraries out in the world that deal with macro variables containing a list. A list being a value containing delimited items.
Consider seplist
filename seplist url "https://www.devenezia.com/downloads/sas/macros/download.php?file=seplist.sas"; %include seplist; %let varlist = wealth,age; %let varlist2 = %seplist( %quote(&varlist), indlm=%str(,), prefix=B. ); %put NOTE: &=varlist; %put NOTE: &=varlist2;
will LOG
NOTE: VARLIST=wealth,age NOTE: VARLIST2=B.wealth,B.age
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
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.
Ready to level-up your skills? Choose your own adventure.