Search code examples
rcountranking

Find the n most common values in a vector


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?


Solution

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

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