Possible Duplicate:
List-operations only when restrictions are fulfilled (Part 1)

I have a set of data like:

list = {{Tim, 45},{Mary,100},{Tim,500},{Bob,499},{Mary,50}};

I'm looking for a simple way to total the values based off of the name so that the output would look like: {{Tim,545},{Mary,150},{Bob,499}}


marked as duplicate by Mr.Wizard Dec 11 '12 at 19:30

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ I'm sure this is a duplicate (can't find it right now), but a simple way would be to use GatherBy[..., First] //. {h___, {a_, b_}, {a_, c_}, t___} :> {h, {a, b + c}, t} (you might need to flatten appropriately at the end) $\endgroup$ – rm -rf Dec 11 '12 at 18:55
  • $\begingroup$ Gather didn't work...but GatherBy worked just fine . Thanks!! $\endgroup$ – Adriana Dec 11 '12 at 19:08
  • $\begingroup$ Sorry, I meant GatherBy :) I typed quickly off the top of my head and didn't run it in mma. Fixed it now $\endgroup$ – rm -rf Dec 11 '12 at 19:09
  • $\begingroup$ @rm-rf is this it? mathematica.stackexchange.com/q/4332/121 Well, I cannot see how it is not a duplicate so closed as duplicate. $\endgroup$ – Mr.Wizard Dec 11 '12 at 19:30
  • $\begingroup$ @Mr.Wizard Yes, that's the one I was thinking about (this one has the better title though) $\endgroup$ – rm -rf Dec 11 '12 at 20:23

Here is a way to do this in one go:

Reap[Sow @@@ Reverse[list, {2}], _, {#1, Total[#2]} &][[2]]
  • $\begingroup$ Wow that's awesome, thanks! $\endgroup$ – Adriana Dec 11 '12 at 19:17

another way

expr = {{"Tim", 45}, {"Mary", 100}, {"Tim", 500}, {"Bob", 499}, {"Mary", 50}}

b = Gather[expr, First[#1] == First[#2] &]
{First[# [[All,1]] ], Total[# [[All, 2]] ]} & /@ b



Not the answer you're looking for? Browse other questions tagged or ask your own question.