SAS : Reordering Variables

Deepanshu Bhalla 4 Comments

This tutorial explains various ways to reorder variables in SAS, along with examples.

Sample Data

Let's create a sample data for demonstration purpose.

data mydata;
input var3 var1 var2 var4;
cards;
1 3 4 1
2 4 5 2
6 4 5 3
5 3 6 4
;
run;

The RETAIN statement in SAS is used to reorder the variables in a dataset.

data newData;
    retain var1 var2 var3 var4;
    set mydata;
run;

In this example, we have reordered variables in this order - var1, var2, var3 and var4.

SAS : Reordering Variables using RETAIN Statement
How to Move a Variable in SAS

Suppose you want to bring one variable to the front. In this example, we are positioning "var1" as the first variable in the order using the RETAIN statement.

data newData;
    retain var1;
    set mydata;
run;
How to Move a Variable in SAS
Reorder Variables Based on Another Dataset

Suppose you have two datasets with same named variables. You want the order of the variables to be same in both the datasets.

Let's create two datasets
data abc;
input a b c;
cards;
1 3 4
2 4 5
;
run;

data bac;
input b a c;
cards;
1 3 4
2 4 5
;
run;

The following code extracts the column names from the table ABC in the WORK library using PROC SQL and store it in the macro variable "reorder". The RETAIN statement ensures that the order of the variables in the table BAC to be same as ABC.

proc sql noprint;
select name
into :reorder
separated by ' '
from dictionary.columns
where libname="WORK" and
memname="ABC"
order by name;
quit;

data bac;
retain &reorder.;
set bac;
run;

Note : Put library and dataset name in LIBNAME and MEMNAME (in caps) in the above code.

In SAS, the dictionary.columns refers to a system table that stores information about columns of a table.
Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 4 Responses to "SAS : Reordering Variables"
  1. Hi Deepanshu ,
    Will you please expalain above code a bit.

    ReplyDelete
    Replies
    1. it is quite simple. Basically accessing metadata within dictionary.columns table where variable information is stored. He is storing the variable names in a macro variable called 'reorder' ordered by name variable separated by spaces. This macro variable will then have value something like 'a b c'. This is used in the retain statement in the final data step where dataset bac is created again from same bac dataset.

      Delete
  2. yes what is mean by dictionary.columns over here

    ReplyDelete
    Replies
    1. It's metadata repository where column level information is stored.
      Eg memname,libname,varname..

      Try to use ity ou will understand.

      Delete
Next → ← Prev