创建一系列新列名

时间:2014-11-17 11:12:54

标签: sas rename columnname

我有一百个左右的列,我想使用以下宏在SAS中重命名:

%macro rename1(oldvarlist, newvarlist);
  %let k=1;
  %let old = %scan(&oldvarlist, &k);
  %let new = %scan(&newvarlist, &k);
     %do %while(("&old" NE "") & ("&new" NE ""));
      rename &old = &new;
      %let k = %eval(&k + 1);
      %let old = %scan(&oldvarlist, &k);
      %let new = %scan(&newvarlist, &k);
  %end;
%mend;

这些列目前被命名为C5,C7,C9,...,C205,我想将它们重命名为AR_0,AR_1,...,AR100。

使用上面的宏,如何将这些新名称放在以下代码的逗号之后而不编写每个代码?

%rename1(C5--C205, # new names here #);

3 个答案:

答案 0 :(得分:1)

这是一个较长的解决方案,但它相当动态,你很容易看出事情是如何运作的。我假设您将在proc数据集中使用重命名语句。否则你可能只是懒惰并使用数组替换然后删除旧变量,虽然这不是有效的。

proc sql;
    create table oldvar as
    select name, varnum
    from sashelp.vcolumn
    where upcase(libname)='SASHELP' 
        and upcase(memname)='CLASS'
    order by varnum;
quit;

data rename;
    set oldvar;
    new_var=catx("_", "AR",varnum);
run;

proc sql noprint;
    select catx("=", name, new_var) into :rename_list 
                    separated by " "
    from rename;
quit;

%put rename &rename_list;

proc datasets library=work;
modify my_dataset;
rename &rename_list;
run;quit;

答案 1 :(得分:1)

首先找到旧列并将它们重命名为AR_#并创建可以使用的宏变量varlist:

proc sql noprint;
    create table newvar as
    select name
    from sashelp.vcolumn
    where libname="SASHELP" and memname="CLASS"
    order by name;
quit;
data newvar;
  set newvar;
  name=compress("AR_"!!put(_n_,4.));
run;
proc sql noprint;
    select name into :varlist separated by " " 
    from newvar;
quit;

答案 2 :(得分:0)

可能这样的事情可以胜任

%macro rename2(oldvarlist, newPrefix);
%let k=1;
%let old = %scan(&oldvarlist, &k);
  %do %while(("&old" NE ""));
    rename &old = &newPrefix.&k.;
    %let k = %eval(&k + 1);
    %let old = %scan(&oldvarlist, &k);
  %end;
%mend;