## How to find 3 most frequently occurring values?

Solved
Occasional Contributor
Posts: 5

# How to find 3 most frequently occurring values?

Hello All,

How can I find 3 most frequently occurring values in my dataset using SAS?

Regards,

Aleksandra

Accepted Solutions
Solution
‎08-15-2017 12:55 PM
Super User
Posts: 11,781

## Re: How to find 3 most frequently occurring values?

If you don't need a dataset Proc Freq with the order=freq will generate a table with the most frequent at the top and provide the count at the same time. This also has an advantage of easily adding multiple, or even all variables in a data set with one pass through the data though that can create a lot of output.

Proc freq data=haveorder=freq;

tables variable;

run;

All Replies
Contributor
Posts: 74

## Re: How to find 3 most frequently occurring values?

From one variable or more?  You could probably use the count() function with proc sql, get counts of your values then sort them.

Occasional Contributor
Posts: 8

## Re: How to find 3 most frequently occurring values?

Assuming your data are in mydat and the variable you would like to know the most frequent values of is myvar, you could use:

/* get frequency of myvar in your data set */

proc freq data=mydat;

tables myvar / noprint out=tmp (keep=myvar count);

run;

/* sort in descending order by frequency */

proc sort data=tmp;

by descending count;

run;

/* get the frequency of the third most frequent item, need to do this as there might be multiple value of myvar tied for this value; note that

code will also work if there are fewer than 3 distinct values for myvar in your data set. */

data _NULL_;

set tmp;

if _n_ <= 3 then call symput('maxcount',count);

run;

/* only keep observations with a frequency of maxcount or higher */

data tmp;

set tmp (where=(count >= &maxcount));

run;

proc print data=tmp;

var myvar;

run;

Beate

Solution
‎08-15-2017 12:55 PM
Super User
Posts: 11,781

## Re: How to find 3 most frequently occurring values?

If you don't need a dataset Proc Freq with the order=freq will generate a table with the most frequent at the top and provide the count at the same time. This also has an advantage of easily adding multiple, or even all variables in a data set with one pass through the data though that can create a lot of output.

Proc freq data=haveorder=freq;

tables variable;

run;

Posts: 2,655

## Re: How to find 3 most frequently occurring values?

That was the technique I was looking for, , when I came up with the other post on the other fork of this thread.  If I could hand out a Correct, you'd get it.

Steve Denham

SAS Super FREQ
Posts: 3,835