1
$\begingroup$

Imagine I have the following list

l = {{1, 2}, {1, 3}, {2, 4}, {2, 2}, {2, 3}}

I want to take the mean only regarding the second element. That is, I want to find the coordinates of the points corresponding to

{{1, 2.5}, {2, 3}}

What is the easiest way to achieve this? In other words, how can I easily compute the mean points (in red) from a list of coordinates

enter image description here

My approach: Mean /@ Split[Sort@l, Last[#2] >= Last[#1] &]. Could this be improved?

$\endgroup$
1
  • 4
    $\begingroup$ Mean /@ GatherBy[alist, First] ? (where alist is the list in the OP. l is hard to read. $\endgroup$
    – Syed
    Nov 7, 2022 at 17:03

1 Answer 1

1
$\begingroup$

Given

alist = {{1, 2}, {1, 3}, {2, 4}, {2, 2}, {2, 3}}

then

groupedMeans = GroupBy[alist, First -> Last, Mean]

gives

<|1 -> 5/2, 2 -> 3|>

To recover the data as coordinates, you could do this:

KeyValueMap[List, groupedMeans]

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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