MathGroup Archive 2001

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

Search the Archive

Re: Summing list subsets

  • To: mathgroup at smc.vnet.net
  • Subject: [mg30749] Re: [mg30711] Summing list subsets
  • From: BobHanlon at aol.com
  • Date: Sun, 9 Sep 2001 03:26:47 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

In a message dated 2001/9/8 3:15:03 AM, mcoleman at bondspace.com writes:

>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.
>

x = {a,a,b,b,b,b,c,d,d,d,d,d};
y = {1,1,2,2,2,2,3,4,4,4,4,4};

f[func_, x_?VectorQ, y_?VectorQ] := 
    {#, func[Sequence@@(Cases[x, #] /. 
                    Union[Thread[x :> y]])]}& /@  
        Union[x] /; Length[x] == Length[y] && 
        Length[Union[x]] == Length[Union[Thread[x :> y]]];

f[Plus, x, y]

{{a, 2}, {b, 8}, {c, 3}, {d, 20}}

f[Times, x, y]

{{a, 1}, {b, 16}, {c, 3}, {d, 1024}}


Bob Hanlon
Chantilly, VA  USA


  • Prev by Date: Re: Summing list subsets
  • Next by Date: Re: Summing list subsets
  • Previous by thread: Re: Summing list subsets
  • Next by thread: Re: Summing list subsets