MathGroup Archive 2012

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Sum elements in a list with conditions


On 10/18/12 at 2:36 AM, guillermo.sanchez at hotmail.com (Guillermo
Sanchez) wrote:

>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}}

Here are a couple of methods

data = {{1, a}, {2, b}, {1, c}, {2, d}, {2, e}, {3, f}};

In[3]:= {#[[1, 1]], Last@Total@#} & /@ GatherBy[data, First]

Out[3]= {{1, a + c}, {2, b + d + e}, {3, f}}

In[4]:= Mean /@ GatherBy[data, First] /. Times[_, a_Plus] -> a

Out[4]= {{1, a + c}, {2, b + d + e}, {3, f}}

The first is likely faster for large data sets




  • Prev by Date: Re: How to make fitting code using NDSolve?
  • Next by Date: Re: Plot in function
  • Previous by thread: Re: Sum elements in a list with conditions
  • Next by thread: Re: Sum elements in a list with conditions