J  Calbreath
J Calbreath

Reputation: 2705

Scala: Sum values across arrays based on key

Very novice Scala programmer so hopefully this is 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 sum up the corresponding values in the second part of the tuple based on the key in the first. So the result would 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 up with is:

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

There error I get is

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

I'm hoping this is something simple where I am just messing up the data types.

Thanks.

Upvotes: 4

Views: 780

Answers (1)

Marth
Marth

Reputation: 24802

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)))

Upvotes: 4

Related Questions