Hi
How to transform this
for (w <- m ){
val w = (w._2.collect {
case x if (x._2 > 0) => x._2;
case x if (x._2 < 0) => x._2 }) // if I add here .sum i got sum of (negative and positive) together
}
to get sum of positive and sum of negative values in one collect, it could be List(positive.sum,negative.sum) or two values
edit:
only groupby, slice, collect, sum and yield
I wrote working program, but it' was not acepted, beacause it doing two collect
val m = d.groupBy(_._1.slice(0, 7))
for (w<- m) {
val x = (w._2.collect { case x if (x._2> 0) => x._2 }).sum
val y = (w._2.collect { case x if (x._2< 0) => x._2 }).sum
println("%7s %11.2f %11.2f %11.2f" format(w._1 , x , y ,(x+y)))
}
}
entry data are
val d = List(("2011-01-04", -137.76),
("2011-01-04", 2376.45),
("2011-01-04", -1.70),
("2011-01-04", -1.70),
("2011-01-04", -1.00),
("2011-01-06", 865.70),
("2011-01-07", -734.15),
("2011-01-05", -188.63),
("2011-01-06", -73.50),
("2011-01-07", -200.00),
("2011-01-09", -215.35),
("2011-01-09", -8.86),
("2011-01-09", -300.00),
("2011-01-11", -634.54),
("2011-01-11", -400.00),
("2011-01-12", -92.87),
("2011-01-13", -1839.24),
("2011-01-13", 10000.00),
("2011-01-13", -10000.00),
("2011-01-15", -127.97),
("2011-01-15", -319.02),
("2011-01-19", -549.00),
("2011-01-21", -164.80),
("2011-01-23", -500.00),
("2011-01-25", -377.97),
("2011-01-26", 2158.66),
("2011-01-26", -130.45),
("2011-01-27", -350.00),
("2011-01-29", -500.00),
("2011-02-01", 2376.45),
("2011-02-01", 955.00))
I recognise this homework 🙂
So it looks like m is a
Map, and you don’t much care about the keys in the output (perhaps you already used filterKeys by this point), so probably easiest to just pull out the values then filter – avoid all those tedious tuples and their underscores…Or if you prefer, this can be tidied up (and made more efficient) using the
partitionmethod:or even use the co-called “point free” style, but that might be pushing it too far:
You shouldn’t have any problem now figuring out what to do with
positivesandnegatives