MathGroup Archive 1998

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

Search the Archive

Re: Summing over like elements

  • To: mathgroup at
  • Subject: [mg13863] Re: [mg13855] Summing over like elements
  • From: Carl Woll <carlw at>
  • Date: Wed, 2 Sep 1998 01:30:58 -0400
  • Sender: owner-wri-mathgroup at

Hi Mitchell,

There are many ways to tackle this kind of problem. Here is one idea,
which is hopefully pretty efficient. We'll see how it manages against
ideas from other posters.

First, I'll define a function which takes as an argument a list of your
pairs which have the same first value, and returns a pair with the
second values summed.

Combine[{a_}] := a
Combine[a] := {a[[1,1]], Plus@@Last/@a}

So, as a check, we should have

Combine[ {{1,.3}} ]


Combine[ {{1,.3},{1,.4}} ]

Now, we sort your list, and then split it up into sets with common first
values. If data is your list, then

Split[Sort[data], First[#1]==First[#2]& ]

will do that. Mapping the function Combine onto this list will give you
what you want. So, the complete function, which I will call Tally, is

Tally[data_] := Combine /@ Split[Sort[data], First[#1]==First[#2]&]
Combine[{a_}] := a
Combine[a] := {a[[1,1]], Plus@@Last/@a}

Good luck!

Carl Woll
Dept of Physics
U of Washington

On Mon, 31 Aug 1998, Mitchell Kaplan wrote:

> I have a 2 column array.  Column 1 has some values, many of which are
> repeated.  Column 2 has probabilities of these values.
> I would like to sum the probabilities for each unique element in column
> 1. For example:
> {{1, .5} , {2, .2} , {1, .1}}  should give me:
> {{1, .6} , {2, .2}}
> I'm sure I can do this with a "Do" loop -- however it seems that in
> general "Do's" are pretty innefficient.
> Does anyone have any suggestions?
>                 Mitch

  • Prev by Date: how can i save a text from noteboook ?
  • Next by Date: Re: Summing over like elements
  • Previous by thread: Re: Summing over like elements
  • Next by thread: Re: Summing over like elements