Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question already has an answer here:

This seems like the sort of thing where Mathematica can give a very simple solution.

I have a list of points {x,y}:

{{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 5}}

From this list, I want to generate a new list of pairs {x,ymean}, where ymean is the average of all y's in the original list which were paired to the same value of x:

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

What's the simplest, most elegant way to accomplish this in Mathematica?

share|improve this question

marked as duplicate by Artes, Jens, Mr.Wizard May 15 at 22:16

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
Something involving GatherBy[list, First], I expect. –  Rahul Narain May 15 at 18:19

2 Answers 2

up vote 7 down vote accepted

Assuming you have your 2D list in a variable named lis, then the following should work:

Mean /@ GatherBy[lis, First]
share|improve this answer
    
+1 I knew my solution was too complicated... –  becko May 15 at 18:32
Replace[GatherBy[data, First], d_List :> {First@First@d, Mean[d[[All, 2]]]}, {1}]

where data is the original list of points.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.