I have large SAS dataset that has spaces in the variable name. I wish to replace the space with underscore. For Example Bus City = Bus_City.
I found this macro in the formun that removes the spaces only. Using the above example, this macro does this: Bus City =BusCity Can someone please help me modify this macro to replace the space with underscore.
data sample;
set sashelp.class;
age_student=age;
'gender - student'n=sex;
run;
%macro rename_vars(table, remove_char);
%let table=%upcase(&table);
%let rename_list=;
proc sql noprint;
select cats("'",name,"'n =",compress(name, "&remove_char")) into :rename_list
separated by " "
from sashelp.vcolumn
where upper(libname)="%scan(WORK.&table,-2)"
and upper(memname)="%scan(&table,-1)"
and findc(strip(name), "&remove_char")>0;
quit;
%put rename_list: %bquote(&rename_list);
%if %bquote(&rename_list) ne %then
%do;
proc datasets lib=%scan(WORK.&table,-2);
modify %scan(&table,-1);
rename &rename_list;
run;
quit;
%end;
%mend;
/* call the macro. First parameter is the table name,
second parameter the characters to be removed in variable names */
%rename_vars(sample,' ');
Just change the function used to generate the new name.
translate(trim(name),'_',' ')
You can also simplify the whole macro.
%macro rename_vars(table);
%local rename_list sqlobs;
proc sql noprint;
select catx('=',nliteral(name),translate(trim(name),'_',' '))
into :rename_list separated by ' '
from sashelp.vcolumn
where libname=%upcase("%scan(work.&table,-2,.)")
and memname=%upcase("%scan(&table,-1,.)")
and indexc(trim(name),' ')
;
quit;
%if &sqlobs %then %do ;
proc datasets lib=%scan(WORK.&table,-2);
modify %scan(&table,-1);
rename &rename_list;
run;
quit;
%end;
%mend rename_vars;
Just change the function used to generate the new name.
translate(trim(name),'_',' ')
You can also simplify the whole macro.
%macro rename_vars(table);
%local rename_list sqlobs;
proc sql noprint;
select catx('=',nliteral(name),translate(trim(name),'_',' '))
into :rename_list separated by ' '
from sashelp.vcolumn
where libname=%upcase("%scan(work.&table,-2,.)")
and memname=%upcase("%scan(&table,-1,.)")
and indexc(trim(name),' ')
;
quit;
%if &sqlobs %then %do ;
proc datasets lib=%scan(WORK.&table,-2);
modify %scan(&table,-1);
rename &rename_list;
run;
quit;
%end;
%mend rename_vars;
Thank you Tom. The simplify Macro works!!!
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!
Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.
Find more tutorials on the SAS Users YouTube channel.