Let's say I have a list like this:
data = {{21, "Alice"}, {27, "Bob"}, {22, "Charles"}, {34, "Dora"}, {75, "Eliza"}}
containing ages and names of persons. What I would like is a list of e.g. 10-year age brackets, containing a list of {age,name}-pairs:
{
{{21, "Alice"}, {27, "Bob"}, {22, "Charles"}}, (* 20-30 years *)
{{34, "Dora"}}, (* 30-40 years *)
{}, (* 40-50 years *)
{}, (* 50-60 years *)
{}, (* 60-70 years *)
{{75, "Eliza"}} (* 70-80 years *)
}
GatherBy[data, Floor[First[#]/10]&]
is close, but it leaves out empty bins.
BinLists[data[[All, 1]], 10]
is also similar, but it only returns the list of ages, I can't get it to include the names as well.
Ideally, I'd like to have a function with similar syntax and performance to BinLists
, i.e.: binListsBy[data, {10,70,10}, First]
. And the function should be fast, because I'm going to use it on millions of entries (pixels of an image, in fact).
(Following Mr.Wizard's meta discussion, I'm not going to add "what have I tried" in my question - I'm really looking for better ideas, or maybe even a built-in function I haven't noticed. Instead I'll post my attempts as an answer.)
Tally
much as my answer here does withGatherBy
. $\endgroup$