Re: grouping and averaging {x,y} pairs of data

• To: mathgroup at smc.vnet.net
• Subject: [mg37227] Re: grouping and averaging {x,y} pairs of data
• From: "Allan Hayes" <hay at haystack.demon.co.uk>
• Date: Thu, 17 Oct 2002 00:09:09 -0400 (EDT)
• References: <aokc56\$ah2\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```"David E. Burmaster" <deb at alceon.com> wrote in message
news:aokc56\$ah2\$1 at smc.vnet.net...
> Dear Fellows in MathGroup,
>
> I have a list of 17,000+ {x,y} pairs of data
>
> each x value is a positive integer from 1 to 100+
>
> each y value is a positive real number
>
> As a *short* example, let's consider:
>
>  data = {{3,1},{4,3},{3,2},{1,10},{4,2},{1,6},{5,2},{2,5},{7,1}}
>
> I want to group the data by the x value and report the arithmetic average
> of the y values in each group.
>
> For the example, i want to report:
>
>  output = {{1,8},{2,5},{3,1.5},{4,2.5},{5,2},{6,0},{7,1}}
>
> In this example, x=6 does not occur so i report the average y[6] = 0.
>
> Can anyone suggest a way to do this efficiently?/
>
> many thanks
> dave

Dave,
One way:

data={{3,1},{4,3},{3,2},{1,10},{4,2},{1,6},{5,2},{2,5},{7,1}};

f[x_] = 0;
((f[#1[[1,1]]] = Plus @@ #1[[All,2]]/Length[#1]) & ) /@
Split[Sort[data], #1[[1]] == #2[[1]] & ]

{8, 5, 3/2, 5/2, 2, 1}

Table[f[i], {i, 1, 8}]

{8, 5, 3/2, 5/2, 2, 0, 1, 0}

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

>
>
>
> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> David E. Burmaster, Ph.D.
> Alceon Corporation
> POBox 382069                 (new Box number effective 1 Sep 2001)
> Harvard Square Station
> Cambridge, MA 02238-2069     (new ZIP code effective 1 Sep 2001)
>
> Voice 617-864-4300
>
> Web http://www.Alceon.com
> Email deb at Alceon.com
> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>
>
>
>

```

• Prev by Date: RE: grouping and averaging {x,y} pairs of data
• Next by Date: Re: grouping and averaging {x,y} pairs of data
• Previous by thread: RE: grouping and averaging {x,y} pairs of data
• Next by thread: RE: grouping and averaging {x,y} pairs of data