TransWikia.com

Gather all elements in a list of floats into groups defined by a list of ranges?

Mathematica Asked on December 8, 2020

A similar question regarding integer numbers was asked and answered here. However, since all the solutions there rely on generating the full set of numbers in the process of grouping them, which is not feasible in the case of floating point numbers, I’m asking the below question.

Consider a list of measurements {x,y} of some sorts, where x is a positive, monotonously increasing floating point number, for example:

list = {{1.1,2},{2.3,4},{4.5,5},{6.2,7},{8.3,8},{9.5,8}};

we also have a list of boundaries in x-space between which we would like to group the readings in list

boundaries = {1,5,7,10};

This particular list of boundaries tells us that we would like to group measurements in list for x-values between 1 and 5, between 5 and 7, and between 7 and 10. I would like to have a function group that does this:

group[list,boundaries]

{ {{1.1,2},{2.3,4},{4.5,5}} , {{6.2,7}} , {{8.3,8},{9.5,8}} }

Does Mathematica have such a function group, or maybe one can implement it efficiently?
Of course, I could hack together a super ugly loop that would iterate through each element and append elements appropriately — however, I’m wondering if there is a better, more efficient solution one could achieve through smarter Mathematica functions?

One Answer

1. BinLists

grouP = Join @@ BinLists[#, {#2}, {{-∞, ∞}}] &;

grouP[list, boundaries]
 {{{1.1, 2}, {2.3, 4}, {4.5, 5}}, {{6.2, 7}}, {{8.3, 8}, {9.5, 8}}}

2. GatherBy

grouP2 = GatherBy[SortBy[First]@#, Function[x, Total[UnitStep[x[[1]] - #2]]]] &;

grouP2[list, boundaries]
 {{{1.1, 2}, {2.3, 4}, {4.5, 5}}, {{6.2, 7}}, {{8.3, 8}, {9.5, 8}}}

3. SplitBy

grouP3 = SplitBy[SortBy[First]@#, Function[x, Total[UnitStep[x[[1]] - #2]]]] &;

grouP3[list, boundaries]
 {{{1.1, 2}, {2.3, 4}, {4.5, 5}}, {{6.2, 7}}, {{8.3, 8}, {9.5, 8}}}

4. GroupBy

grouP4 = Values @ GroupBy[SortBy[First]@#, 
     Function[x, Total[UnitStep[x[[1]] - #2]]]] &;

grouP4[list, boundaries]
 {{{1.1, 2}, {2.3, 4}, {4.5, 5}}, {{6.2, 7}}, {{8.3, 8}, {9.5, 8}}}

Correct answer by kglr on December 8, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP