Sas 如何在不使用原始名称的情况下重命名变量?
我有一个正在上传到sas的数据集。始终有4个变量的顺序完全相同。问题是有时变量的名称可能略有不同 例如,第一个变量Sas 如何在不使用原始名称的情况下重命名变量?,sas,Sas,我有一个正在上传到sas的数据集。始终有4个变量的顺序完全相同。问题是有时变量的名称可能略有不同 例如,第一个变量user。第二天我得到了相同的数据集,它可能是userid。因此,我无法使用重命名(user=my\u user) 我有没有办法按照变量的顺序引用它们。像这样的 重命名(var\u order\u 1=我的用户) 重命名(var\u order\u 3=my\u inc) rename\u ALL\ux1-x4有几种方法可以做到这一点。一种是从PROC CONTENTS或dictio
user
。第二天我得到了相同的数据集,它可能是userid
。因此,我无法使用重命名(user=my\u user)
我有没有办法按照变量的顺序引用它们。像这样的
重命名(var\u order\u 1=我的用户)代码>
重命名(var\u order\u 3=my\u inc)代码>
rename\u ALL\ux1-x4代码>有几种方法可以做到这一点。一种是从PROC CONTENTS
或dictionary.columns
中确定变量名,并生成重命名语句
data have;
input x1-x4;
datalines;
1 2 3 4
5 6 7 8
;;;;
run;
%macro rename(var=,newvar=);
rename &var.=&newvar.;
%mend rename;
data my_vars; *the list of your new variable names, and their variable number;
length varname $10;
input varnum varname $;
datalines;
1 FirstVar
2 SecondVar
3 ThirdVar
4 FourthVar
;;;;
run;
proc sql; *Create a list of macro calls to the rename macro from joining dictionary.columns with your data. ;
* Dictionary.columns is like proc contents.;
select cats('%rename(var=',name,',newvar=',varname,')')
into :renamelist separated by ' '
from dictionary.columns C, my_vars M
where C.memname='HAVE' and C.libname='WORK'
and C.varnum=M.varnum;
quit;
proc datasets;
modify have;
&renamelist; *use the calls;
quit;
另一种方法是使用输入流和\u infle\u
自动变量(参考输入流中的当前行)放置/输入数据。这里有一个例子。当然,如果您愿意,您将只保留新变量
data have;
input x1-x4;
datalines;
1 2 3 4
5 6 7 8
;;;;
run;
data want;
set have;
infile datalines truncover; *or it will go to next line and EOF prematurely;
input @1 @@; *Reinitialize to the start of the line or it will eventually EOF early;
_infile_=catx(' ',of _all_); *put to input stream as space delimited - if your data has spaces you need something else;
input y1-y4 @@; *input as space delimited;
put _all_; *just checking our work, for debugging;
datalines; *dummy datalines (could use a dummy filename as well);
;;;;
run;
下面是使用字典表的另一种方法
data have;
format var1-var4 $1.;
call missing (of _all_);
run;
proc sql noprint;
select name into: namelist separated by ' ' /* create macro var */
from dictionary.columns
where libname='WORK' and memname='HAVE' /* uppercase */
order by varnum; /* should be ordered by this anyway */
%macro create_rename(invar=);
%do x=1 %to %sysfunc(countw(&namelist,%str( )));
/* OLDVAR = NEWVARx */
%scan(&namelist,&x) = NEWVAR&x
%end;
%mend;
data want ;
set have (rename=(%create_rename(invar=&namelist)));
put _all_;
run;
给出:
NEWVAR1= NEWVAR2= NEWVAR3= NEWVAR4=
总体思路是合理的,但我不喜欢这样的宏循环/扫描;我认为与宏调用列表相比,它们往往需要更多的工作。与您的答案相比,我同意。选项1更“可维护”,但选项2得到+1以避免宏!非常感谢。第二个选择很好。它很短,而且不起作用job@Buras请注意,如果以这种方式运行(请使用临时文件或虚拟文件),则批处理文件中不允许使用数据行。谢谢。我实际上打算在批处理文件中运行它。我会用假人的,谢谢!!!