You can use PROC FREQ with the ORDER=FREQ option in SAS to to create a frequency table in which the categories in the table are sorted based on frequency.
You can use the following syntax to do so:
proc freq data=my_data order=freq;
tables my_variable;
run;
The following example shows how to use this syntax in practice.
Example: Use PROC FREQ with ORDER Option in SAS
For this example we will use the SAS built-in dataset called BirthWgt, which contains various characteristics for 100,000 mothers that recently gave birth.
We can use PROC PRINT to view the first 10 observations from this dataset:
/*view first 10 observations from BirthWgt dataset*/ proc print data=sashelp.BirthWgt (obs=10); run;
We can use the following code to create a frequency table for the Race variable:
/*create frequency table for Race variable*/
proc freq data=sashelp.BirthWgt;
tables Race;
run;
Notice that the categories are currently sorted in alphabetical order.
To instead sort the categories by frequency, we can use the following syntax:
/*create frequency table for Race variable, sorted by frequency*/
proc freq data=sashelp.BirthWgt order=freq;
tables Race;
run;
Notice that the categories are now sorted based on frequency from highest to lowest.
Unfortunately, there is no built-in option to sort the categories based on frequency from lowest to highest.
However, you can use the following workaround with the PROC SORT statement to sort based on frequency from lowest to highest:
/*create frequency table and store results in Racefreq*/
proc freq data=sashelp.BirthWgt noprint;
tables Race / out=Racefreq;
run;
/*sort Racefreq based on frequency from lowest to highest*/
proc sort data=Racefreq;
by count;
run;
/*create new dataset with cumulative freq and cumulative percent*/
data freq_low_to_high;
set Racefreq;
cumcount + count;
cumpercent + percent;
run;
/*view results*/
proc print data=freq_low_to_high;
Notice that the categories are now sorted based on frequency from lowest to highest.
Additional Resources
The following tutorials explain how to perform other common tasks in SAS:
SAS: How to Use PROC FREQ with WHERE Statement
SAS: How to Use PROC FREQ by Group
SAS: How to Use PROC RANK