Find the n most common values in a vector

ChairmanMeow picture ChairmanMeow · Jun 29, 2013 · Viewed 94.3k times · Source

I have a vector say

c(1,1,1,1,1,1,2,3,4,5,7,7,5,7,7,7)

How do I count each element, and then return the e.g. 3 most common elements, i.e. 1, 7, 5?

Answer

Thomas picture Thomas · Jun 29, 2013

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

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