Serge Kashlik
Serge Kashlik

Reputation: 413

How to add commas to a list of variables in SAS

I am new to SAS so please forgive my ignorance if this question seems simple (in other languages it is a rather trivial task). How can I convert a list of variables within a %Macro:

%Let var_list = var1 var2 var3

Into this

"var1","var2","var3"

Upvotes: 2

Views: 2973

Answers (4)

Gaadek
Gaadek

Reputation: 159

Let me share a little bit improved version, with pure SAS macro code:

%let var_list = var1 var2 var3;
%put &var_list.; /* var1 var2 var3 */
%let new_var_list = "%sysfunc(prxchange(s/\s+/"%str(,)"/, -1, &var_list.))";
%put &new_var_list.; /* "var1","var2","var3" */

A little bit easier to read/understand than Kermit's proposal which is pretty good of course!

Upvotes: 0

Tom
Tom

Reputation: 51621

This is a FAQ but I did not find another question to link to. You can use the TRANWRD() function to convert the spaces into "," (as long as the resulting string is less that data step maximum of 32,767 bytes). Make sure to reduce multiple spaces to one.

%let var_list = var1   var2   var3 ;
%put "%sysfunc(tranwrd(%sysfunc(compbl(&var_list)),%str( ),%str(",")))" ;

Results:

"var1","var2","var3"

Upvotes: 1

Kermit
Kermit

Reputation: 3117

Without using the SASjs Macro Core library:

%let var_list = var1 var2 var3;
%let var_list=%bquote(")%qsysfunc(prxchange(s/\s+/%nrbquote(",")/,-1,&var_list))%bquote(");
%put &=var_list.; /* VAR_LIST="var1","var2","var3" */

Upvotes: 1

Allan Bowe
Allan Bowe

Reputation: 12701

You can use the mf_getquotedstr() function from the SASjs Macro Core library and do it in one line:

%Let var_list = var1 var2 var3;

%put %mf_getquotedstr(&var_list,quote=D); /* D for Double quote */

enter image description here

Upvotes: 2

Related Questions