4
$\begingroup$

Imagine following list

list = {{0, 3}, {1, 1}, {1, 2}, {2, 3}, {2, 4}}

I would like to get the result

{{0, 3}, {1, 3}, {2, 7}}

i.e., grouping by the first element of the tuples in the list, summing the second element of all tuples that share the same first element.

$\endgroup$
  • 2
    $\begingroup$ Try KeyValueMap[List, Total /@ GroupBy[list, First -> Last]]. $\endgroup$ – J. M.'s discontentment May 25 '17 at 16:39
  • 4
    $\begingroup$ @J.M. GroupBy also accepts a reduce argument, even simpler then KeyValueMap[List, GroupBy[list, First -> Last, Total]] $\endgroup$ – swish May 25 '17 at 17:20
  • $\begingroup$ @swish, ah, that's even better! $\endgroup$ – J. M.'s discontentment May 25 '17 at 17:28
  • $\begingroup$ {#1[[1, 1]], Total[#[[2]]]} & /@ Transpose /@ GatherBy[list, First] works in versions older than V10. $\endgroup$ – m_goldberg May 25 '17 at 19:01
  • 1
    $\begingroup$ {#[[1, 1]], Total[#[[All, 2]]]} & /@ GatherBy[list, First] $\endgroup$ – Bob Hanlon May 25 '17 at 19:18
4
$\begingroup$

Summary of the methods given in the comments to the question.

data = {{0, 3}, {1, 1}, {1, 2}, {2, 3}, {2, 4}};

swish (requires V10 or later)

KeyValueMap[List, GroupBy[data, First -> Last, Total]]

m_goldberg (requires V7 or later)

{#1[[1, 1]], Total[#[[2]]]} & /@ Transpose /@ GatherBy[data, First]

Mr.Wizard

Rule @@@ list // Merge[Total] // KeyValueMap[List]

All the above return

{{0, 3}, {1, 3}, {2, 7}}
$\endgroup$

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