Update: Using BinLists
as the third argument of HistogramList
to get both bin limits and the contents of each bin and organizing the results:
ClearAll[binListsAndLims, binListsAndLimsByCol, oneBin]
oneBin = Floor[Max[#] + #2, #2] - Ceiling[Min[#] - #2, #2] + 2 #2 &;
binListsAndLims[d_, bspec_] := Module[{b = ReplacePart[{oneBin[#, 1]} & /@ Transpose[d],
(-1) -> bspec]},
Thread /@ (Transpose[{#2[[## &@@ConstantArray[1, Length[b] - 1]]], Most[#[[-1]]]}] & @@
HistogramList[d, b, BinLists[d, ## & @@ Function[t, {#[[t]]}] /@ Range[Length@b]] &] /.
{} -> {{}})]
binListsAndLimsByCol[d_, bspec_, col_] := Module[{r = Length[d[[1]]] - col},
If[col == Length[d[[1]]], binListsAndLims[d, bspec],
Replace[binListsAndLims[RotateRight[#, r] & /@ d,
bspec], {a_List, b_} :> {RotateLeft[a, r], b}, {0, Infinity}]]]
Examples:
binListsAndLimsByCol[listA, {1}, 2]
{{{{}, 0}},
{{{1, 1}, 1}, {{3, 1}, 1}, {{6, 1}, 1}},
{{{2, 2}, 2}, {{4, 2}, 2}, {{7, 2}, 2}},
{{{5, 3}, 3}},
{{{}, 4}},
{{{10, 5}, 5}},
{{{9, 6}, 6}},
{{{8, 7}, 7}}}
Use a different bin spec:
binListsAndLimsByCol[listA, {.5}, 2]
{{{{}, 0.5}}, {{{1, 1}, 1.}, {{3, 1}, 1.}, {{6, 1}, 1.}}, {{{},
1.5}}, {{{2, 2}, 2.}, {{4, 2}, 2.}, {{7, 2}, 2.}}, {{{},
2.5}}, {{{5, 3}, 3.}}, {{{}, 3.5}}, {{{}, 4.}}, {{{},
4.5}}, {{{10, 5}, 5.}}, {{{}, 5.5}}, {{{9, 6}, 6.}}, {{{},
6.5}}, {{{8, 7}, 7.}}}
Bin by column 1:
binListsAndLimsByCol[listA, {1}, 1]
{{{{}, 0}}, {{{1, 1}, 1}}, {{{2, 2}, 2}}, {{{3, 1}, 3}}, {{{4, 2},
4}}, {{{5, 3}, 5}}, {{{6, 1}, 6}}, {{{7, 2}, 7}}, {{{8, 7},
8}}, {{{9, 6}, 9}}, {{{10, 5}, 10}}}
With more than 2 columns:
SeedRandom[12345]
dd = RandomInteger[{1, 9}, {20, 4}];
binListsAndLimsByCol[dd, {1}, 2]
{{{{}, 0}}, {{{2, 1, 9, 2}, 1}, {{4, 1, 3, 7}, 1}, {{2, 1, 1, 7},
1}}, {{{6, 2, 4, 2}, 2}}, {{{8, 3, 8, 9}, 3}, {{7, 3, 8, 7},
3}, {{6, 3, 7, 8}, 3}, {{7, 3, 5, 2}, 3}}, {{{9, 4, 4, 8},
4}, {{3, 4, 4, 9}, 4}}, {{{6, 5, 8, 6}, 5}, {{2, 5, 6, 1},
5}, {{9, 5, 6, 7}, 5}}, {{{}, 6}}, {{{8, 7, 9, 6},
7}, {{2, 7, 5, 9}, 7}}, {{{4, 8, 4, 7}, 8}, {{8, 8, 3, 9},
8}, {{9, 8, 9, 7}, 8}}, {{{7, 9, 7, 2}, 9}, {{4, 9, 4, 5}, 9}}}
Original answer:
Table[Thread[{Pick[#, #[[All, 2]], i] /. {} -> {{}}, i}], {i, 0, Max[#[[All, 2]]]}]&@listA
{{{}, 0}, {{{1, 1}, 1}, {{3, 1}, 1}, {{6, 1}, 1}}, {{{2, 2},
2}, {{4, 2}, 2}, {{7, 2}, 2}}, {{{5, 3}, 3}}, {{},
4}, {{{10, 5}, 5}}, {{{9, 6}, 6}}, {{{8, 7}, 7}}}
If you have to use BinLists
as input:
bl = MapIndexed[If[# == {} , #2[[1]] - 1, #]&, BinLists[listA[[All, 2]], 1]]
pick = Pick[listA, listA[[All, 2]], #] & /@ Range[0, Max[listA[[All, 2]]]]
thread = If[Head[#[[2]]] === List, Thread @ #, #]&;
thread /@ Transpose @ {pick, bl}
same result
1
ton
? And would something likeGroupBy[listA, Last]
work for you? The output format is slightly different, but should be able to easily extract everything from there. If this is not good enough, can you explain what exactly you need to do with the list afterwards? Your output format seems quite complicated... $\endgroup$