# second part of a list with something like BinLists

I have a list that looks like this

testList =
Transpose@Table[{RandomInteger[{0, 100}], RandomReal[]}, {100}];


i.e. basically two lists in one. Using BinLists I can bin the values of e.g. the first list.

 BinLists[testList[[1]], {0, 100, 10}]


However, I would like to have the values of the second list in the resulting bin list that correspond to the values of the first list. I hope I make myself clear, otherwise I can make it more clear. I have a solution with a loop which is taking ages, as it is a very large dataset. Thanks!

• Are the binned values (RandomInteger[{0, 100}] in the example) guaranteed to be unique? Dec 3, 2014 at 12:35
• No, that's the problem. Dec 3, 2014 at 15:13

I believe this does what you want. (Note the absence of Transpose before Table.)

SeedRandom[1];

testList = Table[{RandomInteger[{0, 100}], RandomReal[]}, {100}];

BinLists[testList, {0, 100, 10}, {0, 1, 1}][[All, 1]]


The second bin specification {0, 1, 1} simply puts all y values in a single bin, since they all fall in the interval [0, 1].

By the way, sometimes it is both easier an more efficient to roll your own. This is nearly equivalent for the given example and several times faster:

GatherBy[testList, Floor[#[[1]], 10] &] ~SortBy~ First

• Great thanks. Looks good. I have to understand your second approach, though. Dec 3, 2014 at 15:05
• @Mr.Wizard, is it possible to apply similar task, but for bining (or Gathering) in arbitrarily bin widths: eg binning testList2={{"1A",1},{"2A",2}, {"170A",170},{"3A",3}, {"90A",90},{"80A",80},{"2A",2},{"110A",110},{"222A",222},{"200A",200},{"215A",215},{"30A",30}} into bins={{0,20,100,\[Infinity]}} according to 2nd element in sublists as bin criterion? Jul 14, 2016 at 10:56
• @Dragutin I saw your new question and posted an answer. Jul 14, 2016 at 12:04