Scala: summary values ​​for key based arrays

Scala is a very newbie programmer, so hopefully it's pretty simple.

I have an array of tuples that looks like this:

Array((1,Array(1.0,0.0,5.2,0.0), 
      (1,Array(1.0,0.0,6.3,0.0),
      (2,Array(0.0,1.0,0.0,1.2),
      (2,Array(0.0,1.0,0.0,2.5))

I want to summarize the corresponding values ​​in the second part of the tuple based on the key in the first. Thus, the result will look like this:

Array((1,(2.0,0.0,11.5,0.0),
      (2,(0.0,2.0,0.0,3.7))

The function I came with is:

def sumByKeys[A](tuples: Array[(String, Array[Double])]) = {
    tuples.groupBy(_._1).mapValues(_.map(_._2).sum)
}

The error I get is

error: could not find implicit value for parameter num: Numeric[Array[Double]]
       tuples.groupBy(_._1).mapValues(_.map(_._2).sum)
                                                  ^

I hope this is something simple when I just messed with data types.

Thank.

+4
source share
1 answer
scala> a.groupBy(_._1).mapValues(_.map(_._2).transpose.map(_.sum)).toArray
res2: Array[(Int, Array[Double])] = Array((2,Array(0.0, 2.0, 0.0, 3.7)),
                                          (1,Array(2.0, 0.0, 11.5, 0.0)))
+4
source

All Articles