Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: summing values in a collection of maps

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.

like image 238
kfk Avatar asked Dec 22 '22 07:12

kfk


1 Answers

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)
like image 154
Joost Diepenmaat Avatar answered Jan 09 '23 07:01

Joost Diepenmaat