Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2006
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2006

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

Search the Archive

Re: Sum elements in a list with conditions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg69841] Re: Sum elements in a list with conditions
  • From: "Norbert Marxer" <marxer at mec.li>
  • Date: Mon, 25 Sep 2006 03:53:00 -0400 (EDT)
  • References: <ef5066$mm5$1@smc.vnet.net>

Dear Guillermo

With your data:

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

You can use:

els = Union@Part[Transpose@a, 1]
sel[x_] := Select[a, (#[[1]] == x) &];
Map[sel[#] &, els]
Map[{#[[1, 1]], Total@Transpose[#][[2]]} &, %]

Explanation:

The first line finds the different first elements (e.g. {a1,a2,a3})

The function sel[x_] selects the rows of a which have x as their first
element.

Then the first Map applies this function for the different first
elements:  {a1,a2,a3}

Then the second Map constructs your final matrix with the different
elements in the first column and the sum in the second column.

Best Regards
Norbert Marxer
www.mec.li

Guillermo Sanchez 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: Re: Sum elements in a list with conditions
  • Next by Date: Re: Copying cell contents?
  • Previous by thread: Re: Sum elements in a list with conditions
  • Next by thread: Re: Sum elements in a list with conditions