5
$\begingroup$

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!

$\endgroup$
  • $\begingroup$ Are the binned values (RandomInteger[{0, 100}] in the example) guaranteed to be unique? $\endgroup$ – Aisamu Dec 3 '14 at 12:35
  • $\begingroup$ No, that's the problem. $\endgroup$ – Mockup Dungeon Dec 3 '14 at 15:13
6
$\begingroup$

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
$\endgroup$
  • $\begingroup$ Great thanks. Looks good. I have to understand your second approach, though. $\endgroup$ – Mockup Dungeon Dec 3 '14 at 15:05
  • $\begingroup$ @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? $\endgroup$ – Dragutin Jul 14 '16 at 10:56
  • 1
    $\begingroup$ @Dragutin I saw your new question and posted an answer. $\endgroup$ – Mr.Wizard Jul 14 '16 at 12:04

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.