我需要从sas数据开始并获得sas数据。下面是测试数据集。我的实际数据有更多的日期列,所以我不能手动重命名它们。不必重命名前两列(不是日期列)。对于第一个日期列,将其重命名为V1,第二个V2,然后在V3,V4之后重命名。 ......
%macro rename(lib,dsn);
proc sql noprint;
select nvar into :num_vars
from dictionary.tables
where libname="&LIB"
and memname="&DSN";
select distinct(name) into :var1- :var%TRIM(%LEFT(&num_vars))
from dictionary.columns
where libname="&LIB"
and memname="&DSN";
quit;run;
proc datasets library=&LIB;
modify &DSN;
rename %do i=1 %to &num_vars;
&&var&i=V&i.
%end;;
quit; run;
%mend rename;
%rename(WORK,ONE);
评论中包含的代码
pipe.py
答案 0 :(得分:0)
笨重但功能强大:
proc sql;
create table vars as select
name
from dictionary.columns
where memname = upcase("have");
quit;
data vars2;
set vars;
if (_n_ - 2) > 0 then do;
new_name = "V"||strip(_n_ - 2);
end;
else do;
new_name = name;
end;
run;
proc sql noprint;
select name into: old_names
separated by "|"
from vars2;
quit;
proc sql noprint;
select new_name into: new_names
separated by "|"
from vars2;
quit;
%macro renamer;
data want;
set have;
%do i = 1 %to %sysfunc(countw(&old_names.));
rename %scan(&old_names., &i., "|") = %scan(&new_names., &i., "|");
%end;
run;
%mend renamer;
%renamer;
答案 1 :(得分:0)
您的宏很接近,但包含太多内容和一堆错误。
SQLOBS
来保存数字。&
才能正确解析。 <强> 5。您可以通过在导入此数据集之前设置options validvarname=v7
来避免上述所有操作。您还应该以长格式而不是宽格式存储这样的数据。转置和重命名也可能更容易,然后再重新转置。我会把这个解决方案留给别人。
有一些较小的东西,但我会留给你检查代码。下面的代码适合我。
%macro rename(lib,dsn);
proc sql;
select distinct(catt(quote(trim(name)), 'n')) into :var1-
from dictionary.columns
where libname=upper("&LIB")
and memname=upper("&DSN")
and varnum > 2;
quit;
%let num_vars = &sqlobs;
proc datasets library=&LIB;
modify &DSN;
rename %do i=1 %to &num_vars;
&&&var&i=V&i.
%end;;
run; quit;
%mend rename;
%rename(WORK,have);
编辑:改为使用NLITERAL函数:
%macro rename(lib,dsn);
proc sql;
select distinct(nliteral(name)) into :var1-
from dictionary.columns
where libname=upper("&LIB")
and memname=upper("&DSN")
and varnum > 2;
quit;
%let num_vars = &sqlobs;
proc datasets library=&LIB;
modify &DSN;
rename %do i=1 %to &num_vars;
&&&var&i=V&i.
%end;;
run; quit;
%mend rename;
%rename(WORK,have);
答案 2 :(得分:0)
只要您不需要重命名数千个变量,就可以只使用一个宏变量来生成代码。
proc sql noprint;
%let rename=;
select catx('=',nliteral(name),cats('V',varnum-2))
into :rename separated by ' '
from dictionary.columns
where libname='WORK' and memname='HAVE'
and not findw('Name City',name,' ','sir')
;
quit;
data want ;
set have (rename=(&rename)) ;
run;