Hi,
I am trying to build a macro to rename columns by replacing a pattern to another one.
The following code seems to work when all columns names do have the matching pattern but it does not work in case some columns names do not have the matching pattern.
Could you help me to improve my macro ?
Thanks in advance.
Clement
%macro colrename_pattern(table, oldpattern,newpattern);
%local rename_list sqlobs;
proc sql noprint;
select catx('=',nliteral(name),tranwrd(trim(name),&oldpattern,&newpattern))
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),&oldpattern)
;
quit;
%if &sqlobs %then %do ;
proc datasets lib=%scan(WORK.&table,-2);
modify %scan(&table,-1);
rename &rename_list;
run;
quit;
%end;
%mend colrename_pattern;
data faminc;
input famid1 faminc1-faminc12;
cards;
1 3281 3413 3114 2500 2700 3500 3114 -999 3514 1282 2434 2818
2 4042 3084 3108 3150 -999 3100 1531 2914 3819 4124 4274 4471
3 6015 6123 6113 -999 6100 6200 6186 6132 -999 4231 6039 6215
;
run;
%colrename_pattern(faminc,'famid','gfgfgf');
Use INDEX instead of INDEXC:
and index(trim(name),&oldpattern)
INDEXC searches for single characters, while INDEX searches for the whole string.
Use INDEX instead of INDEXC:
and index(trim(name),&oldpattern)
INDEXC searches for single characters, while INDEX searches for the whole string.
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
Check out this tutorial series to learn how to build your own steps in SAS Studio.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.