MathGroup Archive 2012

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

Search the Archive

Re: Sum elements in a list with conditions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg128434] Re: Sum elements in a list with conditions
  • From: Bill Rowe <readnews at sbcglobal.net>
  • Date: Fri, 19 Oct 2012 02:42:23 -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

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