How to Rename Variables in SAS (With Examples)


You can use the rename function to rename one or more variables in a SAS dataset.

This function uses the following basic syntax:

data new_data;
    set original_data (rename=(old_name=new_name));
run;

The following examples show how to use this function in practice with the following dataset:

/*create dataset*/
data original_data;
    input x y z;
    datalines;
1 4 76
2 3 49
2 3 85
4 5 88
2 2 90
;
run;

/*view dataset*/
proc print data=original_data;

Example 1: Rename One Variable

The following code shows how to rename just the x variable in the dataset:

/*rename one variable*/
data new_data;
    set original_data (rename=(x=new_x));
run;

/*view new dataset*/
proc print data=new_data;

Notice that x has been renamed to new_x, but every other variable name remained the same.

Example 2: Rename Multiple Variables

The following code shows how to rename both the x and y variables in the dataset.

Note that you don’t need to include commas in between the new variable names.

/*rename multiple variables*/
data new_data;
    set original_data (rename=(x=new_x y=new_y));
run;

/*view new dataset*/
proc print data=new_data;

Example 3: Add Prefix to All Variables

The following code shows how to add a prefix of _NEW to all variables in the dataset:

/*define prefix to append to each variable*/
proc sql noprint;
   select cats(name, '=', '_NEW', name)
          into :list
          separated by ' '
          from dictionary.columns
          where libname = 'WORK' and memname = 'ORIGINAL_DATA';
quit;

/*add prefix to each variable in dataset*/
proc datasets library = work;
   modify original_data;
   rename &list;
quit;

/*view updated dataset*/
proc print data=original_data;

Example 4: Add Suffix to All Variables

The following code shows how to add a suffix of _NEW to all variables in the dataset:

/*define suffix to append to each variable*/
proc sql noprint;
   select cats(name, '=', name, '_NEW')
          into :list
          separated by ' '
          from dictionary.columns
          where libname = 'WORK' and memname = 'ORIGINAL_DATA';
quit;

/*add suffix to each variable in dataset*/
proc datasets library = work;
   modify original_data;
   rename &list;
quit;

/*view updated dataset*/
proc print data=original_data;

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Replace Missing Values with Zero in SAS
How to Remove Duplicates in SAS
How to Normalize Data in SAS

Leave a Reply

Your email address will not be published. Required fields are marked *