Sample 24696: Reordering variables to be in alphabetical order
Dynamically reorder the variables in a SAS Data set to be in alphabetical order.
Note:
See SN-008395 to learn other ways to reorder variables.
/* Create sample data */
data a;
input x a j z$ q $ ;
datalines;
1 2 3 qwe asd
;
/* Method 1: Using PROC CONTENTS to obtain alphabetical order for variable names */
/* Use PROC CONTENTS to generate an output data set, keeping only the variable names, */
/* which are output in alphabetical order. */
proc contents data=a out=newa(keep=name);
run;
/* Create macro variables for each variable name, and a count of the number of variables */
data _null_;
set newa end=last;
i+1;
call symput('var'||trim(left(put(i,8.))),trim(name));
if last then call symput('total',trim(left(put(i,8.))));
run;
/* Use a macro DO loop to generate the names of the variables on a RETAIN statement. */
/* Placing the variable names on a RETAIN statement prior to the SET statement */
/* ensures the variables are placed in the PDV in that order. */
/* */
/* If you do not need to permanently reorder the variables, just print them in */
/* alphabetical order, you can use the macro DO LOOP on a VAR statement in PROC PRINT.*/
%macro test;
data final;
retain %do j=1 %to &total;
&&var&j
%end;;
set a;
run;
proc print;
run;
%mend test;
/* Invoke the macro */
%test
/* Method 2: Use SQL dictionary tables to create alphabetical list of variable names */
/* Use same starting data set created above, WORK.A. Note the values of MEMNAME and */
/* LIBNAME need to be in upper case. */
proc sql noprint;
select distinct name
into : varlist separated by ' '
from dictionary.columns
where libname='WORK' and memname='A';
quit;
/* Write macro variable value to the log to see the results */
%put &varlist;
/* If you want to permanently reorder the variables in the data set to be in */
/* alphabetical order, you can call the macro variable &varlist on a RETAIN statement */
/* prior to the SET statement when you create the new data set. If you only want to */
/* print them in alphabetical order, you can use the macro variable &varlist on a VAR */
/* statement in PROC PRINT. */
Obs a j q x z
1 2 3 asd 1 qwe
Dynamically reorder the variables in a SAS Data set to be in alphabetical order.
| Type: | Sample |
| Topic: | SAS Reference ==> DATA Step Common Programming Tasks ==> Utilities
|
| Date Modified: | 2006-08-05 03:02:48 |
| Date Created: | 2004-09-30 14:09:05 |
Operating System and Release Information
| SAS System | Base SAS | All | n/a | n/a |