Re: Summing list subsets
- To: mathgroup at smc.vnet.net
- Subject: [mg30744] Re: Summing list subsets
- From: "Allan Hayes" <hay at haystack.demon.co.uk>
- Date: Sun, 9 Sep 2001 03:26:38 -0400 (EDT)
- References: <9ncfgn$prb$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Mark, Two suggestions: This is the most versatile, allowing for arbitrary ordering and zeros and cancelation in y. x = {a,b,b,b,b,c,d,d,d,d,d,e,f,a}; y = {1,2,2,2,2,3,4,4,4,4,4,1,0,-1}; Aggregate[x_,y_, F_]:= Apply[ {First[#1],F@@#2}& , Transpose/@ Split[ Sort[Transpose[{x,y}]], First[#1]== First[#2]& ] , {1} ] Aggregate[x,y,F] {{a,F[-1,1]},{b,F[2,2,2,2]},{c,F[3]},{d,F[4,4,4,4,4]},{e,F[1]},{f,F[0]}} This is quicker for your particular example, but does not allow for zeros and cancellation in the Replace[ Tr[x y]/.z_Plus:>List@@z, x_. y_Symbol:> {x,y}, {1} ] {{8,b},{3,c},{20,d},{1,e}} -- Allan --------------------- Allan Hayes Mathematica Training and Consulting Leicester UK www.haystack.demon.co.uk hay at haystack.demon.co.uk Voice: +44 (0)116 271 4198 Fax: +44 (0)870 164 0565 "Mark Coleman" <mcoleman at bondspace.com> wrote in message news:9ncfgn$prb$1 at smc.vnet.net... > Greetings: > > Consider two lists: > > x = {a,a,b,b,b,b,c,d,d,d,d,d,} and y = {1,1,2,2,2,2,3,4,4,4,4,4} > > I would like to have a function that returns the sum (or any other function) > of each unique element of x, given the corresponding value in y. That is, > for a 'Sum', the result would be > > z={{a,2},{b,8},{c,3},{d,20}} > > This is similar in spirit to a common database aggregation problem. > > Any ideas? > > Thanks. > > -Mark > >