How to Reorder Variables in SAS (With Examples)


You can use the RETAIN function in SAS to quickly reorder the variables in a dataset.

Here are the three most common ways to use this function:

Method 1: Reorder All Variables

data new_data;
    retain var4 var5 var1 var3 var2;
    set original_data;
run;

Method 2: Move One Variable to Front

data new_data;
    retain var4;
    set original_data;
run;

Method 3: Move Several Variables to Front

data new_data;
    retain var4 var5;
    set original_data;
run;

The following examples show how to use each method with the following dataset in SAS:

/*create dataset*/
data original_data;
    input team $ points rebounds assists steals;
    datalines;
A 18 10 4 5
B 24 11 6 7
C 26 14 6 8
D 34 22 5 3
E 38 3 7 7
F 45 12 4 4
G 23 7 9 1
;
run;

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

Example 1: Reorder All Variables

The following code shows how to reorder the variables in the following order: team, rebounds, assists steals, then points.

/*create new dataset with variables reordered*/
data new_data;
    retain team rebounds assists steals points;
    set original_data;
run;

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

reorder variables in SAS

Notice that the variables are reordered in the exact order that we specified in the RETAIN function.

Example 2: Move One Variable to Front

The following code shows how to move the assists variable to the front while leaving all other variables in the same order:

/*create new dataset with variables reordered*/
data new_data;
    retain assists;
    set original_data;
run;

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

We can see that the assists variable is now in the first position while all of the other variables remained in the same order.

Example 3: Move Several Variables to Front

The following code shows how to move the assists and rebounds variables to the front while leaving all other variables in the same order:

/*create new dataset with variables reordered*/
data new_data;
    retain assists;
    set original_data;
run;

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

We can see that the assists and rebounds variables are now in the first and second positions while all of the other variables remained in the same order.

Additional Resources

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

How to Use Proc Summary in SAS
How to Use Proc Tabulate in SAS
How to Rename Variables in SAS
How to Create New Variables in SAS

Leave a Reply

Your email address will not be published.