I am new to Scala and I want to calculate a moving sum with a fixed window for a list.
For example: Given the list values (1.0, 2.0, 3.0, 6.0, 7.0, 8.0, 12.0, 9.0, 4.0, 1.0), and the period 4, the function should return: (1.0, 3.0, 6.0, 12.0, 18.0, 24.0, 33.0, 36.0, 33.0, 26.0)
If list.size < period then just return cumulative sum.
I have made some attempts
def mavg(values: List[Double], period: Int): List[Double] = {
if (values.size <= period) (values.sum ) :: List.fill(period -1)(values.sum ) else {
val rest: List[Double] = mavg(values.tail, period)
(rest.head + ((values.head - values(period)))):: rest
}
}
However, I got
List(12.0, 18.0, 24.0, 33.0, 36.0, 33.0, 26.0, 26.0, 26.0, 26.0
which is not correct. I dont want to use Pyspark to get the results. Can someone help?
Many thanks.
def mavg(values: Seq[Double], period: Int): Seq[Double] = {
(Seq.fill(math.min(period - 1, values.length))(0.0) ++ values) // padding zeros
.sliding(period)
.map(_.sum)
.toSeq
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With