Search code examples
sasrename

Create a sequence of new column names


I have a hundred or so columns which I would like to rename in SAS using the following macro:

%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;

The columns are currently named C5, C7, C9, ..., C205 and I would like to rename them AR_0, AR_1, ..., AR100.

With the macro above, how can I put these new names after the comma of the following code without writing each and every one of them?

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

Solution

  • This is a bit of a longer solution, but it's fairly dynamic and you easy to see how things work. I'm assuming you'll use the rename statement in proc datasets. Otherwise you could just be lazy and use arrays to replace then drop the old variables, though that isn't efficient.

    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;