       Re: Sum elements in a list with conditions

• To: mathgroup at smc.vnet.net
• Subject: [mg69846] Re: [mg69828] Sum elements in a list with conditions
• From: Bob Hanlon <hanlonr at cox.net>
• Date: Mon, 25 Sep 2006 03:53:16 -0400 (EDT)
• Reply-to: hanlonr at cox.net

```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[]==#2[]&]

{{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_?(#[]==v[[n]]&):>x[]]},
{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