MathGroup Archive 2006

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

Search the Archive

Re: Sum elements in a list with conditions


data={{a1, b1},{a2,b2},{a2,b3},
      {a2,b4},{a3, b5}, {a3, b6}};

The first two methods assume that your data is sorted/clustered by the first element (if not, sort first):

{#[[1,1]],Plus@@#[[All,2]]}&/@
  Split[data,#1[[1]]==#2[[1]]&]

{{a1, b1}, {a2, b2 + b3 + b4}, {a3, b5 + b6}}

data//.{s___,{x_,y_},{x_,z_},r___}:>
    {s,{x,y+z},r}

{{a1, b1}, {a2, b2 + b3 + b4}, {a3, b5 + b6}}

Module[{v=Union[data[[All,1]]]},
  Table[{v[[n]],
      Plus@@Cases[data,x_?(#[[1]]==v[[n]]&):>x[[2]]]},
    {n,Length[v]}]]

{{a1, b1}, {a2, b2 + b3 + b4}, {a3, b5 + b6}}

%==%%==%%%

True


Bob Hanlon

---- Guillermo Sanchez <guillermo.sanchez at hotmail.com> wrote: 
> Dear group
> I have a pair of elements list. The second elements of the list should
> be summed when the first element of the pairs are equals. Example
> 
> Given
> 
> {{a1, b1},{a2,b2},{a2,b3},{a2,b4},{a3, b5}, {a3, b6}}
> 
> the output should be
> 
> {{a1, b1},{a2, b2+b3+b4},{a3, b5+b6}}
> 
> Thanks 
> 
> Guillermo
> 


  • Prev by Date: linear secod order homogeneous differential equation recursions
  • Next by Date: Re: DSolve fails with Telegraph equation
  • Previous by thread: Re: Sum elements in a list with conditions
  • Next by thread: Re: Sum elements in a list with conditions