Re-ordering variables

From sasCommunity

Jump to: navigation, search

There are many ways of changing the ordering of variables in SAS. The basic rule is the "Rule of First Encounter:" the first time that SAS encounters a variable in the course of the construction of a new dataset determines the order in which that variable is entered into the new dataset.

So, to change the order of variables, you must change the order in which SAS encounters variables.

Define a dataset:

DATA OLD;
     A=1; B=2; C=3; OUTPUT;
RUN;

In this dataset, variables are in order A B C.

DATA NEW;
     SET OLD;
     LENGTH B A C 3;
RUN;

Variables are still in order A B C, since they are first encountered in Dataset OLD, and that sets the ordering for dataset NEW.

To change the order, ensure that the new order is encountered first:

DATA RENEW;
     LENGTH B A C 3;
     SET OLD;
RUN;

Now Dataset RENEW has a new ordering.

As mentioned earlier any Statement that lists the variables in the desired order before any other Statement will reorder the variables in the newly created Dataset. The most common are the Retain, Length, Attrib, Label, and Format Statements. So which one is considered the safest to use, well that distinction falls to the Retain Statement. The reason for this is all variables coming from a input Dataset are automatically Retained. As such using a Retain Statement to reorder variables in a Dataset has no unintended side effect. All other Statements require the programmer to specify some attribute of each variable.

DATA RENEW;
     RETAIN B A C;
     SET OLD;
RUN;

[Following paragraphs started out as a separate article, so some integration is needed.]

Q: How do I change the order of variables in my data set?

or

How can I reorder variables in data set?

A-1: use retain statement

DATA   Order_I_Want;
retain Var6 Var9 Var2 Var4;
set    Libref.data;

note: easy, variable type (C,N) does not matter

caveat: DO NOT use assignment statements

A-2: use attribute statement

DATA   Order_I_Want;
attrib Var6 
       Var9 
       Var2 
       Var4;
set    Libref.data;

note-1: can add or change other attributes like type and label;

note-2: assignment statements ok.

see also: Attribute_statement


Personal tools