How to find most frequent element in an array?

Hello
is there a simple way to find the most frequent element in an array?

arr = [1, 3, 2, 1, 4, 1]
# answer should be `1`

I think with Base tools you have either to write something a little more involved or accept a O(n^2) solution. If you can use external libraries then StatsBase has many counting functions: Counting Functions · StatsBase.jl

1 Like

could be a good start.

I have seen that post but countmap does not work on dataframes’s columns

Here is an entry for DataFrames

OK,
I get

julia> arr = [1, 3, 2, 1, 4, 1]
6-element Vector{Int64}:
 1
 3
 2
 1
 4
 1

julia> countmap(arr)
Dict{Int64, Int64} with 4 entries:
  4 => 1
  2 => 1
  3 => 1
  1 => 3

How can I extract 1 => 3?

It seems like you are looking for the mode function:

julia> using StatsBase

julia> mode([1, 3, 2, 1, 4, 1])
1
4 Likes

Or

using StatsBase
arr = [1, 3, 2, 1, 4, 1]
dict = countmap(arr)
@show findmax(dict) 

yielding

findmax(dict) = (3, 1)
1 Like