How to find the value of list mode?

Is there a function in scala collections to find the maximum number of occurrences of a value in a list,

Let's say I have a list

L = List("A","B","B","E","B","E","B","B","C","E","B")

output: "B". 

I can write a module to calculate this, but I would expect that there should already be a scala "way" or scala function for this. Thank!

+4
source share
3 answers

I don’t know a ready-made way to do this, but so I would do this:

l.groupBy(i => i).mapValues(_.size).maxBy(_._2)._1

Oh, but note that this does not apply when the mode is not unique!

+6
source

This gives you the mode:

import scala.collection.breakOut
import scala.collection.generic.CanBuildFrom
def mode
  [T, CC[X] <: Seq[X]](coll: CC[T])
  (implicit o: T => Ordered[T], cbf: CanBuildFrom[Nothing, T, CC[T]])
  : CC[T] = {
  val grouped = coll.groupBy(x => x).mapValues(_.size).toSeq
  val max = grouped.map(_._2).max
  grouped.filter(_._2 == max).map(_._1)(breakOut)
}
0
source

( RDD):

val grouped = L.groupBy(i => i).map(kv => (kv._1, kv._2.size))
val modeValue = grouped.maxBy(_._2)._2
val modes = grouped.filter(kv => kv._2 == modeValue).map(_._1)
0

All Articles