Morning Folks,
I'm just wondering is this is possible. I have multiple historic datasets which have naming conventions such as follows 'Underlying Code 'Age Group'.
Is it possible to write some code to pull all the variable names out of my dataset and any which have a space in them to replace them with an underscore. So 'Underlying Code' would be renamed to 'Underlying_Code' etc.
Any help would be welcome.
All the best,
Sean
options validvarname=any;
data fake;
'Underlying Code'n=12;
'Age Group'n=4;
noblank=0;
run;
proc sql noprint;
select cats('"',name,'"n=',translate(trim(name),'_',' ')) into :renames separated by ' '
from dictionary.columns where libname='WORK' and memname='FAKE' and find(trim(name),' ')>0;
quit;
%put &=renames;
proc datasets library=work nolist;
modify fake;
rename &renames;
run; quit;
options validvarname=v7;
options validvarname=any;
data fake;
'Underlying Code'n=12;
'Age Group'n=4;
noblank=0;
run;
proc sql noprint;
select cats('"',name,'"n=',translate(trim(name),'_',' ')) into :renames separated by ' '
from dictionary.columns where libname='WORK' and memname='FAKE' and find(trim(name),' ')>0;
quit;
%put &=renames;
proc datasets library=work nolist;
modify fake;
rename &renames;
run; quit;
options validvarname=v7;
Here a variant for the same. Main difference besides the macro is the use of function nvalid() to test for any non-compliant character and prxchange() to then translate any non-compliant character to an underscore
%macro renameVars(ds);
%local lib tbl rename_list;
%let lib=%upcase(%scan(work.&ds,-2,.));
%let tbl=%upcase(%scan(work.&ds,-1,.));
%let rename_list=;
proc sql noprint;
select cats("'",name,"'n =",prxchange('s/[^\w]/_/oi',-1,strip(name)))
into :rename_list separated by ' '
/* select **/
from dictionary.columns
where
libname="&lib"
and memname="&tbl"
and memtype='DATA'
and nvalid(name,'v7')=0
;
quit;
%if %nrbquote(&rename_list) ne %nrbquote() %then
%do;
proc datasets lib=&lib nolist nowarn;
modify &tbl;
rename &rename_list;
run;
quit;
%end;
%mend;
data work.have;
set sashelp.class;
'var 2 x'n =1;
'var_other$5'n=20;
run;
%renameVars(have);
proc contents data=work.have;
run;quit;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
What’s the difference between SAS Enterprise Guide and SAS Studio? How are they similar? Just ask SAS’ Danny Modlin.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.