Find the n most common values in a vector

I don't know if this is better than the table approach, but if your list is already a factor then its summary method will give you frequency counts:

> summary(as.factor(c(1,1,1,1,1,1,2,3,4,5,7,7,5,7,7,7)))
1 2 3 4 5 7 
6 1 1 1 2 5 

And then you can get the top 3 most frequent like so:

> names(sort(summary(as.factor(c(1,1,1,1,1,1,2,3,4,5,7,7,5,7,7,7))), decreasing=T)[1:3])
[1] "1" "7" "5"

I'm sure this is a duplicate, but the answer is simple:

sort(table(variable),decreasing=TRUE)[1:3]

Tags:

R

Count

Ranking