I am trying to sum up values of a collection of maps by their common keys. I have this snippet:
(def data [{:a 1 :b 2 :c 3} {:a 1 :b 2 :c 3}]
(for [xs data] (map xs [:a :b]))
((1 2) (1 2))
Final result should be ==> (2 4)
Basically, I have a list of maps. Then I perform a list of comprehension to take only the keys I need.
My question now is how can I now sum up those values? I tried to use "reduce" but it works only over sequences, not over collections.
Thanks.
===EDIT====
Using the suggestion from Joost I came out with this:
(apply merge-with + (for [x data] (select-keys x [:col0 :col1 :col2]))
This iterates a collection and sums on the chosen keys. The "select-keys" part I added is needed especially to avoid to get in trouble when the maps in the collection contain literals and not only numbers.
If you really want to sum the values of the common keys you can do the whole transformation in one step:
(apply merge-with + data)
=> {:a 2, :b 4, :c 6}
To sum the sub sequences you have:
(apply map + '((1 2) (1 2)))
=> (2 4)
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