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.

I have a list of points:

points={{3, 0}, {3, 9}, {4, 2}, {5, 5}, {6, 9}, {6, 6}, {6, 1}, {7, 7}, {8,0}, {8, 10}};

enter image description here

And as you can see on the plot, there are some values of x that appear more than once.

I want to accumulate the ones that are at the same value of x, so the final result should look like this:

enter image description here

I tried using

points[[All,1]]//Split

To get

{{3, 3}, {4}, {5}, {6, 6, 6}, {7}, {8, 8}}

But I don't know where to go after that, furthermore, I'm fairly sure this is not the right way to approach this problem.

share|improve this question

marked as duplicate by Kuba, Yves Klett, m_goldberg, Simon Woods, Rahul Narain Mar 9 at 21: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.

2 Answers 2

up vote 4 down vote accepted

Works just fine for a few points:

acc = points //. {a___, {x_, y1_}, {x_, y2_}, 
    b___} :> {a, {x, y1 + y2}, b}

{{3, 9}, {4, 2}, {5, 5}, {6, 16}, {7, 7}, {8, 10}}

More efficient:

acc = Plus @@ #/{Length[#], 1} & /@ GatherBy[points, First]

{{3, 9}, {4, 2}, {5, 5}, {6, 16}, {7, 7}, {8, 10}}

ListLinePlot[acc]

Mathematica graphics

share|improve this answer
f[{a_, b_}] := {First@a, Tr@b}
f /@ Transpose /@ GatherBy[points, First]

Edit Probably much faster:

s[points_] := Module[{p = points, f},
  f[_] = 0;
  Scan[f@#[[1]] += #[[2]] &, p];
  f
  ]
k = s[points];
ListLinePlot[{#, k@#} & /@ points[[All, 1]]]

Mathematica graphics

share|improve this answer
    
@Kuba done :),thanks –  belisarius Mar 9 at 21:18
    
@Kuba I ommited the part that's practically the same as your answer there :) –  belisarius Mar 9 at 21:23
    
I've seen :) +1ed there :) –  Kuba Mar 9 at 21:25

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