Search code examples
sasrenaming

How to efficiently rename variables using sas


I got a SAS dataset DATA which contains 100 variables. Unfortunately, this dataset dont contain the name of each variable. It just name the variable as VAR1 - Var100. I got a seperate file which list the name of each variable Name (one name per cell). I donot want to rename it one by one so the following code is not an option.

data lib.test (rename = (var1= truename1 var2 = truename2 ...) ;
   set lib.test;
run;

Following Reeze's suggestions, I try to implement the following solution http://stackoverflow.com/questions/29006915/rename-variable-regardless-of-its-name-in-sas.

proc sql;
   /* Write the individual rename assignments */
   select strip(name) || " = " || substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", varnum , 1)

   /* Store them in a macro variable and separate them by spaces */
   into :vars separated by " "

   /* Use a sas dictionary table to find metadata about the dataset */
   from sashelp.vcolumn
   where libname = "LIB"
     and memname = "TEST"
     and 1 <= varnum <= 100;
quit;

proc datasets lib=lib nolist nodetails;
   modify test;
   rename &vars.;
quit;

Now, instead of using a,b,c,d ... to rename my variable, I want to use the name on datasetName as new names. Dataset Name looks like the following (I can transpose it if it is easier to use). The order of Name is the same as variable sequence in dataset lib.test. How can I change the code above to achieve this?

Name
name1
anc
sjsjd
mdmd

Solution

  • You can convert your NAME dataset to have both the old and new names and then use that to generate the rename pairs.

    data name_pairs;
      set name ;
      old_name = cats('VAR',_n_);
    run;
    
    proc sql noprint ;
      select catx('=',old_name,name)
        into :vars separated by ' ' 
        from name_pairs
      ;
    quit;
    

    You can then use the macro variable VARS in your rename statement.