suppose the variable names have no any pattern, like the following:
data test;
input _X A1 _10 _B;
cards;
1 2 3 4
;
I want to rename the variable names so that the new variable names will be: Var1, Var2, Var3 and Var4.
Instead of rename each variable one by one, is there any other way?
data have;
input _X A1 _10 _B;
cards;
1 2 3 4
5 6 7 8
;
run;
data _null_;
set sashelp.vcolumn(where=(libname='WORK' and memname='HAVE')) end=eof;
call symput('r' !! strip(put(_n_,best.)),name);
if eof=1 then call symput('nobs',put(_n_,best.));
run;
data _null_;
length vars $512;
retain vars;
do i=1 to &nobs;
if i=1 then vars='';
rname=compress(symget("r" !! strip(i)) !! '=var' !! i,' ');
vars=catx(' ', of vars rname);
if i=&nobs then call symput('vars',vars);
end;
run;
proc datasets lib=work nolist;
modify have;
rename &vars;
quit;
run;
data have;
input _X A1 _10 _B;
cards;
1 2 3 4
5 6 7 8
;
run;
data _null_;
set sashelp.vcolumn(where=(libname='WORK' and memname='HAVE')) end=eof;
call symput('r' !! strip(put(_n_,best.)),name);
if eof=1 then call symput('nobs',put(_n_,best.));
run;
data _null_;
length vars $512;
retain vars;
do i=1 to &nobs;
if i=1 then vars='';
rname=compress(symget("r" !! strip(i)) !! '=var' !! i,' ');
vars=catx(' ', of vars rname);
if i=&nobs then call symput('vars',vars);
end;
run;
proc datasets lib=work nolist;
modify have;
rename &vars;
quit;
run;
Here is one example, using dictionary.columns and VARNUM to create the new name.
1824 proc sql noprint;
1825 select catx('=',name,cats('var',varnum)) into :rename separated by ' '
1826 from dictionary.columns
1827 where libname eq 'SASHELP' and memname eq 'HEART';
1828 quit;
NOTE: PROCEDURE SQL used (Total process time):
real time 0.00 seconds
cpu time 0.00 seconds
1829 run;
1830 %put NOTE: RENAME=&rename;
NOTE: RENAME=Status=var1 DeathCause=var2 AgeCHDdiag=var3 Sex=var4 AgeAtStart=var5
Height=var6 Weight=var7 Diastolic=var8 Systolic=var9 MRW=var10 Smoking=var11
AgeAtDeath=var12 Cholesterol=var13 Chol_Status=var14 BP_Status=var15 Weight_Status=var16
Smoking_Status=var17
Try this: not test
data class; set sashelp.class; run; data _null_; set sashelp.vcolumn(keep=libname memname name where=(libname='WORK' and memname='CLASS')) end=last; if _n_ eq 1 then call execute('proc datasets library=work;modify class;rename '); count+1; call execute(strip(name)||'= var'||strip(count)); if last then call execute(';quit;'); run;
Ksharp
Thank you all for great help.
I never realize SASHELP Dictionary Views can be so powerful and thank you all for teaching me.
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.