Re: Sum elements in a list with conditions

• To: mathgroup at smc.vnet.net
• Subject: [mg128453] Re: Sum elements in a list with conditions
• From: Alexei Boulbitch <Alexei.Boulbitch at iee.lu>
• Date: Sat, 20 Oct 2012 00:35:06 -0400 (EDT)
• Delivered-to: l-mathgroup@mail-archive0.wolfram.com
• Delivered-to: l-mathgroup@wolfram.com
• Delivered-to: mathgroup-newout@smc.vnet.net
• Delivered-to: mathgroup-newsend@smc.vnet.net

```I have a list of sublist of pairs. I wish sum the second elements of
the sublists when the first elements are equals
Example:
Int[]:={{1, a}, {2, b}, {1, c}, {2, d}, {2, e}, {3, f}}
I hope
Out[]:= {{1, a + c}, {2, b + c + e}, {3, f}}

I can do it as  is it is shown below but could any body find and
easier solution.

list1 = {{1, a}, {2, b}, {1, c}, {2, d}, {2, e}, {3, f}};
list2 = GatherBy[list1, First];
{l1, l2} = Transpose[Plus @@@ GatherBy[list, First]];
Transpose[{l1/Length /@ list2 , l2}]

Hi, Guillermo,

I do not know, if you consider the following easier or not:

lst = {{1, a}, {2, b}, {1, c}, {2, d}, {2, e}, {3, f}};
test = First[#1] == First[#2] &;
f[x_] := {x[[1, 1]], Total[Transpose[x][[2]]]};

f /@ Split[Sort[lst, test], test]

{{3, f}, {2, b + d + e}, {1, a + c}}

If you want it to go in the growing order, add one more sorting:

Sort[f /@ Split[Sort[lst, test], test], #1[[1]] <= #2[[1]] &]

{{1, a + c}, {2, b + d + e}, {3, f}}

Have fun, Alexei

Alexei BOULBITCH, Dr., habil.
IEE S.A.
ZAE Weiergewan,
11, rue Edmond Reuter,
L-5326 Contern, LUXEMBOURG

Office phone :  +352-2454-2566
Office fax:       +352-2454-3566
mobile phone:  +49 151 52 40 66 44

e-mail: alexei.boulbitch at iee.lu

```

• Prev by Date: Re: Gauss Quadrature
• Next by Date: Using MorphologicalGraph to split an image? (was: "Discovering" a
• Previous by thread: Re: Sum elements in a list with conditions