☑ This topic is solved.
Need further help from the community? Please
sign in and ask a new question.
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
Posted 12-06-2023 06:36 AM
(1376 views)
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
1 ACCEPTED SOLUTION
Accepted Solutions
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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;
--
Paige Miller
Paige Miller
2 REPLIES 2
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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;
--
Paige Miller
Paige Miller
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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;