sas

Reorder columns in a SAS dataset


I have the following dataset:

ID X1 X2 Xn Y1 Y2 Yn
IC 01 2 4 5 5 9 8
IC 02 1 5 8 3 4 7

And i would like to have the following:

ID X1 Y1 X2 Y2 Xn Yn
IC 01 2 5 4 9 5 8
IC 02 1 3 5 4 8 7

I used the transpose function in SAS EG but I could not find the right way to order my columns in the following order -> X1 - Y1 - X2 - Y2 - X3 - Y3 - ... - Xn - Yn

Any recommendations are welcome

Thanks!


Solution

  • Just define the variables in the order you want.

     data want;
        length ID $8 X1 Y1 X2 Y2 ..... Xn Yn 8;
        set have;
     run;
    

    Or perhaps you can take advantage of the fact that using a RETAIN statement will force SAS to set the position of the variable, but not the type.

     data want;
        retain ID X1 Y1 X2 Y2 ..... Xn Yn ;
        set have;
     run;
    

    If you are too lazy to type all of the variable names then just generate them. Perhaps with a data step:

    data _null_;
       do i=1 to 20;
         put 'X' i 'Y' i @ ;
       end;
    run;
    

    Then just copy the list from the log and paste it back into your program.

    Or you could use macro code to generate the list:

     %macro names(n);
       %local i;
       %do i=1 %to &n; X&i Y&i %end;
     %mend names;
     data want;
        retain ID %names(10) ;
        set have;
     run;